code
stringlengths
82
54.1k
code_codestyle
int64
0
699
style_context
stringlengths
111
35.6k
style_context_codestyle
int64
0
699
label
int64
0
1
import json import os import re import sys import urllib.request import requests from bsa import BeautifulSoup SCREAMING_SNAKE_CASE__ : Union[str, Any] = { """User-Agent""": """Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36""" """ (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582""" } def __lowercase ( snake_case = "dhaka", snake_case = 5 ): """simple docstring""" __magic_name__ :List[str] = min(snake_case, 5_0 ) # Prevent abuse! __magic_name__ :List[str] = { '''q''': query, '''tbm''': '''isch''', '''hl''': '''en''', '''ijn''': '''0''', } __magic_name__ :Union[str, Any] = requests.get('''https://www.google.com/search''', params=snake_case, headers=snake_case ) __magic_name__ :int = BeautifulSoup(html.text, '''html.parser''' ) __magic_name__ :int = ''''''.join( re.findall(R'''AF_initDataCallback\(([^<]+)\);''', str(soup.select('''script''' ) ) ) ) __magic_name__ :List[Any] = json.dumps(snake_case ) __magic_name__ :str = json.loads(snake_case ) __magic_name__ :Dict = re.findall( R'''\[\"GRID_STATE0\",null,\[\[1,\[0,\".*?\",(.*),\"All\",''', snake_case, ) if not matched_google_image_data: return 0 __magic_name__ :Dict = re.sub( R'''\[\"(https\:\/\/encrypted-tbn0\.gstatic\.com\/images\?.*?)\",\d+,\d+\]''', '''''', str(snake_case ), ) __magic_name__ :Union[str, Any] = re.findall( R'''(?:\'|,),\[\"(https:|http.*?)\",\d+,\d+\]''', snake_case, ) for index, fixed_full_res_image in enumerate(snake_case ): if index >= max_images: return index __magic_name__ :Tuple = bytes(snake_case, '''ascii''' ).decode( '''unicode-escape''' ) __magic_name__ :Union[str, Any] = bytes(snake_case, '''ascii''' ).decode( '''unicode-escape''' ) __magic_name__ :List[str] = urllib.request.build_opener() __magic_name__ :Tuple = [ ( '''User-Agent''', '''Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36''' ''' (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582''', ) ] urllib.request.install_opener(snake_case ) __magic_name__ :Any = f'''query_{query.replace(" ", "_" )}''' if not os.path.exists(snake_case ): os.makedirs(snake_case ) urllib.request.urlretrieve( # noqa: S310 snake_case, f'''{path_name}/original_size_img_{index}.jpg''' ) return index if __name__ == "__main__": try: SCREAMING_SNAKE_CASE__ : Union[str, Any] = download_images_from_google_query(sys.argv[1]) print(f"{image_count} images were downloaded to disk.") except IndexError: print("""Please provide a search term.""") raise
0
from __future__ import annotations import unittest from transformers import AutoTokenizer, PegasusConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFPegasusForConditionalGeneration, TFPegasusModel @require_tf class _lowerCAmelCase: """simple docstring""" a : int =PegasusConfig a : List[str] ={} a : Optional[int] ='''gelu''' def __init__( self , _lowerCamelCase , _lowerCamelCase=1_3 , _lowerCamelCase=7 , _lowerCamelCase=True , _lowerCamelCase=False , _lowerCamelCase=9_9 , _lowerCamelCase=3_2 , _lowerCamelCase=2 , _lowerCamelCase=4 , _lowerCamelCase=3_7 , _lowerCamelCase=0.1 , _lowerCamelCase=0.1 , _lowerCamelCase=4_0 , _lowerCamelCase=2 , _lowerCamelCase=1 , _lowerCamelCase=0 , ): UpperCamelCase_: List[Any] = parent UpperCamelCase_: Dict = batch_size UpperCamelCase_: List[str] = seq_length UpperCamelCase_: List[str] = is_training UpperCamelCase_: Any = use_labels UpperCamelCase_: Optional[Any] = vocab_size UpperCamelCase_: Tuple = hidden_size UpperCamelCase_: List[Any] = num_hidden_layers UpperCamelCase_: Any = num_attention_heads UpperCamelCase_: Optional[Any] = intermediate_size UpperCamelCase_: Optional[int] = hidden_dropout_prob UpperCamelCase_: int = attention_probs_dropout_prob UpperCamelCase_: Union[str, Any] = max_position_embeddings UpperCamelCase_: Dict = eos_token_id UpperCamelCase_: Union[str, Any] = pad_token_id UpperCamelCase_: List[Any] = bos_token_id def _a ( self ): UpperCamelCase_: Union[str, Any] = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) UpperCamelCase_: int = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) UpperCamelCase_: List[str] = tf.concat([input_ids, eos_tensor] , axis=1 ) UpperCamelCase_: Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase_: Tuple = 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 , ) UpperCamelCase_: Optional[Any] = prepare_pegasus_inputs_dict(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) return config, inputs_dict def _a ( self , _lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: Optional[Any] = TFPegasusModel(config=_lowerCamelCase ).get_decoder() UpperCamelCase_: Optional[int] = inputs_dict['input_ids'] UpperCamelCase_: Optional[int] = input_ids[:1, :] UpperCamelCase_: int = inputs_dict['attention_mask'][:1, :] UpperCamelCase_: Optional[int] = inputs_dict['head_mask'] UpperCamelCase_: Optional[int] = 1 # first forward pass UpperCamelCase_: Union[str, Any] = model(_lowerCamelCase , attention_mask=_lowerCamelCase , head_mask=_lowerCamelCase , use_cache=_lowerCamelCase ) UpperCamelCase_ ,UpperCamelCase_: int = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids UpperCamelCase_: int = ids_tensor((self.batch_size, 3) , config.vocab_size ) UpperCamelCase_: List[Any] = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and UpperCamelCase_: Union[str, Any] = tf.concat([input_ids, next_tokens] , axis=-1 ) UpperCamelCase_: int = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) UpperCamelCase_: Any = model(_lowerCamelCase , attention_mask=_lowerCamelCase )[0] UpperCamelCase_: int = model(_lowerCamelCase , attention_mask=_lowerCamelCase , past_key_values=_lowerCamelCase )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice UpperCamelCase_: Optional[int] = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) UpperCamelCase_: Any = output_from_no_past[:, -3:, random_slice_idx] UpperCamelCase_: Union[str, Any] = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(_lowerCamelCase , _lowerCamelCase , rtol=1e-3 ) def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__=None , UpperCAmelCase__=None , UpperCAmelCase__=None , UpperCAmelCase__=None , UpperCAmelCase__=None , ) -> str: if attention_mask is None: UpperCamelCase_: Optional[Any] = tf.cast(tf.math.not_equal(UpperCAmelCase__ , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: UpperCamelCase_: int = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: UpperCamelCase_: str = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: UpperCamelCase_: Any = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: UpperCamelCase_: int = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class _lowerCAmelCase( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase ): """simple docstring""" a : Tuple =(TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else () a : int =(TFPegasusForConditionalGeneration,) if is_tf_available() else () a : Tuple =( { '''conversational''': TFPegasusForConditionalGeneration, '''feature-extraction''': TFPegasusModel, '''summarization''': TFPegasusForConditionalGeneration, '''text2text-generation''': TFPegasusForConditionalGeneration, '''translation''': TFPegasusForConditionalGeneration, } if is_tf_available() else {} ) a : List[str] =True a : List[str] =False a : Tuple =False def _a ( self ): UpperCamelCase_: Dict = TFPegasusModelTester(self ) UpperCamelCase_: Any = ConfigTester(self , config_class=_lowerCamelCase ) def _a ( self ): self.config_tester.run_common_tests() def _a ( self ): UpperCamelCase_: Any = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*_lowerCamelCase ) @require_sentencepiece @require_tokenizers @require_tf class _lowerCAmelCase( unittest.TestCase ): """simple docstring""" a : Dict =[ ''' 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!" ''', ] a : int =[ '''California\'s largest electricity provider has cut power to hundreds of thousands of customers in an effort to''' ''' reduce the risk of wildfires.''', '''N-Dubz have revealed they\'re "grateful" to have been nominated for four Mobo Awards.''', ] # differs slightly from pytorch, likely due to numerical differences in linear layers a : Union[str, Any] ='''google/pegasus-xsum''' @cached_property def _a ( self ): return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def _a ( self ): UpperCamelCase_: Optional[Any] = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def _a ( self , **_lowerCamelCase ): UpperCamelCase_: Dict = self.translate_src_text(**_lowerCamelCase ) assert self.expected_text == generated_words def _a ( self , **_lowerCamelCase ): UpperCamelCase_: Union[str, Any] = self.tokenizer(self.src_text , **_lowerCamelCase , padding=_lowerCamelCase , return_tensors='tf' ) UpperCamelCase_: Any = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=_lowerCamelCase , ) UpperCamelCase_: str = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=_lowerCamelCase ) return generated_words @slow def _a ( self ): self._assert_generated_batch_equal_expected()
57
0
import unittest import numpy as np import torch from .utils_summarization import build_mask, compute_token_type_ids, process_story, truncate_or_pad class __lowerCamelCase (unittest.TestCase ): def snake_case_ ( self: List[Any] ): '''simple docstring''' __UpperCamelCase = 10 def snake_case_ ( self: Optional[Any] ): '''simple docstring''' __UpperCamelCase = [1, 2, 3, 4] __UpperCamelCase = [1, 2, 3, 4, 0, 0, 0, 0, 0, 0] self.assertEqual(truncate_or_pad(A_,self.block_size,0 ),A_ ) def snake_case_ ( self: Optional[int] ): '''simple docstring''' __UpperCamelCase = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] __UpperCamelCase = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] self.assertEqual(truncate_or_pad(A_,self.block_size,0 ),A_ ) def snake_case_ ( self: Dict ): '''simple docstring''' __UpperCamelCase = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] __UpperCamelCase = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] self.assertEqual(truncate_or_pad(A_,self.block_size,0 ),A_ ) def snake_case_ ( self: str ): '''simple docstring''' __UpperCamelCase = 'It was the year of Our Lord one thousand seven hundred and\n seventy-five.\n\nSpiritual revelations were conceded to England at that\n favoured period, as at this.' __UpperCamelCase, __UpperCamelCase = process_story(A_ ) self.assertEqual(A_,[] ) def snake_case_ ( self: Optional[int] ): '''simple docstring''' __UpperCamelCase = '' __UpperCamelCase, __UpperCamelCase = process_story(A_ ) self.assertEqual(A_,[] ) self.assertEqual(A_,[] ) def snake_case_ ( self: List[str] ): '''simple docstring''' __UpperCamelCase = ( 'It was the year of Our Lord one thousand seven hundred and ' 'seventy-five\n\nSpiritual revelations were conceded to England ' 'at that favoured period, as at this.\n@highlight\n\nIt was the best of times' ) __UpperCamelCase, __UpperCamelCase = process_story(A_ ) __UpperCamelCase = [ 'It was the year of Our Lord one thousand seven hundred and seventy-five.', 'Spiritual revelations were conceded to England at that favoured period, as at this.', ] self.assertEqual(A_,A_ ) __UpperCamelCase = ['It was the best of times.'] self.assertEqual(A_,A_ ) def snake_case_ ( self: str ): '''simple docstring''' __UpperCamelCase = torch.tensor([1, 2, 3, 4] ) __UpperCamelCase = torch.tensor([1, 1, 1, 1] ) np.testing.assert_array_equal(build_mask(A_,0 ).numpy(),expected.numpy() ) def snake_case_ ( self: str ): '''simple docstring''' __UpperCamelCase = torch.tensor([1, 2, 3, 4, 23, 23, 23] ) __UpperCamelCase = torch.tensor([1, 1, 1, 1, 0, 0, 0] ) np.testing.assert_array_equal(build_mask(A_,23 ).numpy(),expected.numpy() ) def snake_case_ ( self: Dict ): '''simple docstring''' __UpperCamelCase = torch.tensor([8, 2, 3, 4, 1, 1, 1] ) __UpperCamelCase = torch.tensor([1, 1, 1, 1, 0, 0, 0] ) np.testing.assert_array_equal(build_mask(A_,1 ).numpy(),expected.numpy() ) def snake_case_ ( self: Dict ): '''simple docstring''' __UpperCamelCase = 101 __UpperCamelCase = torch.tensor([[1, 2, 3, 4, 5, 6], [1, 2, 3, 101, 5, 6], [1, 101, 3, 4, 101, 6]] ) __UpperCamelCase = torch.tensor([[1, 1, 1, 1, 1, 1], [1, 1, 1, 0, 0, 0], [1, 0, 0, 0, 1, 1]] ) __UpperCamelCase = compute_token_type_ids(A_,A_ ) np.testing.assert_array_equal(A_,A_ )
1
import unittest import numpy as np def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ = None , ) -> np.ndarray: UpperCamelCase_: str = np.shape(UpperCAmelCase__ ) UpperCamelCase_: str = np.shape(UpperCAmelCase__ ) UpperCamelCase_: List[Any] = np.shape(UpperCAmelCase__ ) if shape_a[0] != shape_b[0]: UpperCamelCase_: Any = ( 'Expected the same number of rows for A and B. ' F'''Instead found A of size {shape_a} and B of size {shape_b}''' ) raise ValueError(UpperCAmelCase__ ) if shape_b[1] != shape_c[1]: UpperCamelCase_: int = ( 'Expected the same number of columns for B and C. ' F'''Instead found B of size {shape_b} and C of size {shape_c}''' ) raise ValueError(UpperCAmelCase__ ) UpperCamelCase_: Dict = pseudo_inv if a_inv is None: try: UpperCamelCase_: Optional[Any] = np.linalg.inv(UpperCAmelCase__ ) except np.linalg.LinAlgError: raise ValueError( 'Input matrix A is not invertible. Cannot compute Schur complement.' ) return mat_c - mat_b.T @ a_inv @ mat_b class _lowerCAmelCase( unittest.TestCase ): """simple docstring""" def _a ( self ): UpperCamelCase_: Any = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) UpperCamelCase_: Dict = np.array([[0, 3], [3, 0], [2, 3]] ) UpperCamelCase_: Tuple = np.array([[2, 1], [6, 3]] ) UpperCamelCase_: Tuple = schur_complement(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) UpperCamelCase_: Optional[Any] = np.block([[a, b], [b.T, c]] ) UpperCamelCase_: List[str] = np.linalg.det(_lowerCamelCase ) UpperCamelCase_: List[str] = np.linalg.det(_lowerCamelCase ) UpperCamelCase_: Dict = np.linalg.det(_lowerCamelCase ) self.assertAlmostEqual(_lowerCamelCase , det_a * det_s ) def _a ( self ): UpperCamelCase_: int = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) UpperCamelCase_: List[str] = np.array([[0, 3], [3, 0], [2, 3]] ) UpperCamelCase_: List[str] = np.array([[2, 1], [6, 3]] ) with self.assertRaises(_lowerCamelCase ): schur_complement(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def _a ( self ): UpperCamelCase_: List[Any] = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) UpperCamelCase_: str = np.array([[0, 3], [3, 0], [2, 3]] ) UpperCamelCase_: List[Any] = np.array([[2, 1, 3], [6, 3, 5]] ) with self.assertRaises(_lowerCamelCase ): schur_complement(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) if __name__ == "__main__": import doctest doctest.testmod() unittest.main()
57
0
import doctest import glob import importlib import inspect import os import re from contextlib import contextmanager from functools import wraps from unittest.mock import patch import numpy as np import pytest from absl.testing import parameterized import datasets from datasets import load_metric from .utils import for_all_test_methods, local, slow # mark all tests as integration UpperCAmelCase_ = pytest.mark.integration UpperCAmelCase_ = {"""comet"""} UpperCAmelCase_ = importlib.util.find_spec("""fairseq""") is not None UpperCAmelCase_ = {"""code_eval"""} UpperCAmelCase_ = os.name == """nt""" UpperCAmelCase_ = {"""bertscore""", """frugalscore""", """perplexity"""} UpperCAmelCase_ = importlib.util.find_spec("""transformers""") is not None def SCREAMING_SNAKE_CASE_ ( _snake_case :Any ) -> List[str]: @wraps(_snake_case ) def wrapper(self :Optional[Any] , _snake_case :Dict ): if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ: self.skipTest('''"test requires Fairseq"''' ) else: test_case(self , _snake_case ) return wrapper def SCREAMING_SNAKE_CASE_ ( _snake_case :Tuple ) -> str: @wraps(_snake_case ) def wrapper(self :Optional[int] , _snake_case :List[str] ): if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS: self.skipTest('''"test requires transformers"''' ) else: test_case(self , _snake_case ) return wrapper def SCREAMING_SNAKE_CASE_ ( _snake_case :Optional[Any] ) -> Union[str, Any]: @wraps(_snake_case ) def wrapper(self :List[Any] , _snake_case :str ): if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS: self.skipTest('''"test not supported on Windows"''' ) else: test_case(self , _snake_case ) return wrapper def SCREAMING_SNAKE_CASE_ ( ) -> str: _A = [metric_dir.split(os.sep )[-2] for metric_dir in glob.glob('''./metrics/*/''' )] return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"] # gleu is unfinished @parameterized.named_parameters(get_local_metric_names()) @for_all_test_methods( _A , _A , _A) @local class lowerCamelCase__ ( parameterized.TestCase): """simple docstring""" a__ : List[Any] = {} a__ : Tuple = None @pytest.mark.filterwarnings('''ignore:metric_module_factory is deprecated:FutureWarning''' ) @pytest.mark.filterwarnings('''ignore:load_metric is deprecated:FutureWarning''' ) def snake_case_ ( self : Any , __lowerCAmelCase : Any ) -> List[Any]: _A = '''[...]''' _A = importlib.import_module( datasets.load.metric_module_factory(os.path.join('''metrics''' , __lowerCAmelCase ) ).module_path ) _A = datasets.load.import_main_class(metric_module.__name__ , dataset=__lowerCAmelCase ) # check parameters _A = inspect.signature(metric._compute ).parameters self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values() ) ) # no **kwargs # run doctest with self.patch_intensive_calls(__lowerCAmelCase , metric_module.__name__ ): with self.use_local_metrics(): try: _A = doctest.testmod(__lowerCAmelCase , verbose=__lowerCAmelCase , raise_on_error=__lowerCAmelCase ) except doctest.UnexpectedException as e: raise e.exc_info[1] # raise the exception that doctest caught self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @slow def snake_case_ ( self : int , __lowerCAmelCase : int ) -> Optional[Any]: _A = '''[...]''' _A = importlib.import_module( datasets.load.metric_module_factory(os.path.join('''metrics''' , __lowerCAmelCase ) ).module_path ) # run doctest with self.use_local_metrics(): _A = doctest.testmod(__lowerCAmelCase , verbose=__lowerCAmelCase , raise_on_error=__lowerCAmelCase ) self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @contextmanager def snake_case_ ( self : Optional[int] , __lowerCAmelCase : Dict , __lowerCAmelCase : Tuple ) -> Optional[int]: if metric_name in self.INTENSIVE_CALLS_PATCHER: with self.INTENSIVE_CALLS_PATCHER[metric_name](__lowerCAmelCase ): yield else: yield @contextmanager def snake_case_ ( self : Optional[int] ) -> List[Any]: def load_local_metric(__lowerCAmelCase : List[str] , *__lowerCAmelCase : Dict , **__lowerCAmelCase : Optional[int] ): return load_metric(os.path.join('''metrics''' , __lowerCAmelCase ) , *__lowerCAmelCase , **__lowerCAmelCase ) with patch('''datasets.load_metric''' ) as mock_load_metric: _A = load_local_metric yield @classmethod def snake_case_ ( cls : Dict , __lowerCAmelCase : Any ) -> List[str]: def wrapper(__lowerCAmelCase : Optional[int] ): _A = contextmanager(__lowerCAmelCase ) _A = patcher return patcher return wrapper @LocalMetricTest.register_intensive_calls_patcher('''bleurt''' ) def SCREAMING_SNAKE_CASE_ ( _snake_case :List[str] ) -> Any: import tensorflow.compat.va as tf from bleurt.score import Predictor tf.flags.DEFINE_string('''sv''' , '''''' , '''''' ) # handle pytest cli flags class lowerCamelCase__ ( _A): """simple docstring""" def snake_case_ ( self : Optional[Any] , __lowerCAmelCase : Dict ) -> int: assert len(input_dict['''input_ids'''] ) == 2 return np.array([1.03, 1.04] ) # mock predict_fn which is supposed to do a forward pass with a bleurt model with patch('''bleurt.score._create_predictor''' ) as mock_create_predictor: _A = MockedPredictor() yield @LocalMetricTest.register_intensive_calls_patcher('''bertscore''' ) def SCREAMING_SNAKE_CASE_ ( _snake_case :int ) -> Any: import torch def bert_cos_score_idf(_snake_case :List[Any] , _snake_case :Optional[int] , *_snake_case :Union[str, Any] , **_snake_case :Optional[int] ): return torch.tensor([[1.0, 1.0, 1.0]] * len(_snake_case ) ) # mock get_model which is supposed to do download a bert model # mock bert_cos_score_idf which is supposed to do a forward pass with a bert model with patch('''bert_score.scorer.get_model''' ), patch( '''bert_score.scorer.bert_cos_score_idf''' ) as mock_bert_cos_score_idf: _A = bert_cos_score_idf yield @LocalMetricTest.register_intensive_calls_patcher('''comet''' ) def SCREAMING_SNAKE_CASE_ ( _snake_case :Optional[Any] ) -> Union[str, Any]: def load_from_checkpoint(_snake_case :Dict ): class lowerCamelCase__ : """simple docstring""" def snake_case_ ( self : Optional[int] , __lowerCAmelCase : Any , *__lowerCAmelCase : Any , **__lowerCAmelCase : str ) -> Tuple: assert len(__lowerCAmelCase ) == 2 _A = [0.19, 0.92] return scores, sum(__lowerCAmelCase ) / len(__lowerCAmelCase ) return Model() # mock load_from_checkpoint which is supposed to do download a bert model # mock load_from_checkpoint which is supposed to do download a bert model with patch('''comet.download_model''' ) as mock_download_model: _A = None with patch('''comet.load_from_checkpoint''' ) as mock_load_from_checkpoint: _A = load_from_checkpoint yield def SCREAMING_SNAKE_CASE_ ( ) -> List[Any]: _A = load_metric(os.path.join('''metrics''' , '''seqeval''' ) ) _A = '''ERROR''' _A = F'''Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}''' with pytest.raises(_snake_case , match=re.escape(_snake_case ) ): metric.compute(predictions=[] , references=[] , scheme=_snake_case )
2
import argparse import json import os from collections import OrderedDict import torch from transformers import LukeConfig, LukeForMaskedLM, MLukeTokenizer, XLMRobertaTokenizer from transformers.tokenization_utils_base import AddedToken @torch.no_grad() def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) -> int: # Load configuration defined in the metadata file with open(UpperCAmelCase__ ) as metadata_file: UpperCamelCase_: Tuple = json.load(UpperCAmelCase__ ) UpperCamelCase_: List[str] = LukeConfig(use_entity_aware_attention=UpperCAmelCase__ , **metadata['model_config'] ) # Load in the weights from the checkpoint_path UpperCamelCase_: Optional[int] = torch.load(UpperCAmelCase__ , map_location='cpu' )['module'] # Load the entity vocab file UpperCamelCase_: Any = load_original_entity_vocab(UpperCAmelCase__ ) # add an entry for [MASK2] UpperCamelCase_: List[str] = max(entity_vocab.values() ) + 1 config.entity_vocab_size += 1 UpperCamelCase_: Union[str, Any] = XLMRobertaTokenizer.from_pretrained(metadata['model_config']['bert_model_name'] ) # Add special tokens to the token vocabulary for downstream tasks UpperCamelCase_: Any = AddedToken('<ent>' , lstrip=UpperCAmelCase__ , rstrip=UpperCAmelCase__ ) UpperCamelCase_: Optional[Any] = AddedToken('<ent2>' , lstrip=UpperCAmelCase__ , rstrip=UpperCAmelCase__ ) 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(UpperCAmelCase__ ) with open(os.path.join(UpperCAmelCase__ , 'tokenizer_config.json' ) , 'r' ) as f: UpperCamelCase_: Union[str, Any] = json.load(UpperCAmelCase__ ) UpperCamelCase_: str = 'MLukeTokenizer' with open(os.path.join(UpperCAmelCase__ , 'tokenizer_config.json' ) , 'w' ) as f: json.dump(UpperCAmelCase__ , UpperCAmelCase__ ) with open(os.path.join(UpperCAmelCase__ , MLukeTokenizer.vocab_files_names['entity_vocab_file'] ) , 'w' ) as f: json.dump(UpperCAmelCase__ , UpperCAmelCase__ ) UpperCamelCase_: Optional[Any] = MLukeTokenizer.from_pretrained(UpperCAmelCase__ ) # Initialize the embeddings of the special tokens UpperCamelCase_: Any = tokenizer.convert_tokens_to_ids(['@'] )[0] UpperCamelCase_: List[str] = tokenizer.convert_tokens_to_ids(['#'] )[0] UpperCamelCase_: Tuple = state_dict['embeddings.word_embeddings.weight'] UpperCamelCase_: int = word_emb[ent_init_index].unsqueeze(0 ) UpperCamelCase_: Any = word_emb[enta_init_index].unsqueeze(0 ) UpperCamelCase_: str = torch.cat([word_emb, ent_emb, enta_emb] ) # add special tokens for 'entity_predictions.bias' for bias_name in ["lm_head.decoder.bias", "lm_head.bias"]: UpperCamelCase_: Union[str, Any] = state_dict[bias_name] UpperCamelCase_: Tuple = decoder_bias[ent_init_index].unsqueeze(0 ) UpperCamelCase_: Any = decoder_bias[enta_init_index].unsqueeze(0 ) UpperCamelCase_: Optional[Any] = torch.cat([decoder_bias, ent_decoder_bias, enta_decoder_bias] ) # 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_: List[Any] = F'''encoder.layer.{layer_index}.attention.self.''' UpperCamelCase_: str = state_dict[prefix + matrix_name] UpperCamelCase_: Dict = state_dict[prefix + matrix_name] UpperCamelCase_: Dict = state_dict[prefix + matrix_name] # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks UpperCamelCase_: List[str] = state_dict['entity_embeddings.entity_embeddings.weight'] UpperCamelCase_: int = entity_emb[entity_vocab['[MASK]']].unsqueeze(0 ) UpperCamelCase_: Tuple = torch.cat([entity_emb, entity_mask_emb] ) # add [MASK2] for 'entity_predictions.bias' UpperCamelCase_: Optional[Any] = state_dict['entity_predictions.bias'] UpperCamelCase_: List[str] = entity_prediction_bias[entity_vocab['[MASK]']].unsqueeze(0 ) UpperCamelCase_: List[Any] = torch.cat([entity_prediction_bias, entity_mask_bias] ) UpperCamelCase_: List[Any] = LukeForMaskedLM(config=UpperCAmelCase__ ).eval() state_dict.pop('entity_predictions.decoder.weight' ) state_dict.pop('lm_head.decoder.weight' ) state_dict.pop('lm_head.decoder.bias' ) UpperCamelCase_: Optional[Any] = OrderedDict() for key, value in state_dict.items(): if not (key.startswith('lm_head' ) or key.startswith('entity_predictions' )): UpperCamelCase_: Union[str, Any] = state_dict[key] else: UpperCamelCase_: Dict = state_dict[key] UpperCamelCase_ ,UpperCamelCase_: Optional[int] = model.load_state_dict(UpperCAmelCase__ , strict=UpperCAmelCase__ ) if set(UpperCAmelCase__ ) != {"luke.embeddings.position_ids"}: raise ValueError(F'''Unexpected unexpected_keys: {unexpected_keys}''' ) if set(UpperCAmelCase__ ) != { "lm_head.decoder.weight", "lm_head.decoder.bias", "entity_predictions.decoder.weight", }: raise ValueError(F'''Unexpected missing_keys: {missing_keys}''' ) model.tie_weights() assert (model.luke.embeddings.word_embeddings.weight == model.lm_head.decoder.weight).all() assert (model.luke.entity_embeddings.entity_embeddings.weight == model.entity_predictions.decoder.weight).all() # Check outputs UpperCamelCase_: Optional[int] = MLukeTokenizer.from_pretrained(UpperCAmelCase__ , task='entity_classification' ) UpperCamelCase_: Tuple = 'ISO 639-3 uses the code fas for the dialects spoken across Iran and アフガニスタン (Afghanistan).' UpperCamelCase_: Optional[int] = (0, 9) UpperCamelCase_: Union[str, Any] = tokenizer(UpperCAmelCase__ , entity_spans=[span] , return_tensors='pt' ) UpperCamelCase_: str = model(**UpperCAmelCase__ ) # Verify word hidden states if model_size == "large": raise NotImplementedError else: # base UpperCamelCase_: int = torch.Size((1, 3_3, 7_6_8) ) UpperCamelCase_: Tuple = torch.tensor([[0.0892, 0.0596, -0.2819], [0.0134, 0.1199, 0.0573], [-0.0169, 0.0927, 0.0644]] ) 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] , UpperCAmelCase__ , atol=1E-4 ): raise ValueError # Verify entity hidden states if model_size == "large": raise NotImplementedError else: # base UpperCamelCase_: Dict = torch.Size((1, 1, 7_6_8) ) UpperCamelCase_: Tuple = torch.tensor([[-0.1482, 0.0609, 0.0322]] ) 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] , UpperCAmelCase__ , atol=1E-4 ): raise ValueError # Verify masked word/entity prediction UpperCamelCase_: str = MLukeTokenizer.from_pretrained(UpperCAmelCase__ ) UpperCamelCase_: int = 'Tokyo is the capital of <mask>.' UpperCamelCase_: Dict = (2_4, 3_0) UpperCamelCase_: int = tokenizer(UpperCAmelCase__ , entity_spans=[span] , return_tensors='pt' ) UpperCamelCase_: Dict = model(**UpperCAmelCase__ ) UpperCamelCase_: Optional[int] = encoding['input_ids'][0].tolist() UpperCamelCase_: List[Any] = input_ids.index(tokenizer.convert_tokens_to_ids('<mask>' ) ) UpperCamelCase_: Any = outputs.logits[0][mask_position_id].argmax(dim=-1 ) assert "Japan" == tokenizer.decode(UpperCAmelCase__ ) UpperCamelCase_: Union[str, Any] = outputs.entity_logits[0][0].argmax().item() UpperCamelCase_: Optional[Any] = [ entity for entity, entity_id in tokenizer.entity_vocab.items() if entity_id == predicted_entity_id ] assert [e for e in multilingual_predicted_entities if e.startswith('en:' )][0] == "en:Japan" # Finally, save our PyTorch model and tokenizer print('Saving PyTorch model to {}'.format(UpperCAmelCase__ ) ) model.save_pretrained(UpperCAmelCase__ ) def snake_case (UpperCAmelCase__ ) -> int: UpperCamelCase_: Optional[Any] = ['[MASK]', '[PAD]', '[UNK]'] UpperCamelCase_: Any = [json.loads(UpperCAmelCase__ ) for line in open(UpperCAmelCase__ )] UpperCamelCase_: Tuple = {} for entry in data: UpperCamelCase_: Optional[int] = entry['id'] for entity_name, language in entry["entities"]: if entity_name in SPECIAL_TOKENS: UpperCamelCase_: Union[str, Any] = entity_id break UpperCamelCase_: Dict = F'''{language}:{entity_name}''' UpperCamelCase_: Optional[int] = entity_id return new_mapping if __name__ == "__main__": A_ : Tuple = 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_ : List[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, )
57
0
'''simple docstring''' import gc import unittest from parameterized import parameterized from diffusers import FlaxUNetaDConditionModel from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import load_hf_numpy, require_flax, slow if is_flax_available(): import jax import jax.numpy as jnp @slow @require_flax class SCREAMING_SNAKE_CASE__ ( unittest.TestCase): def UpperCAmelCase_ ( self , A_ , A_ )-> Optional[Any]: '''simple docstring''' return F'''gaussian_noise_s={seed}_shape={"_".join([str(A_ ) for s in shape] )}.npy''' def UpperCAmelCase_ ( self )-> Any: '''simple docstring''' super().tearDown() gc.collect() def UpperCAmelCase_ ( self , A_=0 , A_=(4, 4, 64, 64) , A_=False )-> List[str]: '''simple docstring''' UpperCamelCase = jnp.bfloataa if fpaa else jnp.floataa UpperCamelCase = jnp.array(load_hf_numpy(self.get_file_format(A_ , A_ ) ) , dtype=A_ ) return image def UpperCAmelCase_ ( self , A_=False , A_="CompVis/stable-diffusion-v1-4" )-> Union[str, Any]: '''simple docstring''' UpperCamelCase = jnp.bfloataa if fpaa else jnp.floataa UpperCamelCase = 'bf16' if fpaa else None UpperCamelCase , UpperCamelCase = FlaxUNetaDConditionModel.from_pretrained( A_ , subfolder='unet' , dtype=A_ , revision=A_ ) return model, params def UpperCAmelCase_ ( self , A_=0 , A_=(4, 77, 768) , A_=False )-> Optional[int]: '''simple docstring''' UpperCamelCase = jnp.bfloataa if fpaa else jnp.floataa UpperCamelCase = jnp.array(load_hf_numpy(self.get_file_format(A_ , A_ ) ) , dtype=A_ ) return hidden_states @parameterized.expand( [ # fmt: off [83, 4, [-0.2_323, -0.1_304, 0.0_813, -0.3_093, -0.0_919, -0.1_571, -0.1_125, -0.5_806]], [17, 0.55, [-0.0_831, -0.2_443, 0.0_901, -0.0_919, 0.3_396, 0.0_103, -0.3_743, 0.0_701]], [8, 0.89, [-0.4_863, 0.0_859, 0.0_875, -0.1_658, 0.9_199, -0.0_114, 0.4_839, 0.4_639]], [3, 1000, [-0.5_649, 0.2_402, -0.5_518, 0.1_248, 1.1_328, -0.2_443, -0.0_325, -1.0_078]], # fmt: on ] ) def UpperCAmelCase_ ( self , A_ , A_ , A_ )-> List[Any]: '''simple docstring''' UpperCamelCase , UpperCamelCase = self.get_unet_model(model_id='CompVis/stable-diffusion-v1-4' , fpaa=A_ ) UpperCamelCase = self.get_latents(A_ , fpaa=A_ ) UpperCamelCase = self.get_encoder_hidden_states(A_ , fpaa=A_ ) UpperCamelCase = model.apply( {'params': params} , A_ , jnp.array(A_ , dtype=jnp.intaa ) , encoder_hidden_states=A_ , ).sample assert sample.shape == latents.shape UpperCamelCase = jnp.asarray(jax.device_get((sample[-1, -2:, -2:, :2].flatten()) ) , dtype=jnp.floataa ) UpperCamelCase = jnp.array(A_ , dtype=jnp.floataa ) # Found torch (float16) and flax (bfloat16) outputs to be within this tolerance, in the same hardware assert jnp.allclose(A_ , A_ , atol=1e-2 ) @parameterized.expand( [ # fmt: off [83, 4, [0.1_514, 0.0_807, 0.1_624, 0.1_016, -0.1_896, 0.0_263, 0.0_677, 0.2_310]], [17, 0.55, [0.1_164, -0.0_216, 0.0_170, 0.1_589, -0.3_120, 0.1_005, -0.0_581, -0.1_458]], [8, 0.89, [-0.1_758, -0.0_169, 0.1_004, -0.1_411, 0.1_312, 0.1_103, -0.1_996, 0.2_139]], [3, 1000, [0.1_214, 0.0_352, -0.0_731, -0.1_562, -0.0_994, -0.0_906, -0.2_340, -0.0_539]], # fmt: on ] ) def UpperCAmelCase_ ( self , A_ , A_ , A_ )-> Any: '''simple docstring''' UpperCamelCase , UpperCamelCase = self.get_unet_model(model_id='stabilityai/stable-diffusion-2' , fpaa=A_ ) UpperCamelCase = self.get_latents(A_ , shape=(4, 4, 96, 96) , fpaa=A_ ) UpperCamelCase = self.get_encoder_hidden_states(A_ , shape=(4, 77, 1024) , fpaa=A_ ) UpperCamelCase = model.apply( {'params': params} , A_ , jnp.array(A_ , dtype=jnp.intaa ) , encoder_hidden_states=A_ , ).sample assert sample.shape == latents.shape UpperCamelCase = jnp.asarray(jax.device_get((sample[-1, -2:, -2:, :2].flatten()) ) , dtype=jnp.floataa ) UpperCamelCase = jnp.array(A_ , dtype=jnp.floataa ) # Found torch (float16) and flax (bfloat16) outputs to be within this tolerance, on the same hardware assert jnp.allclose(A_ , A_ , atol=1e-2 )
3
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A_ : Optional[Any] = logging.get_logger(__name__) A_ : Optional[Any] = { 'distilbert-base-uncased': 'https://huggingface.co/distilbert-base-uncased/resolve/main/config.json', 'distilbert-base-uncased-distilled-squad': ( 'https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/config.json' ), 'distilbert-base-cased': 'https://huggingface.co/distilbert-base-cased/resolve/main/config.json', 'distilbert-base-cased-distilled-squad': ( 'https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/config.json' ), 'distilbert-base-german-cased': 'https://huggingface.co/distilbert-base-german-cased/resolve/main/config.json', 'distilbert-base-multilingual-cased': ( 'https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/config.json' ), 'distilbert-base-uncased-finetuned-sst-2-english': ( 'https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-english/resolve/main/config.json' ), } class _lowerCAmelCase( UpperCAmelCase_ ): """simple docstring""" a : Dict ='''distilbert''' a : List[str] ={ '''hidden_size''': '''dim''', '''num_attention_heads''': '''n_heads''', '''num_hidden_layers''': '''n_layers''', } def __init__( self , _lowerCamelCase=3_0_5_2_2 , _lowerCamelCase=5_1_2 , _lowerCamelCase=False , _lowerCamelCase=6 , _lowerCamelCase=1_2 , _lowerCamelCase=7_6_8 , _lowerCamelCase=4 * 7_6_8 , _lowerCamelCase=0.1 , _lowerCamelCase=0.1 , _lowerCamelCase="gelu" , _lowerCamelCase=0.0_2 , _lowerCamelCase=0.1 , _lowerCamelCase=0.2 , _lowerCamelCase=0 , **_lowerCamelCase , ): UpperCamelCase_: Tuple = vocab_size UpperCamelCase_: str = max_position_embeddings UpperCamelCase_: Optional[int] = sinusoidal_pos_embds UpperCamelCase_: Union[str, Any] = n_layers UpperCamelCase_: Optional[int] = n_heads UpperCamelCase_: int = dim UpperCamelCase_: Tuple = hidden_dim UpperCamelCase_: Any = dropout UpperCamelCase_: Optional[Any] = attention_dropout UpperCamelCase_: List[str] = activation UpperCamelCase_: Optional[Any] = initializer_range UpperCamelCase_: Optional[Any] = qa_dropout UpperCamelCase_: List[str] = seq_classif_dropout super().__init__(**_lowerCamelCase , pad_token_id=_lowerCamelCase ) class _lowerCAmelCase( UpperCAmelCase_ ): """simple docstring""" @property def _a ( self ): if self.task == "multiple-choice": UpperCamelCase_: Any = {0: 'batch', 1: 'choice', 2: 'sequence'} else: UpperCamelCase_: List[Any] = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
57
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCamelCase : Optional[Any] = logging.get_logger(__name__) __UpperCamelCase : List[Any] = { # See all MEGATRON_BERT models at https://huggingface.co/models?filter=bert } class a ( a__ ): snake_case__ = '''megatron-bert''' def __init__( self , _snake_case=2_90_56 , _snake_case=10_24 , _snake_case=24 , _snake_case=16 , _snake_case=40_96 , _snake_case="gelu" , _snake_case=0.1 , _snake_case=0.1 , _snake_case=5_12 , _snake_case=2 , _snake_case=0.02 , _snake_case=1E-12 , _snake_case=0 , _snake_case="absolute" , _snake_case=True , **_snake_case , ): """simple docstring""" super().__init__(pad_token_id=_snake_case , **_snake_case ) lowerCAmelCase = vocab_size lowerCAmelCase = hidden_size lowerCAmelCase = num_hidden_layers lowerCAmelCase = num_attention_heads lowerCAmelCase = hidden_act lowerCAmelCase = intermediate_size lowerCAmelCase = hidden_dropout_prob lowerCAmelCase = attention_probs_dropout_prob lowerCAmelCase = max_position_embeddings lowerCAmelCase = type_vocab_size lowerCAmelCase = initializer_range lowerCAmelCase = layer_norm_eps lowerCAmelCase = position_embedding_type lowerCAmelCase = use_cache
4
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A_ : int = { 'configuration_lilt': ['LILT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LiltConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : Any = [ 'LILT_PRETRAINED_MODEL_ARCHIVE_LIST', 'LiltForQuestionAnswering', 'LiltForSequenceClassification', 'LiltForTokenClassification', 'LiltModel', 'LiltPreTrainedModel', ] if TYPE_CHECKING: from .configuration_lilt import LILT_PRETRAINED_CONFIG_ARCHIVE_MAP, LiltConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_lilt import ( LILT_PRETRAINED_MODEL_ARCHIVE_LIST, LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, LiltPreTrainedModel, ) else: import sys A_ : Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
57
0
'''simple docstring''' import inspect import tempfile from collections import OrderedDict, UserDict from collections.abc import MutableMapping from contextlib import ExitStack, contextmanager from dataclasses import fields from enum import Enum from typing import Any, ContextManager, List, Tuple import numpy as np from .import_utils import is_flax_available, is_tf_available, is_torch_available, is_torch_fx_proxy if is_flax_available(): import jax.numpy as jnp class UpperCAmelCase_ ( _SCREAMING_SNAKE_CASE ): '''simple docstring''' def __get__( self , _lowercase , _lowercase=None ): """simple docstring""" if obj is None: return self if self.fget is None: raise AttributeError("""unreadable attribute""" ) _lowerCAmelCase = """__cached_""" + self.fget.__name__ _lowerCAmelCase = getattr(_lowercase , _lowercase , _lowercase ) if cached is None: _lowerCAmelCase = self.fget(_lowercase ) setattr(_lowercase , _lowercase , _lowercase ) return cached def A (__lowerCamelCase :int ): _lowerCAmelCase = val.lower() if val in {"y", "yes", "t", "true", "on", "1"}: return 1 if val in {"n", "no", "f", "false", "off", "0"}: return 0 raise ValueError(f'invalid truth value {val!r}' ) def A (__lowerCamelCase :Union[str, Any] ): if is_torch_fx_proxy(__lowerCamelCase ): return True if is_torch_available(): import torch if isinstance(__lowerCamelCase , torch.Tensor ): return True if is_tf_available(): import tensorflow as tf if isinstance(__lowerCamelCase , tf.Tensor ): return True if is_flax_available(): import jax.numpy as jnp from jax.core import Tracer if isinstance(__lowerCamelCase , (jnp.ndarray, Tracer) ): return True return isinstance(__lowerCamelCase , np.ndarray ) def A (__lowerCamelCase :List[Any] ): return isinstance(__lowerCamelCase , np.ndarray ) def A (__lowerCamelCase :str ): return _is_numpy(__lowerCamelCase ) def A (__lowerCamelCase :Dict ): import torch return isinstance(__lowerCamelCase , torch.Tensor ) def A (__lowerCamelCase :Union[str, Any] ): return False if not is_torch_available() else _is_torch(__lowerCamelCase ) def A (__lowerCamelCase :Union[str, Any] ): import torch return isinstance(__lowerCamelCase , torch.device ) def A (__lowerCamelCase :List[str] ): return False if not is_torch_available() else _is_torch_device(__lowerCamelCase ) def A (__lowerCamelCase :Dict ): import torch if isinstance(__lowerCamelCase , __lowerCamelCase ): if hasattr(__lowerCamelCase , __lowerCamelCase ): _lowerCAmelCase = getattr(__lowerCamelCase , __lowerCamelCase ) else: return False return isinstance(__lowerCamelCase , torch.dtype ) def A (__lowerCamelCase :Dict ): return False if not is_torch_available() else _is_torch_dtype(__lowerCamelCase ) def A (__lowerCamelCase :str ): import tensorflow as tf return isinstance(__lowerCamelCase , tf.Tensor ) def A (__lowerCamelCase :Optional[int] ): return False if not is_tf_available() else _is_tensorflow(__lowerCamelCase ) def A (__lowerCamelCase :Tuple ): import tensorflow as tf # the `is_symbolic_tensor` predicate is only available starting with TF 2.14 if hasattr(__lowerCamelCase , """is_symbolic_tensor""" ): return tf.is_symbolic_tensor(__lowerCamelCase ) return type(__lowerCamelCase ) == tf.Tensor def A (__lowerCamelCase :int ): return False if not is_tf_available() else _is_tf_symbolic_tensor(__lowerCamelCase ) def A (__lowerCamelCase :Optional[int] ): import jax.numpy as jnp # noqa: F811 return isinstance(__lowerCamelCase , jnp.ndarray ) def A (__lowerCamelCase :List[str] ): return False if not is_flax_available() else _is_jax(__lowerCamelCase ) def A (__lowerCamelCase :Dict ): if isinstance(__lowerCamelCase , (dict, UserDict) ): return {k: to_py_obj(__lowerCamelCase ) for k, v in obj.items()} elif isinstance(__lowerCamelCase , (list, tuple) ): return [to_py_obj(__lowerCamelCase ) for o in obj] elif is_tf_tensor(__lowerCamelCase ): return obj.numpy().tolist() elif is_torch_tensor(__lowerCamelCase ): return obj.detach().cpu().tolist() elif is_jax_tensor(__lowerCamelCase ): return np.asarray(__lowerCamelCase ).tolist() elif isinstance(__lowerCamelCase , (np.ndarray, np.number) ): # tolist also works on 0d np arrays return obj.tolist() else: return obj def A (__lowerCamelCase :Optional[int] ): if isinstance(__lowerCamelCase , (dict, UserDict) ): return {k: to_numpy(__lowerCamelCase ) for k, v in obj.items()} elif isinstance(__lowerCamelCase , (list, tuple) ): return np.array(__lowerCamelCase ) elif is_tf_tensor(__lowerCamelCase ): return obj.numpy() elif is_torch_tensor(__lowerCamelCase ): return obj.detach().cpu().numpy() elif is_jax_tensor(__lowerCamelCase ): return np.asarray(__lowerCamelCase ) else: return obj class UpperCAmelCase_ ( _SCREAMING_SNAKE_CASE ): '''simple docstring''' def _lowercase ( self ): """simple docstring""" _lowerCAmelCase = fields(self ) # Safety and consistency checks if not len(_lowercase ): raise ValueError(F'{self.__class__.__name__} has no fields.' ) if not all(field.default is None for field in class_fields[1:] ): raise ValueError(F'{self.__class__.__name__} should not have more than one required field.' ) _lowerCAmelCase = getattr(self , class_fields[0].name ) _lowerCAmelCase = all(getattr(self , field.name ) is None for field in class_fields[1:] ) if other_fields_are_none and not is_tensor(_lowercase ): if isinstance(_lowercase , _lowercase ): _lowerCAmelCase = first_field.items() _lowerCAmelCase = True else: try: _lowerCAmelCase = iter(_lowercase ) _lowerCAmelCase = True except TypeError: _lowerCAmelCase = False # if we provided an iterator as first field and the iterator is a (key, value) iterator # set the associated fields if first_field_iterator: for idx, element in enumerate(_lowercase ): if ( not isinstance(_lowercase , (list, tuple) ) or not len(_lowercase ) == 2 or not isinstance(element[0] , _lowercase ) ): if idx == 0: # If we do not have an iterator of key/values, set it as attribute _lowerCAmelCase = first_field else: # If we have a mixed iterator, raise an error raise ValueError( F'Cannot set key/value for {element}. It needs to be a tuple (key, value).' ) break setattr(self , element[0] , element[1] ) if element[1] is not None: _lowerCAmelCase = element[1] elif first_field is not None: _lowerCAmelCase = first_field else: for field in class_fields: _lowerCAmelCase = getattr(self , field.name ) if v is not None: _lowerCAmelCase = v def __delitem__( self , *_lowercase , **_lowercase ): """simple docstring""" raise Exception(F'You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.' ) def _lowercase ( self , *_lowercase , **_lowercase ): """simple docstring""" raise Exception(F'You cannot use ``setdefault`` on a {self.__class__.__name__} instance.' ) def _lowercase ( self , *_lowercase , **_lowercase ): """simple docstring""" raise Exception(F'You cannot use ``pop`` on a {self.__class__.__name__} instance.' ) def _lowercase ( self , *_lowercase , **_lowercase ): """simple docstring""" raise Exception(F'You cannot use ``update`` on a {self.__class__.__name__} instance.' ) def __getitem__( self , _lowercase ): """simple docstring""" if isinstance(_lowercase , _lowercase ): _lowerCAmelCase = dict(self.items() ) return inner_dict[k] else: return self.to_tuple()[k] def __setattr__( self , _lowercase , _lowercase ): """simple docstring""" if name in self.keys() and value is not None: # Don't call self.__setitem__ to avoid recursion errors super().__setitem__(_lowercase , _lowercase ) super().__setattr__(_lowercase , _lowercase ) def __setitem__( self , _lowercase , _lowercase ): """simple docstring""" super().__setitem__(_lowercase , _lowercase ) # Don't call self.__setattr__ to avoid recursion errors super().__setattr__(_lowercase , _lowercase ) def _lowercase ( self ): """simple docstring""" return tuple(self[k] for k in self.keys() ) class UpperCAmelCase_ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): '''simple docstring''' @classmethod def _lowercase ( cls , _lowercase ): """simple docstring""" raise ValueError( F'{value} is not a valid {cls.__name__}, please select one of {list(cls._valueamember_map_.keys() )}' ) class UpperCAmelCase_ ( _SCREAMING_SNAKE_CASE ): '''simple docstring''' _lowercase : int = '''longest''' _lowercase : str = '''max_length''' _lowercase : List[Any] = '''do_not_pad''' class UpperCAmelCase_ ( _SCREAMING_SNAKE_CASE ): '''simple docstring''' _lowercase : List[Any] = '''pt''' _lowercase : Optional[Any] = '''tf''' _lowercase : List[str] = '''np''' _lowercase : int = '''jax''' class UpperCAmelCase_ : '''simple docstring''' def __init__( self , _lowercase ): """simple docstring""" _lowerCAmelCase = context_managers _lowerCAmelCase = ExitStack() def __enter__( self ): """simple docstring""" for context_manager in self.context_managers: self.stack.enter_context(_lowercase ) def __exit__( self , *_lowercase , **_lowercase ): """simple docstring""" self.stack.__exit__(*_lowercase , **_lowercase ) def A (__lowerCamelCase :str ): _lowerCAmelCase = infer_framework(__lowerCamelCase ) if framework == "tf": _lowerCAmelCase = inspect.signature(model_class.call ) # TensorFlow models elif framework == "pt": _lowerCAmelCase = inspect.signature(model_class.forward ) # PyTorch models else: _lowerCAmelCase = inspect.signature(model_class.__call__ ) # Flax models for p in signature.parameters: if p == "return_loss" and signature.parameters[p].default is True: return True return False def A (__lowerCamelCase :List[str] ): _lowerCAmelCase = model_class.__name__ _lowerCAmelCase = infer_framework(__lowerCamelCase ) if framework == "tf": _lowerCAmelCase = inspect.signature(model_class.call ) # TensorFlow models elif framework == "pt": _lowerCAmelCase = inspect.signature(model_class.forward ) # PyTorch models else: _lowerCAmelCase = inspect.signature(model_class.__call__ ) # Flax models if "QuestionAnswering" in model_name: return [p for p in signature.parameters if "label" in p or p in ("start_positions", "end_positions")] else: return [p for p in signature.parameters if "label" in p] def A (__lowerCamelCase :MutableMapping , __lowerCamelCase :str = "" , __lowerCamelCase :str = "." ): def _flatten_dict(__lowerCamelCase :Optional[Any] , __lowerCamelCase :Optional[int]="" , __lowerCamelCase :Dict="." ): for k, v in d.items(): _lowerCAmelCase = str(__lowerCamelCase ) + delimiter + str(__lowerCamelCase ) if parent_key else k if v and isinstance(__lowerCamelCase , __lowerCamelCase ): yield from flatten_dict(__lowerCamelCase , __lowerCamelCase , delimiter=__lowerCamelCase ).items() else: yield key, v return dict(_flatten_dict(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) ) @contextmanager def A (__lowerCamelCase :Any , __lowerCamelCase :bool = False ): if use_temp_dir: with tempfile.TemporaryDirectory() as tmp_dir: yield tmp_dir else: yield working_dir def A (__lowerCamelCase :Dict , __lowerCamelCase :List[str]=None ): if is_numpy_array(__lowerCamelCase ): return np.transpose(__lowerCamelCase , axes=__lowerCamelCase ) elif is_torch_tensor(__lowerCamelCase ): return array.T if axes is None else array.permute(*__lowerCamelCase ) elif is_tf_tensor(__lowerCamelCase ): import tensorflow as tf return tf.transpose(__lowerCamelCase , perm=__lowerCamelCase ) elif is_jax_tensor(__lowerCamelCase ): return jnp.transpose(__lowerCamelCase , axes=__lowerCamelCase ) else: raise ValueError(f'Type not supported for transpose: {type(__lowerCamelCase )}.' ) def A (__lowerCamelCase :Tuple , __lowerCamelCase :List[Any] ): if is_numpy_array(__lowerCamelCase ): return np.reshape(__lowerCamelCase , __lowerCamelCase ) elif is_torch_tensor(__lowerCamelCase ): return array.reshape(*__lowerCamelCase ) elif is_tf_tensor(__lowerCamelCase ): import tensorflow as tf return tf.reshape(__lowerCamelCase , __lowerCamelCase ) elif is_jax_tensor(__lowerCamelCase ): return jnp.reshape(__lowerCamelCase , __lowerCamelCase ) else: raise ValueError(f'Type not supported for reshape: {type(__lowerCamelCase )}.' ) def A (__lowerCamelCase :str , __lowerCamelCase :Any=None ): if is_numpy_array(__lowerCamelCase ): return np.squeeze(__lowerCamelCase , axis=__lowerCamelCase ) elif is_torch_tensor(__lowerCamelCase ): return array.squeeze() if axis is None else array.squeeze(dim=__lowerCamelCase ) elif is_tf_tensor(__lowerCamelCase ): import tensorflow as tf return tf.squeeze(__lowerCamelCase , axis=__lowerCamelCase ) elif is_jax_tensor(__lowerCamelCase ): return jnp.squeeze(__lowerCamelCase , axis=__lowerCamelCase ) else: raise ValueError(f'Type not supported for squeeze: {type(__lowerCamelCase )}.' ) def A (__lowerCamelCase :Union[str, Any] , __lowerCamelCase :Dict ): if is_numpy_array(__lowerCamelCase ): return np.expand_dims(__lowerCamelCase , __lowerCamelCase ) elif is_torch_tensor(__lowerCamelCase ): return array.unsqueeze(dim=__lowerCamelCase ) elif is_tf_tensor(__lowerCamelCase ): import tensorflow as tf return tf.expand_dims(__lowerCamelCase , axis=__lowerCamelCase ) elif is_jax_tensor(__lowerCamelCase ): return jnp.expand_dims(__lowerCamelCase , axis=__lowerCamelCase ) else: raise ValueError(f'Type not supported for expand_dims: {type(__lowerCamelCase )}.' ) def A (__lowerCamelCase :Optional[Any] ): if is_numpy_array(__lowerCamelCase ): return np.size(__lowerCamelCase ) elif is_torch_tensor(__lowerCamelCase ): return array.numel() elif is_tf_tensor(__lowerCamelCase ): import tensorflow as tf return tf.size(__lowerCamelCase ) elif is_jax_tensor(__lowerCamelCase ): return array.size else: raise ValueError(f'Type not supported for expand_dims: {type(__lowerCamelCase )}.' ) def A (__lowerCamelCase :List[Any] , __lowerCamelCase :Optional[int] ): for key, value in auto_map.items(): if isinstance(__lowerCamelCase , (tuple, list) ): _lowerCAmelCase = [f'{repo_id}--{v}' if (v is not None and """--""" not in v) else v for v in value] elif value is not None and "--" not in value: _lowerCAmelCase = f'{repo_id}--{value}' return auto_map def A (__lowerCamelCase :Tuple ): for base_class in inspect.getmro(__lowerCamelCase ): _lowerCAmelCase = base_class.__module__ _lowerCAmelCase = base_class.__name__ if module.startswith("""tensorflow""" ) or module.startswith("""keras""" ) or name == "TFPreTrainedModel": return "tf" elif module.startswith("""torch""" ) or name == "PreTrainedModel": return "pt" elif module.startswith("""flax""" ) or module.startswith("""jax""" ) or name == "FlaxPreTrainedModel": return "flax" else: raise TypeError(f'Could not infer framework from class {model_class}.' )
5
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available A_ : List[str] = { 'configuration_roc_bert': ['ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'RoCBertConfig'], 'tokenization_roc_bert': ['RoCBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: pass try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : Union[str, Any] = [ 'ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'RoCBertForCausalLM', 'RoCBertForMaskedLM', 'RoCBertForMultipleChoice', 'RoCBertForPreTraining', 'RoCBertForQuestionAnswering', 'RoCBertForSequenceClassification', 'RoCBertForTokenClassification', 'RoCBertLayer', 'RoCBertModel', 'RoCBertPreTrainedModel', 'load_tf_weights_in_roc_bert', ] if TYPE_CHECKING: from .configuration_roc_bert import ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RoCBertConfig from .tokenization_roc_bert import RoCBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: raise OptionalDependencyNotAvailable() try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roc_bert import ( ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, RoCBertForCausalLM, RoCBertForMaskedLM, RoCBertForMultipleChoice, RoCBertForPreTraining, RoCBertForQuestionAnswering, RoCBertForSequenceClassification, RoCBertForTokenClassification, RoCBertLayer, RoCBertModel, RoCBertPreTrainedModel, load_tf_weights_in_roc_bert, ) else: import sys A_ : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
57
0
import numpy as np import torch from torch.utils.data import Dataset from utils import logger class UpperCamelCase_ ( UpperCamelCase__ ): def __init__( self :Any , __A :Any , __A :Any ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = params SCREAMING_SNAKE_CASE__ = np.array(__A ) SCREAMING_SNAKE_CASE__ = np.array([len(__A ) for t in data] ) self.check() self.remove_long_sequences() self.remove_empty_sequences() self.remove_unknown_sequences() self.check() self.print_statistics() def __getitem__( self :Dict , __A :Optional[Any] ) -> Optional[Any]: """simple docstring""" return (self.token_ids[index], self.lengths[index]) def __len__( self :str ) -> List[Any]: """simple docstring""" return len(self.lengths ) def _snake_case ( self :Tuple ) -> str: """simple docstring""" assert len(self.token_ids ) == len(self.lengths ) assert all(self.lengths[i] == len(self.token_ids[i] ) for i in range(len(self.lengths ) ) ) def _snake_case ( self :List[str] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.params.max_model_input_size SCREAMING_SNAKE_CASE__ = self.lengths > max_len logger.info(f'''Splitting {sum(__A )} too long sequences.''' ) def divide_chunks(__A :Dict , __A :Optional[Any] ): return [l[i : i + n] for i in range(0 , len(__A ) , __A )] SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = [] if self.params.mlm: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.params.special_tok_ids["""cls_token"""], self.params.special_tok_ids["""sep_token"""] else: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.params.special_tok_ids["""bos_token"""], self.params.special_tok_ids["""eos_token"""] for seq_, len_ in zip(self.token_ids , self.lengths ): assert (seq_[0] == cls_id) and (seq_[-1] == sep_id), seq_ if len_ <= max_len: new_tok_ids.append(seq_ ) new_lengths.append(len_ ) else: SCREAMING_SNAKE_CASE__ = [] for sub_s in divide_chunks(seq_ , max_len - 2 ): if sub_s[0] != cls_id: SCREAMING_SNAKE_CASE__ = np.insert(__A , 0 , __A ) if sub_s[-1] != sep_id: SCREAMING_SNAKE_CASE__ = np.insert(__A , len(__A ) , __A ) assert len(__A ) <= max_len assert (sub_s[0] == cls_id) and (sub_s[-1] == sep_id), sub_s sub_seqs.append(__A ) new_tok_ids.extend(__A ) new_lengths.extend([len(__A ) for l in sub_seqs] ) SCREAMING_SNAKE_CASE__ = np.array(__A ) SCREAMING_SNAKE_CASE__ = np.array(__A ) def _snake_case ( self :str ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = len(self ) SCREAMING_SNAKE_CASE__ = self.lengths > 11 SCREAMING_SNAKE_CASE__ = self.token_ids[indices] SCREAMING_SNAKE_CASE__ = self.lengths[indices] SCREAMING_SNAKE_CASE__ = len(self ) logger.info(f'''Remove {init_size - new_size} too short (<=11 tokens) sequences.''' ) def _snake_case ( self :str ) -> Any: """simple docstring""" if "unk_token" not in self.params.special_tok_ids: return else: SCREAMING_SNAKE_CASE__ = self.params.special_tok_ids["""unk_token"""] SCREAMING_SNAKE_CASE__ = len(self ) SCREAMING_SNAKE_CASE__ = np.array([np.count_nonzero(a == unk_token_id ) for a in self.token_ids] ) SCREAMING_SNAKE_CASE__ = (unk_occs / self.lengths) < 0.5 SCREAMING_SNAKE_CASE__ = self.token_ids[indices] SCREAMING_SNAKE_CASE__ = self.lengths[indices] SCREAMING_SNAKE_CASE__ = len(self ) logger.info(f'''Remove {init_size - new_size} sequences with a high level of unknown tokens (50%).''' ) def _snake_case ( self :Union[str, Any] ) -> List[str]: """simple docstring""" if not self.params.is_master: return logger.info(f'''{len(self )} sequences''' ) # data_len = sum(self.lengths) # nb_unique_tokens = len(Counter(list(chain(*self.token_ids)))) # logger.info(f'{data_len} tokens ({nb_unique_tokens} unique)') # unk_idx = self.params.special_tok_ids['unk_token'] # nb_unknown = sum([(t==unk_idx).sum() for t in self.token_ids]) # logger.info(f'{nb_unknown} unknown tokens (covering {100*nb_unknown/data_len:.2f}% of the data)') def _snake_case ( self :List[Any] , __A :Dict ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [t[0] for t in batch] SCREAMING_SNAKE_CASE__ = [t[1] for t in batch] assert len(__A ) == len(__A ) # Max for paddings SCREAMING_SNAKE_CASE__ = max(__A ) # Pad token ids if self.params.mlm: SCREAMING_SNAKE_CASE__ = self.params.special_tok_ids["""pad_token"""] else: SCREAMING_SNAKE_CASE__ = self.params.special_tok_ids["""unk_token"""] SCREAMING_SNAKE_CASE__ = [list(t.astype(__A ) ) + [pad_idx] * (max_seq_len_ - len(__A )) for t in token_ids] assert len(tk_ ) == len(__A ) assert all(len(__A ) == max_seq_len_ for t in tk_ ) SCREAMING_SNAKE_CASE__ = torch.tensor(tk_ ) # (bs, max_seq_len_) SCREAMING_SNAKE_CASE__ = torch.tensor(__A ) # (bs) return tk_t, lg_t
6
from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import BaseOutput, is_torch_available, is_transformers_available @dataclass class _lowerCAmelCase( UpperCAmelCase_ ): """simple docstring""" a : Union[List[PIL.Image.Image], np.ndarray] a : Optional[List[bool]] if is_transformers_available() and is_torch_available(): from .pipeline_semantic_stable_diffusion import SemanticStableDiffusionPipeline
57
0
"""simple docstring""" import pytest from datasets.splits import SplitDict, SplitInfo from datasets.utils.py_utils import asdict @pytest.mark.parametrize( 'split_dict' , [ SplitDict(), SplitDict({'train': SplitInfo(name='train' , num_bytes=13_37 , num_examples=42 , dataset_name='my_dataset' )} ), SplitDict({'train': SplitInfo(name='train' , num_bytes=13_37 , num_examples=42 )} ), SplitDict({'train': SplitInfo()} ), ] , ) def _snake_case ( _snake_case : SplitDict ) -> Optional[Any]: '''simple docstring''' _A = split_dict._to_yaml_list() assert len(_snake_case ) == len(_snake_case ) _A = SplitDict._from_yaml_list(_snake_case ) for split_name, split_info in split_dict.items(): # dataset_name field is deprecated, and is therefore not part of the YAML dump _A = None # the split name of split_dict takes over the name of the split info object _A = split_name assert split_dict == reloaded @pytest.mark.parametrize( 'split_info' , [SplitInfo(), SplitInfo(dataset_name=_snake_case ), SplitInfo(dataset_name='my_dataset' )] ) def _snake_case ( _snake_case : Any ) -> Dict: '''simple docstring''' _A = asdict(SplitDict({'train': split_info} ) ) assert "dataset_name" in split_dict_asdict["train"] assert split_dict_asdict["train"]["dataset_name"] == split_info.dataset_name
7
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConfig, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaForCTC, WavaVecaForPreTraining, WavaVecaProcessor, logging, ) from transformers.models.wavaveca.modeling_wavaveca import WavaVecaForSequenceClassification logging.set_verbosity_info() A_ : Tuple = logging.get_logger(__name__) A_ : Optional[int] = { 'post_extract_proj': 'feature_projection.projection', 'encoder.pos_conv.0': 'encoder.pos_conv_embed.conv', 'self_attn.k_proj': 'encoder.layers.*.attention.k_proj', 'self_attn.v_proj': 'encoder.layers.*.attention.v_proj', 'self_attn.q_proj': 'encoder.layers.*.attention.q_proj', 'self_attn.out_proj': 'encoder.layers.*.attention.out_proj', 'self_attn_layer_norm': 'encoder.layers.*.layer_norm', 'fc1': 'encoder.layers.*.feed_forward.intermediate_dense', 'fc2': 'encoder.layers.*.feed_forward.output_dense', 'final_layer_norm': 'encoder.layers.*.final_layer_norm', 'encoder.layer_norm': 'encoder.layer_norm', 'adapter_layer': 'encoder.layers.*.adapter_layer', 'w2v_model.layer_norm': 'feature_projection.layer_norm', 'quantizer.weight_proj': 'quantizer.weight_proj', 'quantizer.vars': 'quantizer.codevectors', 'project_q': 'project_q', 'final_proj': 'project_hid', 'w2v_encoder.proj': 'lm_head', 'mask_emb': 'masked_spec_embed', 'pooling_layer.linear': 'projector', 'pooling_layer.projection': 'classifier', } A_ : int = [ 'lm_head', 'quantizer.weight_proj', 'quantizer.codevectors', 'project_q', 'project_hid', 'projector', 'classifier', ] def snake_case (UpperCAmelCase__ ) -> str: UpperCamelCase_: Tuple = {} with open(UpperCAmelCase__ , 'r' ) as file: for line_number, line in enumerate(UpperCAmelCase__ ): UpperCamelCase_: List[Any] = line.strip() if line: UpperCamelCase_: List[Any] = line.split() UpperCamelCase_: Optional[Any] = line_number UpperCamelCase_: Any = words[0] UpperCamelCase_: List[Any] = value return result def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) -> List[str]: for attribute in key.split('.' ): UpperCamelCase_: str = getattr(UpperCAmelCase__ , UpperCAmelCase__ ) UpperCamelCase_: str = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(UpperCAmelCase__ ): UpperCamelCase_: Any = PARAM_MAPPING[full_name.split('.' )[-1]] UpperCamelCase_: Dict = 'param' if weight_type is not None and weight_type != "param": UpperCamelCase_: Optional[Any] = getattr(UpperCAmelCase__ , UpperCAmelCase__ ).shape elif weight_type is not None and weight_type == "param": UpperCamelCase_: Optional[Any] = hf_pointer for attribute in hf_param_name.split('.' ): UpperCamelCase_: str = getattr(UpperCAmelCase__ , UpperCAmelCase__ ) UpperCamelCase_: Tuple = shape_pointer.shape # let's reduce dimension UpperCamelCase_: int = value[0] else: UpperCamelCase_: Union[str, Any] = hf_pointer.shape if hf_shape != value.shape: raise ValueError( F'''Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be''' F''' {value.shape} for {full_name}''' ) if weight_type == "weight": UpperCamelCase_: Optional[int] = value elif weight_type == "weight_g": UpperCamelCase_: Any = value elif weight_type == "weight_v": UpperCamelCase_: Union[str, Any] = value elif weight_type == "bias": UpperCamelCase_: Union[str, Any] = value elif weight_type == "param": for attribute in hf_param_name.split('.' ): UpperCamelCase_: Dict = getattr(UpperCAmelCase__ , UpperCAmelCase__ ) UpperCamelCase_: Optional[Any] = value else: UpperCamelCase_: int = value logger.info(F'''{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.''' ) def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) -> Any: UpperCamelCase_: Union[str, Any] = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(UpperCAmelCase__ ): UpperCamelCase_: Dict = PARAM_MAPPING[full_name.split('.' )[-1]] UpperCamelCase_: List[Any] = 'param' if weight_type is not None and weight_type != "param": UpperCamelCase_: List[Any] = '.'.join([key, weight_type] ) elif weight_type is not None and weight_type == "param": UpperCamelCase_: Any = '.'.join([key, hf_param_name] ) else: UpperCamelCase_: Union[str, Any] = key UpperCamelCase_: Any = value if 'lm_head' in full_key else value[0] A_ : str = { 'W_a': 'linear_1.weight', 'W_b': 'linear_2.weight', 'b_a': 'linear_1.bias', 'b_b': 'linear_2.bias', 'ln_W': 'norm.weight', 'ln_b': 'norm.bias', } def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__=None , UpperCAmelCase__=None ) -> Any: UpperCamelCase_: Optional[int] = False for key, mapped_key in MAPPING.items(): UpperCamelCase_: Tuple = 'wav2vec2.' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]: UpperCamelCase_: Optional[Any] = True if "*" in mapped_key: UpperCamelCase_: Optional[int] = name.split(UpperCAmelCase__ )[0].split('.' )[-2] UpperCamelCase_: Any = mapped_key.replace('*' , UpperCAmelCase__ ) if "weight_g" in name: UpperCamelCase_: Union[str, Any] = 'weight_g' elif "weight_v" in name: UpperCamelCase_: Dict = 'weight_v' elif "bias" in name: UpperCamelCase_: int = 'bias' elif "weight" in name: # TODO: don't match quantizer.weight_proj UpperCamelCase_: str = 'weight' else: UpperCamelCase_: Union[str, Any] = None if hf_dict is not None: rename_dict(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) else: set_recursively(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) return is_used return is_used def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) -> List[str]: UpperCamelCase_: List[Any] = [] UpperCamelCase_: Dict = fairseq_model.state_dict() UpperCamelCase_: Optional[Any] = hf_model.wavaveca.feature_extractor for name, value in fairseq_dict.items(): UpperCamelCase_: Union[str, Any] = False if "conv_layers" in name: load_conv_layer( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , hf_model.config.feat_extract_norm == 'group' , ) UpperCamelCase_: List[Any] = True else: UpperCamelCase_: Tuple = load_wavaveca_layer(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) if not is_used: unused_weights.append(UpperCAmelCase__ ) logger.warning(F'''Unused weights: {unused_weights}''' ) def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) -> Any: UpperCamelCase_: Any = full_name.split('conv_layers.' )[-1] UpperCamelCase_: int = name.split('.' ) UpperCamelCase_: int = int(items[0] ) UpperCamelCase_: Union[str, Any] = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.''' ) UpperCamelCase_: Union[str, Any] = value logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.''' ) UpperCamelCase_: int = value logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.''' ) UpperCamelCase_: Union[str, Any] = value logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.''' ) UpperCamelCase_: List[Any] = value logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) else: unused_weights.append(UpperCAmelCase__ ) @torch.no_grad() def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__=None , UpperCAmelCase__=None , UpperCAmelCase__=True , UpperCAmelCase__=False ) -> Dict: if config_path is not None: UpperCamelCase_: Tuple = WavaVecaConfig.from_pretrained(UpperCAmelCase__ ) else: UpperCamelCase_: List[str] = WavaVecaConfig() if is_seq_class: UpperCamelCase_: int = read_txt_into_dict(UpperCAmelCase__ ) UpperCamelCase_: Tuple = idalabel UpperCamelCase_: str = WavaVecaForSequenceClassification(UpperCAmelCase__ ) UpperCamelCase_: Optional[int] = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6_0_0_0 , padding_value=0 , do_normalize=UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , ) feature_extractor.save_pretrained(UpperCAmelCase__ ) elif is_finetuned: if dict_path: UpperCamelCase_: List[Any] = Dictionary.load(UpperCAmelCase__ ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq UpperCamelCase_: Dict = target_dict.pad_index UpperCamelCase_: Tuple = target_dict.bos_index UpperCamelCase_: Optional[Any] = target_dict.eos_index UpperCamelCase_: Union[str, Any] = len(target_dict.symbols ) UpperCamelCase_: int = os.path.join(UpperCAmelCase__ , 'vocab.json' ) if not os.path.isdir(UpperCAmelCase__ ): logger.error('--pytorch_dump_folder_path ({}) should be a directory'.format(UpperCAmelCase__ ) ) return os.makedirs(UpperCAmelCase__ , exist_ok=UpperCAmelCase__ ) UpperCamelCase_: str = target_dict.indices # fairseq has the <pad> and <s> switched UpperCamelCase_: List[str] = 0 UpperCamelCase_: List[Any] = 1 with open(UpperCAmelCase__ , 'w' , encoding='utf-8' ) as vocab_handle: json.dump(UpperCAmelCase__ , UpperCAmelCase__ ) UpperCamelCase_: Union[str, Any] = WavaVecaCTCTokenizer( UpperCAmelCase__ , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token='|' , do_lower_case=UpperCAmelCase__ , ) UpperCamelCase_: Any = True if config.feat_extract_norm == 'layer' else False UpperCamelCase_: Tuple = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6_0_0_0 , padding_value=0 , do_normalize=UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , ) UpperCamelCase_: Dict = WavaVecaProcessor(feature_extractor=UpperCAmelCase__ , tokenizer=UpperCAmelCase__ ) processor.save_pretrained(UpperCAmelCase__ ) UpperCamelCase_: Any = WavaVecaForCTC(UpperCAmelCase__ ) else: UpperCamelCase_: Any = WavaVecaForPreTraining(UpperCAmelCase__ ) if is_finetuned or is_seq_class: UpperCamelCase_ ,UpperCamelCase_ ,UpperCamelCase_: Dict = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] )} ) else: UpperCamelCase_: List[str] = argparse.Namespace(task='audio_pretraining' ) UpperCamelCase_: Any = fairseq.tasks.setup_task(UpperCAmelCase__ ) UpperCamelCase_ ,UpperCamelCase_ ,UpperCamelCase_: Union[str, Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=UpperCAmelCase__ ) UpperCamelCase_: str = model[0].eval() recursively_load_weights(UpperCAmelCase__ , UpperCAmelCase__ , not is_finetuned ) hf_wavavec.save_pretrained(UpperCAmelCase__ ) if __name__ == "__main__": A_ : str = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint') parser.add_argument('--dict_path', default=None, type=str, help='Path to dict of fine-tuned model') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') parser.add_argument( '--not_finetuned', action='store_true', help='Whether the model to convert is a fine-tuned model or not' ) parser.add_argument( '--is_seq_class', action='store_true', help='Whether the model to convert is a fine-tuned sequence classification model or not', ) A_ : int = parser.parse_args() A_ : str = not args.not_finetuned and not args.is_seq_class convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, is_finetuned, args.is_seq_class, )
57
0
'''simple docstring''' import torch from diffusers import DiffusionPipeline class SCREAMING_SNAKE_CASE (a__ ): def __init__( self , _UpperCAmelCase , _UpperCAmelCase): '''simple docstring''' super().__init__() self.register_modules(unet=_UpperCAmelCase , scheduler=_UpperCAmelCase) def __call__( self): '''simple docstring''' __A : int = torch.randn( (1, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , ) __A : Dict = 1 __A : int = self.unet(_UpperCAmelCase , _UpperCAmelCase).sample __A : Any = self.scheduler.step(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase).prev_sample __A : int = scheduler_output - scheduler_output + torch.ones_like(_UpperCAmelCase) return result
8
import inspect import os import unittest import torch import accelerate from accelerate import debug_launcher from accelerate.test_utils import ( execute_subprocess_async, require_cpu, require_huggingface_suite, require_multi_gpu, require_single_gpu, ) from accelerate.utils import patch_environment @require_huggingface_suite class _lowerCAmelCase( unittest.TestCase ): """simple docstring""" def _a ( self ): UpperCamelCase_: Optional[int] = inspect.getfile(accelerate.test_utils ) UpperCamelCase_: Dict = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ['scripts', 'external_deps', 'test_metrics.py'] ) from accelerate.test_utils.scripts.external_deps import test_metrics # noqa: F401 UpperCamelCase_: Tuple = test_metrics @require_cpu def _a ( self ): debug_launcher(self.test_metrics.main , num_processes=1 ) @require_cpu def _a ( self ): debug_launcher(self.test_metrics.main ) @require_single_gpu def _a ( self ): self.test_metrics.main() @require_multi_gpu def _a ( self ): print(f'''Found {torch.cuda.device_count()} devices.''' ) UpperCamelCase_: List[Any] = ['torchrun', f'''--nproc_per_node={torch.cuda.device_count()}''', self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(_lowerCamelCase , env=os.environ.copy() )
57
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 __lowerCAmelCase ( UpperCAmelCase_ ): """simple docstring""" A__ : str = ["image_processor", "tokenizer"] A__ : str = "LayoutLMv3ImageProcessor" A__ : Tuple = ("LayoutLMv3Tokenizer", "LayoutLMv3TokenizerFast") def __init__( self : Optional[int] , _snake_case : Optional[int]=None , _snake_case : Optional[int]=None , **_snake_case : int ): """simple docstring""" A__ = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , _snake_case , ) A__ = kwargs.pop('feature_extractor' ) A__ = 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__(_snake_case , _snake_case ) def __call__( self : Optional[int] , _snake_case : List[str] , _snake_case : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , _snake_case : Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None , _snake_case : Union[List[List[int]], List[List[List[int]]]] = None , _snake_case : Optional[Union[List[int], List[List[int]]]] = None , _snake_case : bool = True , _snake_case : Union[bool, str, PaddingStrategy] = False , _snake_case : Union[bool, str, TruncationStrategy] = None , _snake_case : Optional[int] = None , _snake_case : int = 0 , _snake_case : Optional[int] = None , _snake_case : Optional[bool] = None , _snake_case : Optional[bool] = None , _snake_case : bool = False , _snake_case : bool = False , _snake_case : bool = False , _snake_case : bool = False , _snake_case : bool = True , _snake_case : Optional[Union[str, TensorType]] = None , **_snake_case : Optional[Any] , ): """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 A__ = self.image_processor(images=_snake_case , return_tensors=_snake_case ) # second, apply the tokenizer if text is not None and self.image_processor.apply_ocr and text_pair is None: if isinstance(_snake_case , _snake_case ): A__ = [text] # add batch dimension (as the image processor always adds a batch dimension) A__ = features['words'] A__ = 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=_snake_case , add_special_tokens=_snake_case , padding=_snake_case , truncation=_snake_case , max_length=_snake_case , stride=_snake_case , pad_to_multiple_of=_snake_case , return_token_type_ids=_snake_case , return_attention_mask=_snake_case , return_overflowing_tokens=_snake_case , return_special_tokens_mask=_snake_case , return_offsets_mapping=_snake_case , return_length=_snake_case , verbose=_snake_case , return_tensors=_snake_case , **_snake_case , ) # add pixel values A__ = features.pop('pixel_values' ) if return_overflowing_tokens is True: A__ = self.get_overflowing_images(_snake_case , encoded_inputs['overflow_to_sample_mapping'] ) A__ = images return encoded_inputs def _a ( self : int , _snake_case : List[str] , _snake_case : Union[str, Any] ): """simple docstring""" A__ = [] for sample_idx in overflow_to_sample_mapping: images_with_overflow.append(images[sample_idx] ) if len(_snake_case ) != len(_snake_case ): raise ValueError( 'Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got' F''' {len(_snake_case )} and {len(_snake_case )}''' ) return images_with_overflow def _a ( self : Union[str, Any] , *_snake_case : List[Any] , **_snake_case : Any ): """simple docstring""" return self.tokenizer.batch_decode(*_snake_case , **_snake_case ) def _a ( self : List[str] , *_snake_case : Optional[int] , **_snake_case : int ): """simple docstring""" return self.tokenizer.decode(*_snake_case , **_snake_case ) @property def _a ( self : Optional[Any] ): """simple docstring""" return ["input_ids", "bbox", "attention_mask", "pixel_values"] @property def _a ( self : Any ): """simple docstring""" warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , _snake_case , ) return self.image_processor_class @property def _a ( self : int ): """simple docstring""" warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , _snake_case , ) return self.image_processor
9
import math class _lowerCAmelCase: """simple docstring""" def _a ( self , _lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: int = 0.0 UpperCamelCase_: Tuple = 0.0 for i in range(len(_lowerCamelCase ) ): da += math.pow((sample[i] - weights[0][i]) , 2 ) da += math.pow((sample[i] - weights[1][i]) , 2 ) return 0 if da > da else 1 return 0 def _a ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): for i in range(len(_lowerCamelCase ) ): weights[j][i] += alpha * (sample[i] - weights[j][i]) return weights def snake_case () -> None: # Training Examples ( m, n ) UpperCamelCase_: List[str] = [[1, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 1, 1]] # weight initialization ( n, C ) UpperCamelCase_: List[Any] = [[0.2, 0.6, 0.5, 0.9], [0.8, 0.4, 0.7, 0.3]] # training UpperCamelCase_: Dict = SelfOrganizingMap() UpperCamelCase_: List[Any] = 3 UpperCamelCase_: List[str] = 0.5 for _ in range(UpperCAmelCase__ ): for j in range(len(UpperCAmelCase__ ) ): # training sample UpperCamelCase_: int = training_samples[j] # Compute the winning vector UpperCamelCase_: Tuple = self_organizing_map.get_winner(UpperCAmelCase__ , UpperCAmelCase__ ) # Update the winning vector UpperCamelCase_: Union[str, Any] = self_organizing_map.update(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) # classify test sample UpperCamelCase_: Dict = [0, 0, 0, 1] UpperCamelCase_: Union[str, Any] = self_organizing_map.get_winner(UpperCAmelCase__ , UpperCAmelCase__ ) # results print(F'''Clusters that the test sample belongs to : {winner}''' ) print(F'''Weights that have been trained : {weights}''' ) # running the main() function if __name__ == "__main__": main()
57
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) _lowerCAmelCase = {"configuration_reformer": ["REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "ReformerConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase = ["ReformerTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase = ["ReformerTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase = [ "REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "ReformerAttention", "ReformerForMaskedLM", "ReformerForQuestionAnswering", "ReformerForSequenceClassification", "ReformerLayer", "ReformerModel", "ReformerModelWithLMHead", "ReformerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_reformer import REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ReformerConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer import ReformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer_fast import ReformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_reformer import ( REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ReformerAttention, ReformerForMaskedLM, ReformerForQuestionAnswering, ReformerForSequenceClassification, ReformerLayer, ReformerModel, ReformerModelWithLMHead, ReformerPreTrainedModel, ) else: import sys _lowerCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
10
from collections import namedtuple A_ : Tuple = namedtuple('from_to', 'from_ to') A_ : int = { 'cubicmeter': from_to(1, 1), 'litre': from_to(0.001, 1000), 'kilolitre': from_to(1, 1), 'gallon': from_to(0.00454, 264.172), 'cubicyard': from_to(0.76455, 1.30795), 'cubicfoot': from_to(0.028, 35.3147), 'cup': from_to(0.000236588, 4226.75), } def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) -> float: if from_type not in METRIC_CONVERSION: raise ValueError( F'''Invalid \'from_type\' value: {from_type!r} Supported values are:\n''' + ', '.join(UpperCAmelCase__ ) ) if to_type not in METRIC_CONVERSION: raise ValueError( F'''Invalid \'to_type\' value: {to_type!r}. Supported values are:\n''' + ', '.join(UpperCAmelCase__ ) ) return value * METRIC_CONVERSION[from_type].from_ * METRIC_CONVERSION[to_type].to if __name__ == "__main__": import doctest doctest.testmod()
57
0
'''simple docstring''' import inspect from typing import Optional, Union import numpy as np import PIL import torch from torch.nn import functional as F from torchvision import transforms from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, DPMSolverMultistepScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput from diffusers.utils import ( PIL_INTERPOLATION, randn_tensor, ) def lowerCAmelCase (__A , __A , __A): """simple docstring""" if isinstance(__A , torch.Tensor): return image elif isinstance(__A , PIL.Image.Image): _a = [image] if isinstance(image[0] , PIL.Image.Image): _a = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION['''lanczos''']))[None, :] for i in image] _a = np.concatenate(__A , axis=0) _a = np.array(__A).astype(np.floataa) / 2_55.0 _a = image.transpose(0 , 3 , 1 , 2) _a = 2.0 * image - 1.0 _a = torch.from_numpy(__A) elif isinstance(image[0] , torch.Tensor): _a = torch.cat(__A , dim=0) return image def lowerCAmelCase (__A , __A , __A , __A=0.99_95): """simple docstring""" if not isinstance(__A , np.ndarray): _a = True _a = va.device _a = va.cpu().numpy() _a = va.cpu().numpy() _a = np.sum(va * va / (np.linalg.norm(__A) * np.linalg.norm(__A))) if np.abs(__A) > DOT_THRESHOLD: _a = (1 - t) * va + t * va else: _a = np.arccos(__A) _a = np.sin(__A) _a = theta_a * t _a = np.sin(__A) _a = np.sin(theta_a - theta_t) / sin_theta_a _a = sin_theta_t / sin_theta_a _a = sa * va + sa * va if inputs_are_torch: _a = torch.from_numpy(__A).to(__A) return va def lowerCAmelCase (__A , __A): """simple docstring""" _a = F.normalize(__A , dim=-1) _a = F.normalize(__A , dim=-1) return (x - y).norm(dim=-1).div(2).arcsin().pow(2).mul(2) def lowerCAmelCase (__A , __A): """simple docstring""" for param in model.parameters(): _a = value class __A ( A ): '''simple docstring''' def __init__(self , A , A , A , A , A , A , A , A=None , A=None , A=None , ) -> str: """simple docstring""" super().__init__() self.register_modules( vae=A , text_encoder=A , clip_model=A , tokenizer=A , unet=A , scheduler=A , feature_extractor=A , coca_model=A , coca_tokenizer=A , coca_transform=A , ) _a = ( feature_extractor.size if isinstance(feature_extractor.size , A ) else feature_extractor.size['''shortest_edge'''] ) _a = transforms.Normalize(mean=feature_extractor.image_mean , std=feature_extractor.image_std ) set_requires_grad(self.text_encoder , A ) set_requires_grad(self.clip_model , A ) def a__ (self , A = "auto" ) -> Union[str, Any]: """simple docstring""" if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory _a = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(A ) def a__ (self ) -> Optional[Any]: """simple docstring""" self.enable_attention_slicing(A ) def a__ (self ) -> int: """simple docstring""" set_requires_grad(self.vae , A ) def a__ (self ) -> Union[str, Any]: """simple docstring""" set_requires_grad(self.vae , A ) def a__ (self ) -> Dict: """simple docstring""" set_requires_grad(self.unet , A ) def a__ (self ) -> str: """simple docstring""" set_requires_grad(self.unet , A ) def a__ (self , A , A , A ) -> Optional[Any]: """simple docstring""" _a = min(int(num_inference_steps * strength ) , A ) _a = max(num_inference_steps - init_timestep , 0 ) _a = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def a__ (self , A , A , A , A , A , A=None ) -> List[str]: """simple docstring""" if not isinstance(A , torch.Tensor ): raise ValueError(f'''`image` has to be of type `torch.Tensor` but is {type(A )}''' ) _a = image.to(device=A , dtype=A ) if isinstance(A , A ): _a = [ self.vae.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(A ) ] _a = torch.cat(A , dim=0 ) else: _a = self.vae.encode(A ).latent_dist.sample(A ) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor _a = 0.18215 * init_latents _a = init_latents.repeat_interleave(A , dim=0 ) _a = randn_tensor(init_latents.shape , generator=A , device=A , dtype=A ) # get latents _a = self.scheduler.add_noise(A , A , A ) _a = init_latents return latents def a__ (self , A ) -> Tuple: """simple docstring""" _a = self.coca_transform(A ).unsqueeze(0 ) with torch.no_grad(), torch.cuda.amp.autocast(): _a = self.coca_model.generate(transformed_image.to(device=self.device , dtype=self.coca_model.dtype ) ) _a = self.coca_tokenizer.decode(generated[0].cpu().numpy() ) return generated.split('''<end_of_text>''' )[0].replace('''<start_of_text>''' , '''''' ).rstrip(''' .,''' ) def a__ (self , A , A ) -> List[Any]: """simple docstring""" _a = self.feature_extractor.preprocess(A ) _a = torch.from_numpy(clip_image_input['''pixel_values'''][0] ).unsqueeze(0 ).to(self.device ).half() _a = self.clip_model.get_image_features(A ) _a = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=A ) _a = image_embeddings_clip.repeat_interleave(A , dim=0 ) return image_embeddings_clip @torch.enable_grad() def a__ (self , A , A , A , A , A , A , A , ) -> Union[str, Any]: """simple docstring""" _a = latents.detach().requires_grad_() _a = self.scheduler.scale_model_input(A , A ) # predict the noise residual _a = self.unet(A , A , encoder_hidden_states=A ).sample if isinstance(self.scheduler , (PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler) ): _a = self.scheduler.alphas_cumprod[timestep] _a = 1 - alpha_prod_t # compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf _a = (latents - beta_prod_t ** 0.5 * noise_pred) / alpha_prod_t ** 0.5 _a = torch.sqrt(A ) _a = pred_original_sample * (fac) + latents * (1 - fac) elif isinstance(self.scheduler , A ): _a = self.scheduler.sigmas[index] _a = latents - sigma * noise_pred else: raise ValueError(f'''scheduler type {type(self.scheduler )} not supported''' ) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor _a = 1 / 0.18215 * sample _a = self.vae.decode(A ).sample _a = (image / 2 + 0.5).clamp(0 , 1 ) _a = transforms.Resize(self.feature_extractor_size )(A ) _a = self.normalize(A ).to(latents.dtype ) _a = self.clip_model.get_image_features(A ) _a = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=A ) _a = spherical_dist_loss(A , A ).mean() * clip_guidance_scale _a = -torch.autograd.grad(A , A )[0] if isinstance(self.scheduler , A ): _a = latents.detach() + grads * (sigma**2) _a = noise_pred_original else: _a = noise_pred_original - torch.sqrt(A ) * grads return noise_pred, latents @torch.no_grad() def __call__(self , A , A , A = None , A = None , A = 512 , A = 512 , A = 0.6 , A = 50 , A = 7.5 , A = 1 , A = 0.0 , A = 100 , A = None , A = "pil" , A = True , A = 0.8 , A = 0.1 , A = 0.1 , ) -> str: """simple docstring""" if isinstance(A , A ) and len(A ) != batch_size: raise ValueError(f'''You have passed {batch_size} batch_size, but only {len(A )} generators.''' ) if height % 8 != 0 or width % 8 != 0: raise ValueError(f'''`height` and `width` have to be divisible by 8 but are {height} and {width}.''' ) if isinstance(A , torch.Generator ) and batch_size > 1: _a = [generator] + [None] * (batch_size - 1) _a = [ ('''model''', self.coca_model is None), ('''tokenizer''', self.coca_tokenizer is None), ('''transform''', self.coca_transform is None), ] _a = [x[0] for x in coca_is_none if x[1]] _a = ''', '''.join(A ) # generate prompts with coca model if prompt is None if content_prompt is None: if len(A ): raise ValueError( f'''Content prompt is None and CoCa [{coca_is_none_str}] is None.''' f'''Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.''' ) _a = self.get_image_description(A ) if style_prompt is None: if len(A ): raise ValueError( f'''Style prompt is None and CoCa [{coca_is_none_str}] is None.''' f''' Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.''' ) _a = self.get_image_description(A ) # get prompt text embeddings for content and style _a = self.tokenizer( A , padding='''max_length''' , max_length=self.tokenizer.model_max_length , truncation=A , return_tensors='''pt''' , ) _a = self.text_encoder(content_text_input.input_ids.to(self.device ) )[0] _a = self.tokenizer( A , padding='''max_length''' , max_length=self.tokenizer.model_max_length , truncation=A , return_tensors='''pt''' , ) _a = self.text_encoder(style_text_input.input_ids.to(self.device ) )[0] _a = slerp(A , A , A ) # duplicate text embeddings for each generation per prompt _a = text_embeddings.repeat_interleave(A , dim=0 ) # set timesteps _a = '''offset''' in set(inspect.signature(self.scheduler.set_timesteps ).parameters.keys() ) _a = {} if accepts_offset: _a = 1 self.scheduler.set_timesteps(A , **A ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand self.scheduler.timesteps.to(self.device ) _a , _a = self.get_timesteps(A , A , self.device ) _a = timesteps[:1].repeat(A ) # Preprocess image _a = preprocess(A , A , A ) _a = self.prepare_latents( A , A , A , text_embeddings.dtype , self.device , A ) _a = preprocess(A , A , A ) _a = self.prepare_latents( A , A , A , text_embeddings.dtype , self.device , A ) _a = slerp(A , A , A ) if clip_guidance_scale > 0: _a = self.get_clip_image_embeddings(A , A ) _a = self.get_clip_image_embeddings(A , A ) _a = slerp( A , A , A ) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. _a = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: _a = content_text_input.input_ids.shape[-1] _a = self.tokenizer([''''''] , padding='''max_length''' , max_length=A , return_tensors='''pt''' ) _a = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt _a = uncond_embeddings.repeat_interleave(A , dim=0 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes _a = torch.cat([uncond_embeddings, text_embeddings] ) # get the initial random noise unless the user supplied it # Unlike in other pipelines, latents need to be generated in the target device # for 1-to-1 results reproducibility with the CompVis implementation. # However this currently doesn't work in `mps`. _a = (batch_size, self.unet.config.in_channels, height // 8, width // 8) _a = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not work reproducibly on mps _a = torch.randn(A , generator=A , device='''cpu''' , dtype=A ).to( self.device ) else: _a = torch.randn(A , generator=A , device=self.device , dtype=A ) else: if latents.shape != latents_shape: raise ValueError(f'''Unexpected latents shape, got {latents.shape}, expected {latents_shape}''' ) _a = latents.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler _a = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] _a = '''eta''' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) _a = {} if accepts_eta: _a = eta # check if the scheduler accepts generator _a = '''generator''' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) if accepts_generator: _a = generator with self.progress_bar(total=A ): for i, t in enumerate(A ): # expand the latents if we are doing classifier free guidance _a = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents _a = self.scheduler.scale_model_input(A , A ) # predict the noise residual _a = self.unet(A , A , encoder_hidden_states=A ).sample # perform classifier free guidance if do_classifier_free_guidance: _a , _a = noise_pred.chunk(2 ) _a = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # perform clip guidance if clip_guidance_scale > 0: _a = ( text_embeddings.chunk(2 )[1] if do_classifier_free_guidance else text_embeddings ) _a , _a = self.cond_fn( A , A , A , A , A , A , A , ) # compute the previous noisy sample x_t -> x_t-1 _a = self.scheduler.step(A , A , A , **A ).prev_sample # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor _a = 1 / 0.18215 * latents _a = self.vae.decode(A ).sample _a = (image / 2 + 0.5).clamp(0 , 1 ) _a = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": _a = self.numpy_to_pil(A ) if not return_dict: return (image, None) return StableDiffusionPipelineOutput(images=A , nsfw_content_detected=A )
11
import warnings from ...utils import logging from .image_processing_clip import CLIPImageProcessor A_ : int = logging.get_logger(__name__) class _lowerCAmelCase( UpperCAmelCase_ ): """simple docstring""" def __init__( self , *_lowerCamelCase , **_lowerCamelCase ): warnings.warn( 'The class CLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use CLIPImageProcessor instead.' , _lowerCamelCase , ) super().__init__(*_lowerCamelCase , **_lowerCamelCase )
57
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available lowerCamelCase__ : str = { """configuration_altclip""": [ """ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP""", """AltCLIPConfig""", """AltCLIPTextConfig""", """AltCLIPVisionConfig""", ], """processing_altclip""": ["""AltCLIPProcessor"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ : Union[str, Any] = [ """ALTCLIP_PRETRAINED_MODEL_ARCHIVE_LIST""", """AltCLIPPreTrainedModel""", """AltCLIPModel""", """AltCLIPTextModel""", """AltCLIPVisionModel""", ] if TYPE_CHECKING: from .configuration_altclip import ( ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, AltCLIPConfig, AltCLIPTextConfig, AltCLIPVisionConfig, ) from .processing_altclip import AltCLIPProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_altclip import ( ALTCLIP_PRETRAINED_MODEL_ARCHIVE_LIST, AltCLIPModel, AltCLIPPreTrainedModel, AltCLIPTextModel, AltCLIPVisionModel, ) else: import sys lowerCamelCase__ : List[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
12
import math from typing import Any, Callable, List, Optional, Tuple, Union import numpy as np import torch from ...models import TaFilmDecoder from ...schedulers import DDPMScheduler from ...utils import is_onnx_available, logging, randn_tensor if is_onnx_available(): from ..onnx_utils import OnnxRuntimeModel from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline from .continous_encoder import SpectrogramContEncoder from .notes_encoder import SpectrogramNotesEncoder A_ : List[Any] = logging.get_logger(__name__) # pylint: disable=invalid-name A_ : Optional[int] = 256 class _lowerCAmelCase( UpperCAmelCase_ ): """simple docstring""" a : Union[str, Any] =['''melgan'''] def __init__( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , ): super().__init__() # From MELGAN UpperCamelCase_: Any = math.log(1e-5 ) # Matches MelGAN training. UpperCamelCase_: List[Any] = 4.0 # Largest value for most examples UpperCamelCase_: Tuple = 1_2_8 self.register_modules( notes_encoder=_lowerCamelCase , continuous_encoder=_lowerCamelCase , decoder=_lowerCamelCase , scheduler=_lowerCamelCase , melgan=_lowerCamelCase , ) def _a ( self , _lowerCamelCase , _lowerCamelCase=(-1.0, 1.0) , _lowerCamelCase=False ): UpperCamelCase_ ,UpperCamelCase_: Union[str, Any] = output_range if clip: UpperCamelCase_: int = torch.clip(_lowerCamelCase , self.min_value , self.max_value ) # Scale to [0, 1]. UpperCamelCase_: List[Any] = (features - self.min_value) / (self.max_value - self.min_value) # Scale to [min_out, max_out]. return zero_one * (max_out - min_out) + min_out def _a ( self , _lowerCamelCase , _lowerCamelCase=(-1.0, 1.0) , _lowerCamelCase=False ): UpperCamelCase_ ,UpperCamelCase_: Dict = input_range UpperCamelCase_: List[str] = torch.clip(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) if clip else outputs # Scale to [0, 1]. UpperCamelCase_: Optional[Any] = (outputs - min_out) / (max_out - min_out) # Scale to [self.min_value, self.max_value]. return zero_one * (self.max_value - self.min_value) + self.min_value def _a ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: str = input_tokens > 0 UpperCamelCase_ ,UpperCamelCase_: Tuple = self.notes_encoder( encoder_input_tokens=_lowerCamelCase , encoder_inputs_mask=_lowerCamelCase ) UpperCamelCase_ ,UpperCamelCase_: Any = self.continuous_encoder( encoder_inputs=_lowerCamelCase , encoder_inputs_mask=_lowerCamelCase ) return [(tokens_encoded, tokens_mask), (continuous_encoded, continuous_mask)] def _a ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: Dict = noise_time if not torch.is_tensor(_lowerCamelCase ): UpperCamelCase_: List[str] = torch.tensor([timesteps] , dtype=torch.long , device=input_tokens.device ) elif torch.is_tensor(_lowerCamelCase ) and len(timesteps.shape ) == 0: UpperCamelCase_: Dict = timesteps[None].to(input_tokens.device ) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML UpperCamelCase_: Union[str, Any] = timesteps * torch.ones(input_tokens.shape[0] , dtype=timesteps.dtype , device=timesteps.device ) UpperCamelCase_: Any = self.decoder( encodings_and_masks=_lowerCamelCase , decoder_input_tokens=_lowerCamelCase , decoder_noise_time=_lowerCamelCase ) return logits @torch.no_grad() def __call__( self , _lowerCamelCase , _lowerCamelCase = None , _lowerCamelCase = 1_0_0 , _lowerCamelCase = True , _lowerCamelCase = "numpy" , _lowerCamelCase = None , _lowerCamelCase = 1 , ): if (callback_steps is None) or ( callback_steps is not None and (not isinstance(_lowerCamelCase , _lowerCamelCase ) or callback_steps <= 0) ): raise ValueError( f'''`callback_steps` has to be a positive integer but is {callback_steps} of type''' f''' {type(_lowerCamelCase )}.''' ) UpperCamelCase_: List[str] = np.zeros([1, TARGET_FEATURE_LENGTH, self.n_dims] , dtype=np.floataa ) UpperCamelCase_: str = np.zeros([1, 0, self.n_dims] , np.floataa ) UpperCamelCase_: Dict = torch.ones((1, TARGET_FEATURE_LENGTH) , dtype=_lowerCamelCase , device=self.device ) for i, encoder_input_tokens in enumerate(_lowerCamelCase ): if i == 0: UpperCamelCase_: str = torch.from_numpy(pred_mel[:1].copy() ).to( device=self.device , dtype=self.decoder.dtype ) # The first chunk has no previous context. UpperCamelCase_: Tuple = torch.zeros((1, TARGET_FEATURE_LENGTH) , dtype=_lowerCamelCase , device=self.device ) else: # The full song pipeline does not feed in a context feature, so the mask # will be all 0s after the feature converter. Because we know we're # feeding in a full context chunk from the previous prediction, set it # to all 1s. UpperCamelCase_: Any = ones UpperCamelCase_: str = self.scale_features( _lowerCamelCase , output_range=[-1.0, 1.0] , clip=_lowerCamelCase ) UpperCamelCase_: Union[str, Any] = self.encode( input_tokens=torch.IntTensor([encoder_input_tokens] ).to(device=self.device ) , continuous_inputs=_lowerCamelCase , continuous_mask=_lowerCamelCase , ) # Sample encoder_continuous_inputs shaped gaussian noise to begin loop UpperCamelCase_: List[str] = randn_tensor( shape=encoder_continuous_inputs.shape , generator=_lowerCamelCase , device=self.device , dtype=self.decoder.dtype , ) # set step values self.scheduler.set_timesteps(_lowerCamelCase ) # Denoising diffusion loop for j, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): UpperCamelCase_: int = self.decode( encodings_and_masks=_lowerCamelCase , input_tokens=_lowerCamelCase , noise_time=t / self.scheduler.config.num_train_timesteps , ) # Compute previous output: x_t -> x_t-1 UpperCamelCase_: Tuple = self.scheduler.step(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , generator=_lowerCamelCase ).prev_sample UpperCamelCase_: List[Any] = self.scale_to_features(_lowerCamelCase , input_range=[-1.0, 1.0] ) UpperCamelCase_: Any = mel[:1] UpperCamelCase_: List[str] = mel.cpu().float().numpy() UpperCamelCase_: Tuple = np.concatenate([full_pred_mel, pred_mel[:1]] , axis=1 ) # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(_lowerCamelCase , _lowerCamelCase ) logger.info('Generated segment' , _lowerCamelCase ) if output_type == "numpy" and not is_onnx_available(): raise ValueError( 'Cannot return output in \'np\' format if ONNX is not available. Make sure to have ONNX installed or set \'output_type\' to \'mel\'.' ) elif output_type == "numpy" and self.melgan is None: raise ValueError( 'Cannot return output in \'np\' format if melgan component is not defined. Make sure to define `self.melgan` or set \'output_type\' to \'mel\'.' ) if output_type == "numpy": UpperCamelCase_: int = self.melgan(input_features=full_pred_mel.astype(np.floataa ) ) else: UpperCamelCase_: int = full_pred_mel if not return_dict: return (output,) return AudioPipelineOutput(audios=_lowerCamelCase )
57
0
'''simple docstring''' import sys from collections import defaultdict class UpperCAmelCase_ : """simple docstring""" def __init__( self ) -> int: __lowerCamelCase : Any = [] def lowercase_ ( self , SCREAMING_SNAKE_CASE_ ) -> Any: return self.node_position[vertex] def lowercase_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Tuple: __lowerCamelCase : Optional[int] = pos def lowercase_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> int: if start > size // 2 - 1: return else: if 2 * start + 2 >= size: __lowerCamelCase : str = 2 * start + 1 else: if heap[2 * start + 1] < heap[2 * start + 2]: __lowerCamelCase : Optional[Any] = 2 * start + 1 else: __lowerCamelCase : int = 2 * start + 2 if heap[smallest_child] < heap[start]: __lowerCamelCase , __lowerCamelCase : Optional[Any] = heap[smallest_child], positions[smallest_child] __lowerCamelCase , __lowerCamelCase : int = ( heap[start], positions[start], ) __lowerCamelCase , __lowerCamelCase : str = temp, tempa __lowerCamelCase : Dict = self.get_position(positions[smallest_child] ) self.set_position( positions[smallest_child] , self.get_position(positions[start] ) ) self.set_position(positions[start] , SCREAMING_SNAKE_CASE_ ) self.top_to_bottom(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def lowercase_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Any: __lowerCamelCase : Any = position[index] while index != 0: __lowerCamelCase : Union[str, Any] = int((index - 2) / 2 ) if index % 2 == 0 else int((index - 1) / 2 ) if val < heap[parent]: __lowerCamelCase : Union[str, Any] = heap[parent] __lowerCamelCase : Any = position[parent] self.set_position(position[parent] , SCREAMING_SNAKE_CASE_ ) else: __lowerCamelCase : Tuple = val __lowerCamelCase : List[str] = temp self.set_position(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) break __lowerCamelCase : Tuple = parent else: __lowerCamelCase : Union[str, Any] = val __lowerCamelCase : Tuple = temp self.set_position(SCREAMING_SNAKE_CASE_ , 0 ) def lowercase_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Optional[int]: __lowerCamelCase : Optional[int] = len(SCREAMING_SNAKE_CASE_ ) // 2 - 1 for i in range(SCREAMING_SNAKE_CASE_ , -1 , -1 ): self.top_to_bottom(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , len(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) def lowercase_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> List[Any]: __lowerCamelCase : Any = positions[0] __lowerCamelCase : Union[str, Any] = sys.maxsize self.top_to_bottom(SCREAMING_SNAKE_CASE_ , 0 , len(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) return temp def UpperCAmelCase__ ( UpperCAmelCase_ : Optional[int] ) -> str: __lowerCamelCase : List[Any] = Heap() __lowerCamelCase : Optional[int] = [0] * len(UpperCAmelCase_ ) __lowerCamelCase : str = [-1] * len(UpperCAmelCase_ ) # Neighboring Tree Vertex of selected vertex # Minimum Distance of explored vertex with neighboring vertex of partial tree # formed in graph __lowerCamelCase : List[str] = [] # Heap of Distance of vertices from their neighboring vertex __lowerCamelCase : Tuple = [] for vertex in range(len(UpperCAmelCase_ ) ): distance_tv.append(sys.maxsize ) positions.append(UpperCAmelCase_ ) heap.node_position.append(UpperCAmelCase_ ) __lowerCamelCase : Tuple = [] __lowerCamelCase : Dict = 1 __lowerCamelCase : str = sys.maxsize for neighbor, distance in adjacency_list[0]: __lowerCamelCase : Any = 0 __lowerCamelCase : Any = distance heap.heapify(UpperCAmelCase_ , UpperCAmelCase_ ) for _ in range(1 , len(UpperCAmelCase_ ) ): __lowerCamelCase : List[Any] = heap.delete_minimum(UpperCAmelCase_ , UpperCAmelCase_ ) if visited[vertex] == 0: tree_edges.append((nbr_tv[vertex], vertex) ) __lowerCamelCase : Union[str, Any] = 1 for neighbor, distance in adjacency_list[vertex]: if ( visited[neighbor] == 0 and distance < distance_tv[heap.get_position(UpperCAmelCase_ )] ): __lowerCamelCase : Dict = distance heap.bottom_to_top( UpperCAmelCase_ , heap.get_position(UpperCAmelCase_ ) , UpperCAmelCase_ , UpperCAmelCase_ ) __lowerCamelCase : str = vertex return tree_edges if __name__ == "__main__": # pragma: no cover # < --------- Prims Algorithm --------- > A__ : Tuple = int(input("""Enter number of edges: """).strip()) A__ : str = defaultdict(list) for _ in range(edges_number): A__ : Optional[int] = [int(x) for x in input().strip().split()] adjacency_list[edge[0]].append([edge[1], edge[2]]) adjacency_list[edge[1]].append([edge[0], edge[2]]) print(prisms_algorithm(adjacency_list))
13
import itertools from dataclasses import dataclass from typing import Any, Callable, Dict, List, Optional, Union import pandas as pd import pyarrow as pa import datasets import datasets.config from datasets.features.features import require_storage_cast from datasets.table import table_cast from datasets.utils.py_utils import Literal A_ : Union[str, Any] = datasets.utils.logging.get_logger(__name__) A_ : Optional[Any] = ['names', 'prefix'] A_ : List[str] = ['warn_bad_lines', 'error_bad_lines', 'mangle_dupe_cols'] A_ : List[Any] = ['encoding_errors', 'on_bad_lines'] A_ : Optional[Any] = ['date_format'] @dataclass class _lowerCAmelCase( datasets.BuilderConfig ): """simple docstring""" a : str ="," a : Optional[str] =None a : Optional[Union[int, List[int], str]] ="infer" a : Optional[List[str]] =None a : Optional[List[str]] =None a : Optional[Union[int, str, List[int], List[str]]] =None a : Optional[Union[List[int], List[str]]] =None a : Optional[str] =None a : bool =True a : Optional[Literal["c", "python", "pyarrow"]] =None a : Dict[Union[int, str], Callable[[Any], Any]] =None a : Optional[list] =None a : Optional[list] =None a : bool =False a : Optional[Union[int, List[int]]] =None a : Optional[int] =None a : Optional[Union[str, List[str]]] =None a : bool =True a : bool =True a : bool =False a : bool =True a : Optional[str] =None a : str ="." a : Optional[str] =None a : str ='"' a : int =0 a : Optional[str] =None a : Optional[str] =None a : Optional[str] =None a : Optional[str] =None a : bool =True a : bool =True a : int =0 a : bool =True a : bool =False a : Optional[str] =None a : int =10000 a : Optional[datasets.Features] =None a : Optional[str] ="strict" a : Literal["error", "warn", "skip"] ="error" a : Optional[str] =None def _a ( self ): if self.delimiter is not None: UpperCamelCase_: Optional[Any] = self.delimiter if self.column_names is not None: UpperCamelCase_: int = self.column_names @property def _a ( self ): UpperCamelCase_: Any = { 'sep': self.sep, 'header': self.header, 'names': self.names, 'index_col': self.index_col, 'usecols': self.usecols, 'prefix': self.prefix, 'mangle_dupe_cols': self.mangle_dupe_cols, 'engine': self.engine, 'converters': self.converters, 'true_values': self.true_values, 'false_values': self.false_values, 'skipinitialspace': self.skipinitialspace, 'skiprows': self.skiprows, 'nrows': self.nrows, 'na_values': self.na_values, 'keep_default_na': self.keep_default_na, 'na_filter': self.na_filter, 'verbose': self.verbose, 'skip_blank_lines': self.skip_blank_lines, 'thousands': self.thousands, 'decimal': self.decimal, 'lineterminator': self.lineterminator, 'quotechar': self.quotechar, 'quoting': self.quoting, 'escapechar': self.escapechar, 'comment': self.comment, 'encoding': self.encoding, 'dialect': self.dialect, 'error_bad_lines': self.error_bad_lines, 'warn_bad_lines': self.warn_bad_lines, 'skipfooter': self.skipfooter, 'doublequote': self.doublequote, 'memory_map': self.memory_map, 'float_precision': self.float_precision, 'chunksize': self.chunksize, 'encoding_errors': self.encoding_errors, 'on_bad_lines': self.on_bad_lines, 'date_format': self.date_format, } # some kwargs must not be passed if they don't have a default value # some others are deprecated and we can also not pass them if they are the default value for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS: if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig() , _lowerCamelCase ): del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 2.0 new arguments if not (datasets.config.PANDAS_VERSION.major >= 2): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 1.3 new arguments if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] return pd_read_csv_kwargs class _lowerCAmelCase( datasets.ArrowBasedBuilder ): """simple docstring""" a : Dict =CsvConfig def _a ( self ): return datasets.DatasetInfo(features=self.config.features ) def _a ( self , _lowerCamelCase ): if not self.config.data_files: raise ValueError(f'''At least one data file must be specified, but got data_files={self.config.data_files}''' ) UpperCamelCase_: Tuple = dl_manager.download_and_extract(self.config.data_files ) if isinstance(_lowerCamelCase , (str, list, tuple) ): UpperCamelCase_: List[Any] = data_files if isinstance(_lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: str = [files] UpperCamelCase_: Tuple = [dl_manager.iter_files(_lowerCamelCase ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'files': files} )] UpperCamelCase_: Tuple = [] for split_name, files in data_files.items(): if isinstance(_lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: Dict = [files] UpperCamelCase_: int = [dl_manager.iter_files(_lowerCamelCase ) for file in files] splits.append(datasets.SplitGenerator(name=_lowerCamelCase , gen_kwargs={'files': files} ) ) return splits def _a ( self , _lowerCamelCase ): if self.config.features is not None: UpperCamelCase_: List[Any] = self.config.features.arrow_schema if all(not require_storage_cast(_lowerCamelCase ) for feature in self.config.features.values() ): # cheaper cast UpperCamelCase_: Optional[int] = pa.Table.from_arrays([pa_table[field.name] for field in schema] , schema=_lowerCamelCase ) else: # more expensive cast; allows str <-> int/float or str to Audio for example UpperCamelCase_: int = table_cast(_lowerCamelCase , _lowerCamelCase ) return pa_table def _a ( self , _lowerCamelCase ): UpperCamelCase_: List[str] = self.config.features.arrow_schema if self.config.features else None # dtype allows reading an int column as str UpperCamelCase_: Dict = ( { name: dtype.to_pandas_dtype() if not require_storage_cast(_lowerCamelCase ) else object for name, dtype, feature in zip(schema.names , schema.types , self.config.features.values() ) } if schema is not None else None ) for file_idx, file in enumerate(itertools.chain.from_iterable(_lowerCamelCase ) ): UpperCamelCase_: Optional[Any] = pd.read_csv(_lowerCamelCase , iterator=_lowerCamelCase , dtype=_lowerCamelCase , **self.config.pd_read_csv_kwargs ) try: for batch_idx, df in enumerate(_lowerCamelCase ): UpperCamelCase_: Union[str, Any] = pa.Table.from_pandas(_lowerCamelCase ) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(_lowerCamelCase ) except ValueError as e: logger.error(f'''Failed to read file \'{file}\' with error {type(_lowerCamelCase )}: {e}''' ) raise
57
0
import os # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_doctest_list.py a__ = '''.''' if __name__ == "__main__": a__ = os.path.join(REPO_PATH, '''utils/documentation_tests.txt''') a__ = [] a__ = [] with open(doctest_file_path) as fp: for line in fp: a__ = line.strip() a__ = os.path.join(REPO_PATH, line) if not (os.path.isfile(path) or os.path.isdir(path)): non_existent_paths.append(line) all_paths.append(path) if len(non_existent_paths) > 0: a__ = '''\n'''.join(non_existent_paths) raise ValueError(f'''`utils/documentation_tests.txt` contains non-existent paths:\n{non_existent_paths}''') if all_paths != sorted(all_paths): raise ValueError('''Files in `utils/documentation_tests.txt` are not in alphabetical order.''')
14
from ...configuration_utils import PretrainedConfig from ...utils import logging A_ : str = logging.get_logger(__name__) A_ : Union[str, Any] = { 's-JoL/Open-Llama-V1': 'https://huggingface.co/s-JoL/Open-Llama-V1/blob/main/config.json', } class _lowerCAmelCase( UpperCAmelCase_ ): """simple docstring""" a : Tuple ='''open-llama''' def __init__( self , _lowerCamelCase=1_0_0_0_0_0 , _lowerCamelCase=4_0_9_6 , _lowerCamelCase=1_1_0_0_8 , _lowerCamelCase=3_2 , _lowerCamelCase=3_2 , _lowerCamelCase="silu" , _lowerCamelCase=2_0_4_8 , _lowerCamelCase=0.0_2 , _lowerCamelCase=1e-6 , _lowerCamelCase=True , _lowerCamelCase=0 , _lowerCamelCase=1 , _lowerCamelCase=2 , _lowerCamelCase=False , _lowerCamelCase=True , _lowerCamelCase=0.1 , _lowerCamelCase=0.1 , _lowerCamelCase=True , _lowerCamelCase=True , _lowerCamelCase=None , **_lowerCamelCase , ): UpperCamelCase_: int = vocab_size UpperCamelCase_: List[Any] = max_position_embeddings UpperCamelCase_: Dict = hidden_size UpperCamelCase_: Dict = intermediate_size UpperCamelCase_: Union[str, Any] = num_hidden_layers UpperCamelCase_: Dict = num_attention_heads UpperCamelCase_: Union[str, Any] = hidden_act UpperCamelCase_: Union[str, Any] = initializer_range UpperCamelCase_: List[Any] = rms_norm_eps UpperCamelCase_: Union[str, Any] = use_cache UpperCamelCase_: Dict = kwargs.pop( 'use_memorry_efficient_attention' , _lowerCamelCase ) UpperCamelCase_: Union[str, Any] = hidden_dropout_prob UpperCamelCase_: Any = attention_dropout_prob UpperCamelCase_: int = use_stable_embedding UpperCamelCase_: Tuple = shared_input_output_embedding UpperCamelCase_: str = rope_scaling self._rope_scaling_validation() super().__init__( pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , tie_word_embeddings=_lowerCamelCase , **_lowerCamelCase , ) def _a ( self ): if self.rope_scaling is None: return if not isinstance(self.rope_scaling , _lowerCamelCase ) or len(self.rope_scaling ) != 2: raise ValueError( '`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, ' f'''got {self.rope_scaling}''' ) UpperCamelCase_: str = self.rope_scaling.get('type' , _lowerCamelCase ) UpperCamelCase_: int = self.rope_scaling.get('factor' , _lowerCamelCase ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( f'''`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}''' ) if rope_scaling_factor is None or not isinstance(_lowerCamelCase , _lowerCamelCase ) or rope_scaling_factor <= 1.0: raise ValueError(f'''`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}''' )
57
0
from ...configuration_utils import PretrainedConfig from ...utils import logging A : Any = logging.get_logger(__name__) A : List[str] = { 'microsoft/cvt-13': 'https://huggingface.co/microsoft/cvt-13/resolve/main/config.json', # See all Cvt models at https://huggingface.co/models?filter=cvt } class A ( UpperCAmelCase__ ): '''simple docstring''' A__ = '''cvt''' def __init__(self : str , _UpperCAmelCase : str=3 , _UpperCAmelCase : str=[7, 3, 3] , _UpperCAmelCase : Any=[4, 2, 2] , _UpperCAmelCase : Any=[2, 1, 1] , _UpperCAmelCase : Any=[64, 192, 384] , _UpperCAmelCase : Optional[Any]=[1, 3, 6] , _UpperCAmelCase : Tuple=[1, 2, 10] , _UpperCAmelCase : List[str]=[4.0, 4.0, 4.0] , _UpperCAmelCase : Any=[0.0, 0.0, 0.0] , _UpperCAmelCase : Any=[0.0, 0.0, 0.0] , _UpperCAmelCase : Optional[Any]=[0.0, 0.0, 0.1] , _UpperCAmelCase : List[str]=[True, True, True] , _UpperCAmelCase : str=[False, False, True] , _UpperCAmelCase : Union[str, Any]=["dw_bn", "dw_bn", "dw_bn"] , _UpperCAmelCase : List[Any]=[3, 3, 3] , _UpperCAmelCase : List[str]=[1, 1, 1] , _UpperCAmelCase : List[Any]=[2, 2, 2] , _UpperCAmelCase : Dict=[1, 1, 1] , _UpperCAmelCase : List[Any]=[1, 1, 1] , _UpperCAmelCase : int=0.02 , _UpperCAmelCase : str=1E-1_2 , **_UpperCAmelCase : Optional[Any] , ) -> Tuple: """simple docstring""" super().__init__(**_UpperCAmelCase ) lowercase__ = num_channels lowercase__ = patch_sizes lowercase__ = patch_stride lowercase__ = patch_padding lowercase__ = embed_dim lowercase__ = num_heads lowercase__ = depth lowercase__ = mlp_ratio lowercase__ = attention_drop_rate lowercase__ = drop_rate lowercase__ = drop_path_rate lowercase__ = qkv_bias lowercase__ = cls_token lowercase__ = qkv_projection_method lowercase__ = kernel_qkv lowercase__ = padding_kv lowercase__ = stride_kv lowercase__ = padding_q lowercase__ = stride_q lowercase__ = initializer_range lowercase__ = layer_norm_eps
15
import collections import inspect import unittest from transformers import FocalNetConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( FocalNetBackbone, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetModel, ) from transformers.models.focalnet.modeling_focalnet import FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class _lowerCAmelCase: """simple docstring""" def __init__( self , _lowerCamelCase , _lowerCamelCase=1_3 , _lowerCamelCase=3_2 , _lowerCamelCase=2 , _lowerCamelCase=3 , _lowerCamelCase=1_6 , _lowerCamelCase=[3_2, 6_4, 1_2_8] , _lowerCamelCase=[1, 2, 1] , _lowerCamelCase=[2, 2, 4] , _lowerCamelCase=2 , _lowerCamelCase=2.0 , _lowerCamelCase=True , _lowerCamelCase=0.0 , _lowerCamelCase=0.0 , _lowerCamelCase=0.1 , _lowerCamelCase="gelu" , _lowerCamelCase=False , _lowerCamelCase=True , _lowerCamelCase=0.0_2 , _lowerCamelCase=1e-5 , _lowerCamelCase=True , _lowerCamelCase=None , _lowerCamelCase=True , _lowerCamelCase=1_0 , _lowerCamelCase=8 , _lowerCamelCase=["stage1", "stage2"] , _lowerCamelCase=[1, 2] , ): UpperCamelCase_: Tuple = parent UpperCamelCase_: Dict = batch_size UpperCamelCase_: List[str] = image_size UpperCamelCase_: Tuple = patch_size UpperCamelCase_: Tuple = num_channels UpperCamelCase_: Dict = embed_dim UpperCamelCase_: List[Any] = hidden_sizes UpperCamelCase_: List[str] = depths UpperCamelCase_: List[str] = num_heads UpperCamelCase_: Optional[int] = window_size UpperCamelCase_: Tuple = mlp_ratio UpperCamelCase_: Dict = qkv_bias UpperCamelCase_: str = hidden_dropout_prob UpperCamelCase_: Optional[Any] = attention_probs_dropout_prob UpperCamelCase_: int = drop_path_rate UpperCamelCase_: Dict = hidden_act UpperCamelCase_: List[str] = use_absolute_embeddings UpperCamelCase_: Dict = patch_norm UpperCamelCase_: Optional[Any] = layer_norm_eps UpperCamelCase_: List[str] = initializer_range UpperCamelCase_: List[Any] = is_training UpperCamelCase_: Optional[int] = scope UpperCamelCase_: str = use_labels UpperCamelCase_: List[str] = type_sequence_label_size UpperCamelCase_: Union[str, Any] = encoder_stride UpperCamelCase_: Dict = out_features UpperCamelCase_: str = out_indices def _a ( self ): UpperCamelCase_: int = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase_: List[Any] = None if self.use_labels: UpperCamelCase_: Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase_: Optional[Any] = self.get_config() return config, pixel_values, labels def _a ( self ): return FocalNetConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , hidden_sizes=self.hidden_sizes , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , out_features=self.out_features , out_indices=self.out_indices , ) def _a ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: Optional[int] = FocalNetModel(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() UpperCamelCase_: int = model(_lowerCamelCase ) UpperCamelCase_: int = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) UpperCamelCase_: int = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) ) def _a ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: List[str] = FocalNetBackbone(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() UpperCamelCase_: Optional[int] = model(_lowerCamelCase ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.image_size, 8, 8] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[:-1] ) # verify backbone works with out_features=None UpperCamelCase_: int = None UpperCamelCase_: List[Any] = FocalNetBackbone(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() UpperCamelCase_: Any = model(_lowerCamelCase ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.image_size * 2, 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def _a ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: Tuple = FocalNetForMaskedImageModeling(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() UpperCamelCase_: Any = model(_lowerCamelCase ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images UpperCamelCase_: List[Any] = 1 UpperCamelCase_: Dict = FocalNetForMaskedImageModeling(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() UpperCamelCase_: Optional[int] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) UpperCamelCase_: Union[str, Any] = model(_lowerCamelCase ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def _a ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: Tuple = self.type_sequence_label_size UpperCamelCase_: List[Any] = FocalNetForImageClassification(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() UpperCamelCase_: str = model(_lowerCamelCase , labels=_lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images UpperCamelCase_: Union[str, Any] = 1 UpperCamelCase_: Dict = FocalNetForImageClassification(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() UpperCamelCase_: Dict = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) UpperCamelCase_: Union[str, Any] = model(_lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def _a ( self ): UpperCamelCase_: Dict = self.prepare_config_and_inputs() UpperCamelCase_ ,UpperCamelCase_ ,UpperCamelCase_: List[str] = config_and_inputs UpperCamelCase_: int = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class _lowerCAmelCase( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase ): """simple docstring""" a : Optional[int] =( ( FocalNetModel, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetBackbone, ) if is_torch_available() else () ) a : Any =( {'''feature-extraction''': FocalNetModel, '''image-classification''': FocalNetForImageClassification} if is_torch_available() else {} ) a : Dict =False a : Union[str, Any] =False a : Tuple =False a : Optional[int] =False a : Union[str, Any] =False def _a ( self ): UpperCamelCase_: str = FocalNetModelTester(self ) UpperCamelCase_: Tuple = ConfigTester(self , config_class=_lowerCamelCase , embed_dim=3_7 , has_text_modality=_lowerCamelCase ) def _a ( self ): self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _a ( self ): return def _a ( self ): UpperCamelCase_: Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowerCamelCase ) def _a ( self ): UpperCamelCase_: List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*_lowerCamelCase ) def _a ( self ): UpperCamelCase_: Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*_lowerCamelCase ) def _a ( self ): UpperCamelCase_: Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_lowerCamelCase ) @unittest.skip(reason='FocalNet does not use inputs_embeds' ) def _a ( self ): pass @unittest.skip(reason='FocalNet does not use feedforward chunking' ) def _a ( self ): pass def _a ( self ): UpperCamelCase_ ,UpperCamelCase_: List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes[:-1]: UpperCamelCase_: Union[str, Any] = model_class(_lowerCamelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) UpperCamelCase_: List[str] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_lowerCamelCase , nn.Linear ) ) def _a ( self ): UpperCamelCase_ ,UpperCamelCase_: Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes[:-1]: UpperCamelCase_: List[Any] = model_class(_lowerCamelCase ) UpperCamelCase_: Optional[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase_: Any = [*signature.parameters.keys()] UpperCamelCase_: List[Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] , _lowerCamelCase ) def _a ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: Tuple = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() with torch.no_grad(): UpperCamelCase_: Tuple = model(**self._prepare_for_class(_lowerCamelCase , _lowerCamelCase ) ) UpperCamelCase_: Union[str, Any] = outputs.hidden_states UpperCamelCase_: Tuple = getattr( self.model_tester , 'expected_num_hidden_layers' , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(_lowerCamelCase ) , _lowerCamelCase ) # FocalNet has a different seq_length UpperCamelCase_: Optional[Any] = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) UpperCamelCase_: int = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) UpperCamelCase_: Dict = outputs.reshaped_hidden_states self.assertEqual(len(_lowerCamelCase ) , _lowerCamelCase ) UpperCamelCase_ ,UpperCamelCase_ ,UpperCamelCase_ ,UpperCamelCase_: int = reshaped_hidden_states[0].shape UpperCamelCase_: List[str] = ( reshaped_hidden_states[0].view(_lowerCamelCase , _lowerCamelCase , height * width ).permute(0 , 2 , 1 ) ) self.assertListEqual( list(reshaped_hidden_states.shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def _a ( self ): UpperCamelCase_ ,UpperCamelCase_: Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase_: int = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes[:-1]: UpperCamelCase_: int = True self.check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCamelCase_: Optional[Any] = True self.check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def _a ( self ): UpperCamelCase_ ,UpperCamelCase_: Dict = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase_: str = 3 UpperCamelCase_: Any = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) UpperCamelCase_: int = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) UpperCamelCase_: List[Any] = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) UpperCamelCase_: str = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes[:-1]: UpperCamelCase_: Dict = True self.check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCamelCase_: Optional[Any] = True self.check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , (padded_height, padded_width) ) @slow def _a ( self ): for model_name in FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase_: List[Any] = FocalNetModel.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) def _a ( self ): UpperCamelCase_ ,UpperCamelCase_: Dict = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase_: Dict = _config_zero_init(_lowerCamelCase ) for model_class in self.all_model_classes: UpperCamelCase_: List[str] = model_class(config=_lowerCamelCase ) for name, param in model.named_parameters(): if "embeddings" not in name and param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=f'''Parameter {name} of model {model_class} seems not properly initialized''' , ) @require_vision @require_torch class _lowerCAmelCase( unittest.TestCase ): """simple docstring""" @cached_property def _a ( self ): # TODO update organization return AutoImageProcessor.from_pretrained('microsoft/focalnet-tiny' ) if is_vision_available() else None @slow def _a ( self ): UpperCamelCase_: Optional[int] = FocalNetForImageClassification.from_pretrained('microsoft/focalnet-tiny' ).to(_lowerCamelCase ) UpperCamelCase_: Optional[Any] = self.default_image_processor UpperCamelCase_: str = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) UpperCamelCase_: str = image_processor(images=_lowerCamelCase , return_tensors='pt' ).to(_lowerCamelCase ) # forward pass with torch.no_grad(): UpperCamelCase_: List[str] = model(**_lowerCamelCase ) # verify the logits UpperCamelCase_: Optional[int] = torch.Size((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , _lowerCamelCase ) UpperCamelCase_: Optional[int] = torch.tensor([0.2_1_6_6, -0.4_3_6_8, 0.2_1_9_1] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _lowerCamelCase , atol=1e-4 ) ) self.assertTrue(outputs.logits.argmax(dim=-1 ).item() , 2_8_1 ) @require_torch class _lowerCAmelCase( UpperCAmelCase_ , unittest.TestCase ): """simple docstring""" a : Optional[Any] =(FocalNetBackbone,) if is_torch_available() else () a : List[str] =FocalNetConfig a : List[str] =False def _a ( self ): UpperCamelCase_: Any = FocalNetModelTester(self )
57
0
from __future__ import annotations from decimal import Decimal from numpy import array def __a ( A__ : list[list[float]] ): SCREAMING_SNAKE_CASE = Decimal # Check if the provided matrix has 2 rows and 2 columns # since this implementation only works for 2x2 matrices if len(A__ ) == 2 and len(matrix[0] ) == 2 and len(matrix[1] ) == 2: # Calculate the determinant of the matrix SCREAMING_SNAKE_CASE = float( d(matrix[0][0] ) * d(matrix[1][1] ) - d(matrix[1][0] ) * d(matrix[0][1] ) ) if determinant == 0: raise ValueError("This matrix has no inverse." ) # Creates a copy of the matrix with swapped positions of the elements SCREAMING_SNAKE_CASE = [[0.0, 0.0], [0.0, 0.0]] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = matrix[1][1], matrix[0][0] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = -matrix[1][0], -matrix[0][1] # Calculate the inverse of the matrix return [ [(float(d(A__ ) ) / determinant) or 0.0 for n in row] for row in swapped_matrix ] elif ( len(A__ ) == 3 and len(matrix[0] ) == 3 and len(matrix[1] ) == 3 and len(matrix[2] ) == 3 ): # Calculate the determinant of the matrix using Sarrus rule SCREAMING_SNAKE_CASE = float( ( (d(matrix[0][0] ) * d(matrix[1][1] ) * d(matrix[2][2] )) + (d(matrix[0][1] ) * d(matrix[1][2] ) * d(matrix[2][0] )) + (d(matrix[0][2] ) * d(matrix[1][0] ) * d(matrix[2][1] )) ) - ( (d(matrix[0][2] ) * d(matrix[1][1] ) * d(matrix[2][0] )) + (d(matrix[0][1] ) * d(matrix[1][0] ) * d(matrix[2][2] )) + (d(matrix[0][0] ) * d(matrix[1][2] ) * d(matrix[2][1] )) ) ) if determinant == 0: raise ValueError("This matrix has no inverse." ) # Creating cofactor matrix SCREAMING_SNAKE_CASE = [ [d(0.0 ), d(0.0 ), d(0.0 )], [d(0.0 ), d(0.0 ), d(0.0 )], [d(0.0 ), d(0.0 ), d(0.0 )], ] SCREAMING_SNAKE_CASE = (d(matrix[1][1] ) * d(matrix[2][2] )) - ( d(matrix[1][2] ) * d(matrix[2][1] ) ) SCREAMING_SNAKE_CASE = -( (d(matrix[1][0] ) * d(matrix[2][2] )) - (d(matrix[1][2] ) * d(matrix[2][0] )) ) SCREAMING_SNAKE_CASE = (d(matrix[1][0] ) * d(matrix[2][1] )) - ( d(matrix[1][1] ) * d(matrix[2][0] ) ) SCREAMING_SNAKE_CASE = -( (d(matrix[0][1] ) * d(matrix[2][2] )) - (d(matrix[0][2] ) * d(matrix[2][1] )) ) SCREAMING_SNAKE_CASE = (d(matrix[0][0] ) * d(matrix[2][2] )) - ( d(matrix[0][2] ) * d(matrix[2][0] ) ) SCREAMING_SNAKE_CASE = -( (d(matrix[0][0] ) * d(matrix[2][1] )) - (d(matrix[0][1] ) * d(matrix[2][0] )) ) SCREAMING_SNAKE_CASE = (d(matrix[0][1] ) * d(matrix[1][2] )) - ( d(matrix[0][2] ) * d(matrix[1][1] ) ) SCREAMING_SNAKE_CASE = -( (d(matrix[0][0] ) * d(matrix[1][2] )) - (d(matrix[0][2] ) * d(matrix[1][0] )) ) SCREAMING_SNAKE_CASE = (d(matrix[0][0] ) * d(matrix[1][1] )) - ( d(matrix[0][1] ) * d(matrix[1][0] ) ) # Transpose the cofactor matrix (Adjoint matrix) SCREAMING_SNAKE_CASE = array(A__ ) for i in range(3 ): for j in range(3 ): SCREAMING_SNAKE_CASE = cofactor_matrix[j][i] # Inverse of the matrix using the formula (1/determinant) * adjoint matrix SCREAMING_SNAKE_CASE = array(A__ ) for i in range(3 ): for j in range(3 ): inverse_matrix[i][j] /= d(A__ ) # Calculate the inverse of the matrix return [[float(d(A__ ) ) or 0.0 for n in row] for row in inverse_matrix] raise ValueError("Please provide a matrix of size 2x2 or 3x3." )
16
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) A_ : Tuple = { 'configuration_distilbert': [ 'DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'DistilBertConfig', 'DistilBertOnnxConfig', ], 'tokenization_distilbert': ['DistilBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : Optional[Any] = ['DistilBertTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : int = [ 'DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'DistilBertForMaskedLM', 'DistilBertForMultipleChoice', 'DistilBertForQuestionAnswering', 'DistilBertForSequenceClassification', 'DistilBertForTokenClassification', 'DistilBertModel', 'DistilBertPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : List[Any] = [ 'TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFDistilBertForMaskedLM', 'TFDistilBertForMultipleChoice', 'TFDistilBertForQuestionAnswering', 'TFDistilBertForSequenceClassification', 'TFDistilBertForTokenClassification', 'TFDistilBertMainLayer', 'TFDistilBertModel', 'TFDistilBertPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : int = [ 'FlaxDistilBertForMaskedLM', 'FlaxDistilBertForMultipleChoice', 'FlaxDistilBertForQuestionAnswering', 'FlaxDistilBertForSequenceClassification', 'FlaxDistilBertForTokenClassification', 'FlaxDistilBertModel', 'FlaxDistilBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_distilbert import ( DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DistilBertConfig, DistilBertOnnxConfig, ) from .tokenization_distilbert import DistilBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_distilbert_fast import DistilBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_distilbert import ( DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, DistilBertModel, DistilBertPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_distilbert import ( TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDistilBertForMaskedLM, TFDistilBertForMultipleChoice, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertMainLayer, TFDistilBertModel, TFDistilBertPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, FlaxDistilBertPreTrainedModel, ) else: import sys A_ : Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
57
0
import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin from .feature_extraction_wavaveca import WavaVecaFeatureExtractor from .tokenization_wavaveca import WavaVecaCTCTokenizer class lowerCamelCase_ ( _lowercase ): _lowercase : Union[str, Any] = '''Wav2Vec2FeatureExtractor''' _lowercase : Any = '''AutoTokenizer''' def __init__( self : List[str] , __A : List[Any] , __A : Optional[Any] ): super().__init__(__A , __A ) __A : Optional[Any] = self.feature_extractor __A : str = False @classmethod def lowerCAmelCase_ ( cls : Dict , __A : List[str] , **__A : Optional[Any] ): try: return super().from_pretrained(__A , **__A ) except OSError: warnings.warn( F"""Loading a tokenizer inside {cls.__name__} from a config that does not""" """ include a `tokenizer_class` attribute is deprecated and will be """ """removed in v5. Please add `'tokenizer_class': 'Wav2Vec2CTCTokenizer'`""" """ attribute to either your `config.json` or `tokenizer_config.json` """ """file to suppress this warning: """ , __A , ) __A : Any = WavaVecaFeatureExtractor.from_pretrained(__A , **__A ) __A : List[str] = WavaVecaCTCTokenizer.from_pretrained(__A , **__A ) return cls(feature_extractor=__A , tokenizer=__A ) def __call__( self : Optional[int] , *__A : Optional[Any] , **__A : List[str] ): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*__A , **__A ) if "raw_speech" in kwargs: warnings.warn("""Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.""" ) __A : Any = kwargs.pop("""raw_speech""" ) else: __A : List[str] = kwargs.pop("""audio""" , __A ) __A : int = kwargs.pop("""sampling_rate""" , __A ) __A : Tuple = kwargs.pop("""text""" , __A ) if len(__A ) > 0: __A : Union[str, Any] = args[0] __A : Optional[Any] = args[1:] if audio is None and text is None: raise ValueError("""You need to specify either an `audio` or `text` input to process.""" ) if audio is not None: __A : Tuple = self.feature_extractor(__A , *__A , sampling_rate=__A , **__A ) if text is not None: __A : Any = self.tokenizer(__A , **__A ) if text is None: return inputs elif audio is None: return encodings else: __A : List[str] = encodings["""input_ids"""] return inputs def lowerCAmelCase_ ( self : List[str] , *__A : int , **__A : Tuple ): # For backward compatibility if self._in_target_context_manager: return self.current_processor.pad(*__A , **__A ) __A : Any = kwargs.pop("""input_features""" , __A ) __A : Tuple = kwargs.pop("""labels""" , __A ) if len(__A ) > 0: __A : Any = args[0] __A : Union[str, Any] = args[1:] if input_features is not None: __A : str = self.feature_extractor.pad(__A , *__A , **__A ) if labels is not None: __A : Union[str, Any] = self.tokenizer.pad(__A , **__A ) if labels is None: return input_features elif input_features is None: return labels else: __A : Optional[Any] = labels["""input_ids"""] return input_features def lowerCAmelCase_ ( self : List[Any] , *__A : List[Any] , **__A : List[str] ): return self.tokenizer.batch_decode(*__A , **__A ) def lowerCAmelCase_ ( self : Optional[Any] , *__A : Dict , **__A : Optional[int] ): return self.tokenizer.decode(*__A , **__A ) @contextmanager def lowerCAmelCase_ ( self : str ): warnings.warn( """`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your """ """labels by using the argument `text` of the regular `__call__` method (either in the same call as """ """your audio inputs, or in a separate call.""" ) __A : Dict = True __A : List[str] = self.tokenizer yield __A : Tuple = self.feature_extractor __A : int = False
17
import os import socket from contextlib import contextmanager import torch from ..commands.config.default import write_basic_config # noqa: F401 from ..state import PartialState from .dataclasses import DistributedType from .imports import is_deepspeed_available, is_tpu_available from .transformer_engine import convert_model from .versions import is_torch_version if is_deepspeed_available(): from deepspeed import DeepSpeedEngine if is_tpu_available(check_device=False): import torch_xla.core.xla_model as xm def snake_case (UpperCAmelCase__ ) -> Union[str, Any]: if is_torch_version('<' , '2.0.0' ) or not hasattr(UpperCAmelCase__ , '_dynamo' ): return False return isinstance(UpperCAmelCase__ , torch._dynamo.eval_frame.OptimizedModule ) def snake_case (UpperCAmelCase__ , UpperCAmelCase__ = True ) -> Any: UpperCamelCase_: Optional[Any] = (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel) UpperCamelCase_: int = is_compiled_module(UpperCAmelCase__ ) if is_compiled: UpperCamelCase_: List[str] = model UpperCamelCase_: Dict = model._orig_mod if is_deepspeed_available(): options += (DeepSpeedEngine,) while isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): UpperCamelCase_: Dict = model.module if not keep_fpaa_wrapper: UpperCamelCase_: int = getattr(UpperCAmelCase__ , 'forward' ) UpperCamelCase_: List[str] = model.__dict__.pop('_original_forward' , UpperCAmelCase__ ) if original_forward is not None: while hasattr(UpperCAmelCase__ , '__wrapped__' ): UpperCamelCase_: Any = forward.__wrapped__ if forward == original_forward: break UpperCamelCase_: Optional[int] = forward if getattr(UpperCAmelCase__ , '_converted_to_transformer_engine' , UpperCAmelCase__ ): convert_model(UpperCAmelCase__ , to_transformer_engine=UpperCAmelCase__ ) if is_compiled: UpperCamelCase_: Union[str, Any] = model UpperCamelCase_: Tuple = compiled_model return model def snake_case () -> List[str]: PartialState().wait_for_everyone() def snake_case (UpperCAmelCase__ , UpperCAmelCase__ ) -> Dict: if PartialState().distributed_type == DistributedType.TPU: xm.save(UpperCAmelCase__ , UpperCAmelCase__ ) elif PartialState().local_process_index == 0: torch.save(UpperCAmelCase__ , UpperCAmelCase__ ) @contextmanager def snake_case (**UpperCAmelCase__ ) -> Any: for key, value in kwargs.items(): UpperCamelCase_: int = str(UpperCAmelCase__ ) yield for key in kwargs: if key.upper() in os.environ: del os.environ[key.upper()] def snake_case (UpperCAmelCase__ ) -> str: if not hasattr(UpperCAmelCase__ , '__qualname__' ) and not hasattr(UpperCAmelCase__ , '__name__' ): UpperCamelCase_: List[Any] = getattr(UpperCAmelCase__ , '__class__' , UpperCAmelCase__ ) if hasattr(UpperCAmelCase__ , '__qualname__' ): return obj.__qualname__ if hasattr(UpperCAmelCase__ , '__name__' ): return obj.__name__ return str(UpperCAmelCase__ ) def snake_case (UpperCAmelCase__ , UpperCAmelCase__ ) -> Any: for key, value in source.items(): if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): UpperCamelCase_: Any = destination.setdefault(UpperCAmelCase__ , {} ) merge_dicts(UpperCAmelCase__ , UpperCAmelCase__ ) else: UpperCamelCase_: str = value return destination def snake_case (UpperCAmelCase__ = None ) -> bool: if port is None: UpperCamelCase_: List[str] = 2_9_5_0_0 with socket.socket(socket.AF_INET , socket.SOCK_STREAM ) as s: return s.connect_ex(('localhost', port) ) == 0
57
0
'''simple docstring''' import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ConditionalDetrImageProcessor class lowerCAmelCase_ ( unittest.TestCase ): def __init__( self , _lowerCAmelCase , _lowerCAmelCase=7 , _lowerCAmelCase=3 , _lowerCAmelCase=30 , _lowerCAmelCase=400 , _lowerCAmelCase=True , _lowerCAmelCase=None , _lowerCAmelCase=True , _lowerCAmelCase=[0.5, 0.5, 0.5] , _lowerCAmelCase=[0.5, 0.5, 0.5] , _lowerCAmelCase=True , _lowerCAmelCase=1 / 255 , _lowerCAmelCase=True , ) -> int: # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p _lowerCAmelCase = size if size is not None else {"shortest_edge": 18, "longest_edge": 1333} _lowerCAmelCase = parent _lowerCAmelCase = batch_size _lowerCAmelCase = num_channels _lowerCAmelCase = min_resolution _lowerCAmelCase = max_resolution _lowerCAmelCase = do_resize _lowerCAmelCase = size _lowerCAmelCase = do_normalize _lowerCAmelCase = image_mean _lowerCAmelCase = image_std _lowerCAmelCase = do_rescale _lowerCAmelCase = rescale_factor _lowerCAmelCase = do_pad def _snake_case ( self ) -> Dict: return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def _snake_case ( self , _lowerCAmelCase , _lowerCAmelCase=False ) -> Union[str, Any]: if not batched: _lowerCAmelCase = image_inputs[0] if isinstance(_lowerCAmelCase , Image.Image ): _lowerCAmelCase , _lowerCAmelCase = image.size else: _lowerCAmelCase , _lowerCAmelCase = image.shape[1], image.shape[2] if w < h: _lowerCAmelCase = int(self.size["shortest_edge"] * h / w ) _lowerCAmelCase = self.size["shortest_edge"] elif w > h: _lowerCAmelCase = self.size["shortest_edge"] _lowerCAmelCase = int(self.size["shortest_edge"] * w / h ) else: _lowerCAmelCase = self.size["shortest_edge"] _lowerCAmelCase = self.size["shortest_edge"] else: _lowerCAmelCase = [] for image in image_inputs: _lowerCAmelCase , _lowerCAmelCase = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) _lowerCAmelCase = max(_lowerCAmelCase , key=lambda _lowerCAmelCase : item[0] )[0] _lowerCAmelCase = max(_lowerCAmelCase , key=lambda _lowerCAmelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class lowerCAmelCase_ ( __magic_name__ ,unittest.TestCase ): __lowerCamelCase : Union[str, Any] = ConditionalDetrImageProcessor if is_vision_available() else None def _snake_case ( self ) -> List[str]: _lowerCAmelCase = ConditionalDetrImageProcessingTester(self ) @property def _snake_case ( self ) -> str: return self.image_processor_tester.prepare_image_processor_dict() def _snake_case ( self ) -> Optional[Any]: _lowerCAmelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCAmelCase , "image_mean" ) ) self.assertTrue(hasattr(_lowerCAmelCase , "image_std" ) ) self.assertTrue(hasattr(_lowerCAmelCase , "do_normalize" ) ) self.assertTrue(hasattr(_lowerCAmelCase , "do_resize" ) ) self.assertTrue(hasattr(_lowerCAmelCase , "size" ) ) def _snake_case ( self ) -> Dict: _lowerCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"shortest_edge": 18, "longest_edge": 1333} ) self.assertEqual(image_processor.do_pad , _lowerCAmelCase ) _lowerCAmelCase = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=_lowerCAmelCase ) self.assertEqual(image_processor.size , {"shortest_edge": 42, "longest_edge": 84} ) self.assertEqual(image_processor.do_pad , _lowerCAmelCase ) def _snake_case ( self ) -> Tuple: pass def _snake_case ( self ) -> List[str]: # Initialize image_processing _lowerCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _lowerCAmelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCAmelCase ) for image in image_inputs: self.assertIsInstance(_lowerCAmelCase , Image.Image ) # Test not batched input _lowerCAmelCase = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values _lowerCAmelCase , _lowerCAmelCase = self.image_processor_tester.get_expected_values(_lowerCAmelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched _lowerCAmelCase , _lowerCAmelCase = self.image_processor_tester.get_expected_values(_lowerCAmelCase , batched=_lowerCAmelCase ) _lowerCAmelCase = image_processing(_lowerCAmelCase , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def _snake_case ( self ) -> Optional[Any]: # Initialize image_processing _lowerCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _lowerCAmelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCAmelCase , numpify=_lowerCAmelCase ) for image in image_inputs: self.assertIsInstance(_lowerCAmelCase , np.ndarray ) # Test not batched input _lowerCAmelCase = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values _lowerCAmelCase , _lowerCAmelCase = self.image_processor_tester.get_expected_values(_lowerCAmelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched _lowerCAmelCase = image_processing(_lowerCAmelCase , return_tensors="pt" ).pixel_values _lowerCAmelCase , _lowerCAmelCase = self.image_processor_tester.get_expected_values(_lowerCAmelCase , batched=_lowerCAmelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def _snake_case ( self ) -> Optional[Any]: # Initialize image_processing _lowerCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _lowerCAmelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCAmelCase , torchify=_lowerCAmelCase ) for image in image_inputs: self.assertIsInstance(_lowerCAmelCase , torch.Tensor ) # Test not batched input _lowerCAmelCase = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values _lowerCAmelCase , _lowerCAmelCase = self.image_processor_tester.get_expected_values(_lowerCAmelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched _lowerCAmelCase = image_processing(_lowerCAmelCase , return_tensors="pt" ).pixel_values _lowerCAmelCase , _lowerCAmelCase = self.image_processor_tester.get_expected_values(_lowerCAmelCase , batched=_lowerCAmelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def _snake_case ( self ) -> str: # prepare image and target _lowerCAmelCase = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_annotations.txt" , "r" ) as f: _lowerCAmelCase = json.loads(f.read() ) _lowerCAmelCase = {"image_id": 39769, "annotations": target} # encode them _lowerCAmelCase = ConditionalDetrImageProcessor.from_pretrained("microsoft/conditional-detr-resnet-50" ) _lowerCAmelCase = image_processing(images=_lowerCAmelCase , annotations=_lowerCAmelCase , return_tensors="pt" ) # verify pixel values _lowerCAmelCase = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding["pixel_values"].shape , _lowerCAmelCase ) _lowerCAmelCase = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , _lowerCAmelCase , atol=1E-4 ) ) # verify area _lowerCAmelCase = torch.tensor([5887.9600, 11250.2061, 489353.8438, 837122.7500, 147967.5156, 165732.3438] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , _lowerCAmelCase ) ) # verify boxes _lowerCAmelCase = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , _lowerCAmelCase ) _lowerCAmelCase = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , _lowerCAmelCase , atol=1E-3 ) ) # verify image_id _lowerCAmelCase = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , _lowerCAmelCase ) ) # verify is_crowd _lowerCAmelCase = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , _lowerCAmelCase ) ) # verify class_labels _lowerCAmelCase = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , _lowerCAmelCase ) ) # verify orig_size _lowerCAmelCase = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , _lowerCAmelCase ) ) # verify size _lowerCAmelCase = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , _lowerCAmelCase ) ) @slow def _snake_case ( self ) -> List[Any]: # prepare image, target and masks_path _lowerCAmelCase = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt" , "r" ) as f: _lowerCAmelCase = json.loads(f.read() ) _lowerCAmelCase = {"file_name": "000000039769.png", "image_id": 39769, "segments_info": target} _lowerCAmelCase = pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic" ) # encode them _lowerCAmelCase = ConditionalDetrImageProcessor(format="coco_panoptic" ) _lowerCAmelCase = image_processing(images=_lowerCAmelCase , annotations=_lowerCAmelCase , masks_path=_lowerCAmelCase , return_tensors="pt" ) # verify pixel values _lowerCAmelCase = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding["pixel_values"].shape , _lowerCAmelCase ) _lowerCAmelCase = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , _lowerCAmelCase , atol=1E-4 ) ) # verify area _lowerCAmelCase = torch.tensor([147979.6875, 165527.0469, 484638.5938, 11292.9375, 5879.6562, 7634.1147] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , _lowerCAmelCase ) ) # verify boxes _lowerCAmelCase = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , _lowerCAmelCase ) _lowerCAmelCase = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , _lowerCAmelCase , atol=1E-3 ) ) # verify image_id _lowerCAmelCase = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , _lowerCAmelCase ) ) # verify is_crowd _lowerCAmelCase = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , _lowerCAmelCase ) ) # verify class_labels _lowerCAmelCase = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , _lowerCAmelCase ) ) # verify masks _lowerCAmelCase = 822873 self.assertEqual(encoding["labels"][0]["masks"].sum().item() , _lowerCAmelCase ) # verify orig_size _lowerCAmelCase = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , _lowerCAmelCase ) ) # verify size _lowerCAmelCase = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , _lowerCAmelCase ) )
18
import argparse import os import pickle import sys import torch from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() # We do this to be able to load python 2 datasets pickles # See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918 A_ : Optional[Any] = data_utils.TransfoXLTokenizer A_ : Union[str, Any] = data_utils.TransfoXLCorpus A_ : Any = data_utils A_ : Optional[Any] = data_utils def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) -> List[str]: if transfo_xl_dataset_file: # Convert a pre-processed corpus (see original TensorFlow repo) with open(UpperCAmelCase__ , 'rb' ) as fp: UpperCamelCase_: Union[str, Any] = pickle.load(UpperCAmelCase__ , encoding='latin1' ) # Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term) UpperCamelCase_: Any = pytorch_dump_folder_path + '/' + VOCAB_FILES_NAMES['pretrained_vocab_file'] print(F'''Save vocabulary to {pytorch_vocab_dump_path}''' ) UpperCamelCase_: Union[str, Any] = corpus.vocab.__dict__ torch.save(UpperCAmelCase__ , UpperCAmelCase__ ) UpperCamelCase_: str = corpus.__dict__ corpus_dict_no_vocab.pop('vocab' , UpperCAmelCase__ ) UpperCamelCase_: str = pytorch_dump_folder_path + '/' + CORPUS_NAME print(F'''Save dataset to {pytorch_dataset_dump_path}''' ) torch.save(UpperCAmelCase__ , UpperCAmelCase__ ) if tf_checkpoint_path: # Convert a pre-trained TensorFlow model UpperCamelCase_: Any = os.path.abspath(UpperCAmelCase__ ) UpperCamelCase_: Dict = os.path.abspath(UpperCAmelCase__ ) print(F'''Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.''' ) # Initialise PyTorch model if transfo_xl_config_file == "": UpperCamelCase_: List[str] = TransfoXLConfig() else: UpperCamelCase_: Optional[int] = TransfoXLConfig.from_json_file(UpperCAmelCase__ ) print(F'''Building PyTorch model from configuration: {config}''' ) UpperCamelCase_: Union[str, Any] = TransfoXLLMHeadModel(UpperCAmelCase__ ) UpperCamelCase_: Tuple = load_tf_weights_in_transfo_xl(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) # Save pytorch-model UpperCamelCase_: str = os.path.join(UpperCAmelCase__ , UpperCAmelCase__ ) UpperCamelCase_: Union[str, Any] = os.path.join(UpperCAmelCase__ , UpperCAmelCase__ ) print(F'''Save PyTorch model to {os.path.abspath(UpperCAmelCase__ )}''' ) torch.save(model.state_dict() , UpperCAmelCase__ ) print(F'''Save configuration file to {os.path.abspath(UpperCAmelCase__ )}''' ) with open(UpperCAmelCase__ , 'w' , encoding='utf-8' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": A_ : int = argparse.ArgumentParser() parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the folder to store the PyTorch model or dataset/vocab.', ) parser.add_argument( '--tf_checkpoint_path', default='', type=str, help='An optional path to a TensorFlow checkpoint path to be converted.', ) parser.add_argument( '--transfo_xl_config_file', default='', type=str, help=( 'An optional config json file corresponding to the pre-trained BERT model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--transfo_xl_dataset_file', default='', type=str, help='An optional dataset file to be converted in a vocabulary.', ) A_ : Tuple = parser.parse_args() convert_transfo_xl_checkpoint_to_pytorch( args.tf_checkpoint_path, args.transfo_xl_config_file, args.pytorch_dump_folder_path, args.transfo_xl_dataset_file, )
57
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 _UpperCAmelCase( lowerCamelCase , lowerCamelCase , unittest.TestCase ): lowercase__ = ( ( TFMobileBertModel, TFMobileBertForMaskedLM, TFMobileBertForNextSentencePrediction, TFMobileBertForPreTraining, TFMobileBertForQuestionAnswering, TFMobileBertForSequenceClassification, TFMobileBertForTokenClassification, TFMobileBertForMultipleChoice, ) if is_tf_available() else () ) lowercase__ = ( { 'feature-extraction': TFMobileBertModel, 'fill-mask': TFMobileBertForMaskedLM, 'question-answering': TFMobileBertForQuestionAnswering, 'text-classification': TFMobileBertForSequenceClassification, 'token-classification': TFMobileBertForTokenClassification, 'zero-shot': TFMobileBertForSequenceClassification, } if is_tf_available() else {} ) lowercase__ = False lowercase__ = False def UpperCAmelCase ( self , __a , __a , __a=False) -> Optional[Any]: '''simple docstring''' _UpperCamelCase = super()._prepare_for_class(__a , __a , return_labels=__a) if return_labels: if model_class in get_values(__a): _UpperCamelCase = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa) return inputs_dict class _UpperCAmelCase( lowerCamelCase ): def __init__( self , __a , __a=13 , __a=7 , __a=True , __a=True , __a=True , __a=True , __a=99 , __a=32 , __a=32 , __a=2 , __a=4 , __a=37 , __a="gelu" , __a=0.1 , __a=0.1 , __a=5_12 , __a=16 , __a=2 , __a=0.02 , __a=3 , __a=4 , __a=None , ) -> List[str]: '''simple docstring''' _UpperCamelCase = parent _UpperCamelCase = batch_size _UpperCamelCase = seq_length _UpperCamelCase = is_training _UpperCamelCase = use_input_mask _UpperCamelCase = use_token_type_ids _UpperCamelCase = use_labels _UpperCamelCase = vocab_size _UpperCamelCase = hidden_size _UpperCamelCase = num_hidden_layers _UpperCamelCase = num_attention_heads _UpperCamelCase = intermediate_size _UpperCamelCase = hidden_act _UpperCamelCase = hidden_dropout_prob _UpperCamelCase = attention_probs_dropout_prob _UpperCamelCase = max_position_embeddings _UpperCamelCase = type_vocab_size _UpperCamelCase = type_sequence_label_size _UpperCamelCase = initializer_range _UpperCamelCase = num_labels _UpperCamelCase = num_choices _UpperCamelCase = scope _UpperCamelCase = embedding_size def UpperCAmelCase ( self) -> List[str]: '''simple docstring''' _UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) _UpperCamelCase = None if self.use_input_mask: _UpperCamelCase = random_attention_mask([self.batch_size, self.seq_length]) _UpperCamelCase = None if self.use_token_type_ids: _UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size) _UpperCamelCase = None _UpperCamelCase = None _UpperCamelCase = None if self.use_labels: _UpperCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size) _UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels) _UpperCamelCase = ids_tensor([self.batch_size] , self.num_choices) _UpperCamelCase = 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 , __a , __a , __a , __a , __a , __a , __a) -> Any: '''simple docstring''' _UpperCamelCase = TFMobileBertModel(config=__a) _UpperCamelCase = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} _UpperCamelCase = model(__a) _UpperCamelCase = [input_ids, input_mask] _UpperCamelCase = model(__a) _UpperCamelCase = 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 , __a , __a , __a , __a , __a , __a , __a) -> Any: '''simple docstring''' _UpperCamelCase = TFMobileBertForMaskedLM(config=__a) _UpperCamelCase = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} _UpperCamelCase = model(__a) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> Dict: '''simple docstring''' _UpperCamelCase = TFMobileBertForNextSentencePrediction(config=__a) _UpperCamelCase = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} _UpperCamelCase = model(__a) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2)) def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> Tuple: '''simple docstring''' _UpperCamelCase = TFMobileBertForPreTraining(config=__a) _UpperCamelCase = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} _UpperCamelCase = 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 , __a , __a , __a , __a , __a , __a , __a) -> Union[str, Any]: '''simple docstring''' _UpperCamelCase = self.num_labels _UpperCamelCase = TFMobileBertForSequenceClassification(config=__a) _UpperCamelCase = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} _UpperCamelCase = model(__a) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> Dict: '''simple docstring''' _UpperCamelCase = self.num_choices _UpperCamelCase = TFMobileBertForMultipleChoice(config=__a) _UpperCamelCase = tf.tile(tf.expand_dims(__a , 1) , (1, self.num_choices, 1)) _UpperCamelCase = tf.tile(tf.expand_dims(__a , 1) , (1, self.num_choices, 1)) _UpperCamelCase = tf.tile(tf.expand_dims(__a , 1) , (1, self.num_choices, 1)) _UpperCamelCase = { '''input_ids''': multiple_choice_inputs_ids, '''attention_mask''': multiple_choice_input_mask, '''token_type_ids''': multiple_choice_token_type_ids, } _UpperCamelCase = model(__a) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices)) def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> Dict: '''simple docstring''' _UpperCamelCase = self.num_labels _UpperCamelCase = TFMobileBertForTokenClassification(config=__a) _UpperCamelCase = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} _UpperCamelCase = model(__a) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels)) def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> Any: '''simple docstring''' _UpperCamelCase = TFMobileBertForQuestionAnswering(config=__a) _UpperCamelCase = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} _UpperCamelCase = 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: '''simple docstring''' _UpperCamelCase = self.prepare_config_and_inputs() ( ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ( _UpperCamelCase ) , ) = config_and_inputs _UpperCamelCase = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict def UpperCAmelCase ( self) -> Union[str, Any]: '''simple docstring''' _UpperCamelCase = TFMobileBertModelTest.TFMobileBertModelTester(self) _UpperCamelCase = ConfigTester(self , config_class=__a , hidden_size=37) def UpperCAmelCase ( self) -> Union[str, Any]: '''simple docstring''' self.config_tester.run_common_tests() def UpperCAmelCase ( self) -> Union[str, Any]: '''simple docstring''' _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_model(*__a) def UpperCAmelCase ( self) -> Union[str, Any]: '''simple docstring''' _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_masked_lm(*__a) def UpperCAmelCase ( self) -> List[str]: '''simple docstring''' _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_multiple_choice(*__a) def UpperCAmelCase ( self) -> Any: '''simple docstring''' _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*__a) def UpperCAmelCase ( self) -> Any: '''simple docstring''' _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_pretraining(*__a) def UpperCAmelCase ( self) -> List[str]: '''simple docstring''' _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_question_answering(*__a) def UpperCAmelCase ( self) -> str: '''simple docstring''' _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_sequence_classification(*__a) def UpperCAmelCase ( self) -> List[Any]: '''simple docstring''' _UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_token_classification(*__a) @slow def UpperCAmelCase ( self) -> List[str]: '''simple docstring''' # for model_name in TF_MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["google/mobilebert-uncased"]: _UpperCamelCase = TFMobileBertModel.from_pretrained(__a) self.assertIsNotNone(__a) @require_tf class _UpperCAmelCase( unittest.TestCase ): @slow def UpperCAmelCase ( self) -> int: '''simple docstring''' _UpperCamelCase = TFMobileBertForPreTraining.from_pretrained('''google/mobilebert-uncased''') _UpperCamelCase = tf.constant([[0, 1, 2, 3, 4, 5]]) _UpperCamelCase = model(__a)[0] _UpperCamelCase = [1, 6, 3_05_22] self.assertEqual(output.shape , __a) _UpperCamelCase = tf.constant( [ [ [-4.591_9547, -9.24_8295, -9.64_5256], [-6.730_6175, -6.44_0284, -6.605_2837], [-7.274_3506, -6.784_7915, -6.02_4673], ] ]) tf.debugging.assert_near(output[:, :3, :3] , __a , atol=1e-4)
19
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL A_ : List[str] = logging.get_logger(__name__) def snake_case (UpperCAmelCase__ , UpperCAmelCase__ ) -> Union[str, Any]: UpperCamelCase_: Tuple = b.T UpperCamelCase_: Tuple = np.sum(np.square(UpperCAmelCase__ ) , axis=1 ) UpperCamelCase_: Optional[Any] = np.sum(np.square(UpperCAmelCase__ ) , axis=0 ) UpperCamelCase_: Optional[int] = np.matmul(UpperCAmelCase__ , UpperCAmelCase__ ) UpperCamelCase_: List[Any] = aa[:, None] - 2 * ab + ba[None, :] return d def snake_case (UpperCAmelCase__ , UpperCAmelCase__ ) -> Optional[Any]: UpperCamelCase_: List[str] = x.reshape(-1 , 3 ) UpperCamelCase_: Union[str, Any] = squared_euclidean_distance(UpperCAmelCase__ , UpperCAmelCase__ ) return np.argmin(UpperCAmelCase__ , axis=1 ) class _lowerCAmelCase( UpperCAmelCase_ ): """simple docstring""" a : Any =['''pixel_values'''] def __init__( self , _lowerCamelCase = None , _lowerCamelCase = True , _lowerCamelCase = None , _lowerCamelCase = PILImageResampling.BILINEAR , _lowerCamelCase = True , _lowerCamelCase = True , **_lowerCamelCase , ): super().__init__(**_lowerCamelCase ) UpperCamelCase_: List[str] = size if size is not None else {'height': 2_5_6, 'width': 2_5_6} UpperCamelCase_: str = get_size_dict(_lowerCamelCase ) UpperCamelCase_: Any = np.array(_lowerCamelCase ) if clusters is not None else None UpperCamelCase_: Optional[int] = do_resize UpperCamelCase_: List[Any] = size UpperCamelCase_: Optional[int] = resample UpperCamelCase_: str = do_normalize UpperCamelCase_: str = do_color_quantize def _a ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = PILImageResampling.BILINEAR , _lowerCamelCase = None , **_lowerCamelCase , ): UpperCamelCase_: Any = get_size_dict(_lowerCamelCase ) if "height" not in size or "width" not in size: raise ValueError(f'''Size dictionary must contain both height and width keys. Got {size.keys()}''' ) return resize( _lowerCamelCase , size=(size['height'], size['width']) , resample=_lowerCamelCase , data_format=_lowerCamelCase , **_lowerCamelCase ) def _a ( self , _lowerCamelCase , _lowerCamelCase = None , ): UpperCamelCase_: Optional[Any] = rescale(image=_lowerCamelCase , scale=1 / 1_2_7.5 , data_format=_lowerCamelCase ) UpperCamelCase_: Optional[Any] = image - 1 return image def _a ( self , _lowerCamelCase , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = ChannelDimension.FIRST , **_lowerCamelCase , ): UpperCamelCase_: Optional[Any] = do_resize if do_resize is not None else self.do_resize UpperCamelCase_: Tuple = size if size is not None else self.size UpperCamelCase_: Union[str, Any] = get_size_dict(_lowerCamelCase ) UpperCamelCase_: Union[str, Any] = resample if resample is not None else self.resample UpperCamelCase_: Any = do_normalize if do_normalize is not None else self.do_normalize UpperCamelCase_: str = do_color_quantize if do_color_quantize is not None else self.do_color_quantize UpperCamelCase_: Dict = clusters if clusters is not None else self.clusters UpperCamelCase_: Dict = np.array(_lowerCamelCase ) UpperCamelCase_: Optional[int] = make_list_of_images(_lowerCamelCase ) if not valid_images(_lowerCamelCase ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None or resample is None: raise ValueError('Size and resample must be specified if do_resize is True.' ) if do_color_quantize and clusters is None: raise ValueError('Clusters must be specified if do_color_quantize is True.' ) # All transformations expect numpy arrays. UpperCamelCase_: Union[str, Any] = [to_numpy_array(_lowerCamelCase ) for image in images] if do_resize: UpperCamelCase_: Union[str, Any] = [self.resize(image=_lowerCamelCase , size=_lowerCamelCase , resample=_lowerCamelCase ) for image in images] if do_normalize: UpperCamelCase_: Optional[Any] = [self.normalize(image=_lowerCamelCase ) for image in images] if do_color_quantize: UpperCamelCase_: Any = [to_channel_dimension_format(_lowerCamelCase , ChannelDimension.LAST ) for image in images] # color quantize from (batch_size, height, width, 3) to (batch_size, height, width) UpperCamelCase_: Optional[Any] = np.array(_lowerCamelCase ) UpperCamelCase_: Optional[Any] = color_quantize(_lowerCamelCase , _lowerCamelCase ).reshape(images.shape[:-1] ) # flatten to (batch_size, height*width) UpperCamelCase_: Dict = images.shape[0] UpperCamelCase_: Any = images.reshape(_lowerCamelCase , -1 ) # We need to convert back to a list of images to keep consistent behaviour across processors. UpperCamelCase_: List[Any] = list(_lowerCamelCase ) else: UpperCamelCase_: int = [to_channel_dimension_format(_lowerCamelCase , _lowerCamelCase ) for image in images] UpperCamelCase_: str = {'input_ids': images} return BatchFeature(data=_lowerCamelCase , tensor_type=_lowerCamelCase )
57
0
import re from flax.core.frozen_dict import freeze from flax.traverse_util import flatten_dict, unflatten_dict from jax.experimental import PartitionSpec as P # Sentinels _lowerCAmelCase: Any = object() # For specifying empty leaf dict `{}` _lowerCAmelCase: Dict = object() def _lowercase( __a : Tuple , __a : Optional[Any] ): a__ =tuple((re.compile(x + '$' ) for x in qs) ) for i in range(len(__a ) - len(__a ) + 1 ): a__ =[x.match(__a ) for x, y in zip(__a , ks[i:] )] if matches and all(__a ): return True return False def _lowercase( __a : Any ): def replace(__a : List[str] , __a : Tuple ): for rule, replacement in rules: if _match(__a , __a ): return replacement return val return replace def _lowercase( ): return [ # embeddings (("transformer", "wpe", "embedding"), P('mp' , __a )), (("transformer", "wte", "embedding"), P('mp' , __a )), # atention (("attention", "(q_proj|k_proj|v_proj)", "kernel"), P(__a , 'mp' )), (("attention", "out_proj", "kernel"), P('mp' , __a )), (("attention", "out_proj", "bias"), None), # mlp (("mlp", "c_fc", "kernel"), P(__a , 'mp' )), (("mlp", "c_fc", "bias"), P('mp' )), (("mlp", "c_proj", "kernel"), P('mp' , __a )), (("mlp", "c_proj", "bias"), None), # layer norms ((r"ln_\d+", "bias"), None), ((r"\d+", r"ln_\d+", "scale"), None), (("ln_f", "bias"), None), (("ln_f", "scale"), None), ] def _lowercase( __a : int ): a__ =_get_partition_rules() a__ =_replacement_rules(__a ) a__ ={k: _unmatched for k in flatten_dict(__a )} a__ ={k: replace(__a , __a ) for k, v in initd.items()} assert _unmatched not in result.values(), "Incomplete partition spec." return freeze(unflatten_dict(__a ) )
20
import numpy # List of input, output pairs A_ : Any = ( ((5, 2, 3), 15), ((6, 5, 9), 25), ((11, 12, 13), 41), ((1, 1, 1), 8), ((11, 12, 13), 41), ) A_ : List[Any] = (((515, 22, 13), 555), ((61, 35, 49), 150)) A_ : Any = [2, 4, 1, 5] A_ : List[Any] = len(train_data) A_ : List[Any] = 0.009 def snake_case (UpperCAmelCase__ , UpperCAmelCase__="train" ) -> Optional[int]: return calculate_hypothesis_value(UpperCAmelCase__ , UpperCAmelCase__ ) - output( UpperCAmelCase__ , UpperCAmelCase__ ) def snake_case (UpperCAmelCase__ ) -> Optional[Any]: UpperCamelCase_: Optional[Any] = 0 for i in range(len(UpperCAmelCase__ ) - 1 ): hyp_val += data_input_tuple[i] * parameter_vector[i + 1] hyp_val += parameter_vector[0] return hyp_val def snake_case (UpperCAmelCase__ , UpperCAmelCase__ ) -> List[Any]: if data_set == "train": return train_data[example_no][1] elif data_set == "test": return test_data[example_no][1] return None def snake_case (UpperCAmelCase__ , UpperCAmelCase__ ) -> Optional[Any]: if data_set == "train": return _hypothesis_value(train_data[example_no][0] ) elif data_set == "test": return _hypothesis_value(test_data[example_no][0] ) return None def snake_case (UpperCAmelCase__ , UpperCAmelCase__=m ) -> Optional[Any]: UpperCamelCase_: Any = 0 for i in range(UpperCAmelCase__ ): if index == -1: summation_value += _error(UpperCAmelCase__ ) else: summation_value += _error(UpperCAmelCase__ ) * train_data[i][0][index] return summation_value def snake_case (UpperCAmelCase__ ) -> Optional[Any]: UpperCamelCase_: Optional[int] = summation_of_cost_derivative(UpperCAmelCase__ , UpperCAmelCase__ ) / m return cost_derivative_value def snake_case () -> Union[str, Any]: global parameter_vector # Tune these values to set a tolerance value for predicted output UpperCamelCase_: str = 0.00_0002 UpperCamelCase_: Any = 0 UpperCamelCase_: int = 0 while True: j += 1 UpperCamelCase_: int = [0, 0, 0, 0] for i in range(0 , len(UpperCAmelCase__ ) ): UpperCamelCase_: Any = get_cost_derivative(i - 1 ) UpperCamelCase_: Optional[int] = ( parameter_vector[i] - LEARNING_RATE * cost_derivative ) if numpy.allclose( UpperCAmelCase__ , UpperCAmelCase__ , atol=UpperCAmelCase__ , rtol=UpperCAmelCase__ , ): break UpperCamelCase_: Optional[int] = temp_parameter_vector print(('Number of iterations:', j) ) def snake_case () -> int: for i in range(len(UpperCAmelCase__ ) ): print(('Actual output value:', output(UpperCAmelCase__ , 'test' )) ) print(('Hypothesis output:', calculate_hypothesis_value(UpperCAmelCase__ , 'test' )) ) if __name__ == "__main__": run_gradient_descent() print('\nTesting gradient descent for a linear hypothesis function.\n') test_gradient_descent()
57
0
import cmath import math def lowerCAmelCase_ ( lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ): __magic_name__ : List[str] =math.radians(lowerCamelCase ) __magic_name__ : Union[str, Any] =math.radians(lowerCamelCase ) # Convert voltage and current to rectangular form __magic_name__ : int =cmath.rect(lowerCamelCase , lowerCamelCase ) __magic_name__ : List[str] =cmath.rect(lowerCamelCase , lowerCamelCase ) # Calculate apparent power return voltage_rect * current_rect if __name__ == "__main__": import doctest doctest.testmod()
21
from ...utils import ( OptionalDependencyNotAvailable, is_flax_available, is_torch_available, is_transformers_available, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .multicontrolnet import MultiControlNetModel from .pipeline_controlnet import StableDiffusionControlNetPipeline from .pipeline_controlnet_imgaimg import StableDiffusionControlNetImgaImgPipeline from .pipeline_controlnet_inpaint import StableDiffusionControlNetInpaintPipeline if is_transformers_available() and is_flax_available(): from .pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline
57
0
'''simple docstring''' from math import atan, cos, radians, sin, tan from .haversine_distance import haversine_distance _snake_case : Tuple = 637_8137.0 _snake_case : Optional[int] = 635_6752.31_4245 _snake_case : int = 6378137 def snake_case_ (UpperCamelCase : float , UpperCamelCase : float , UpperCamelCase : float , UpperCamelCase : float ): '''simple docstring''' _a = (AXIS_A - AXIS_B) / AXIS_A # Parametric latitudes # https://en.wikipedia.org/wiki/Latitude#Parametric_(or_reduced)_latitude _a = atan((1 - flattening) * tan(radians(UpperCamelCase ) ) ) _a = atan((1 - flattening) * tan(radians(UpperCamelCase ) ) ) # Compute central angle between two points # using haversine theta. sigma = haversine_distance / equatorial radius _a = haversine_distance(UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) / EQUATORIAL_RADIUS # Intermediate P and Q values _a = (b_lata + b_lata) / 2 _a = (b_lata - b_lata) / 2 # Intermediate X value # X = (sigma - sin(sigma)) * sin^2Pcos^2Q / cos^2(sigma/2) _a = (sin(UpperCamelCase ) ** 2) * (cos(UpperCamelCase ) ** 2) _a = cos(sigma / 2 ) ** 2 _a = (sigma - sin(UpperCamelCase )) * (x_numerator / x_demonimator) # Intermediate Y value # Y = (sigma + sin(sigma)) * cos^2Psin^2Q / sin^2(sigma/2) _a = (cos(UpperCamelCase ) ** 2) * (sin(UpperCamelCase ) ** 2) _a = sin(sigma / 2 ) ** 2 _a = (sigma + sin(UpperCamelCase )) * (y_numerator / y_denominator) return EQUATORIAL_RADIUS * (sigma - ((flattening / 2) * (x_value + y_value))) if __name__ == "__main__": import doctest doctest.testmod()
22
from __future__ import annotations import unittest from transformers import AutoTokenizer, PegasusConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFPegasusForConditionalGeneration, TFPegasusModel @require_tf class _lowerCAmelCase: """simple docstring""" a : int =PegasusConfig a : List[str] ={} a : Optional[int] ='''gelu''' def __init__( self , _lowerCamelCase , _lowerCamelCase=1_3 , _lowerCamelCase=7 , _lowerCamelCase=True , _lowerCamelCase=False , _lowerCamelCase=9_9 , _lowerCamelCase=3_2 , _lowerCamelCase=2 , _lowerCamelCase=4 , _lowerCamelCase=3_7 , _lowerCamelCase=0.1 , _lowerCamelCase=0.1 , _lowerCamelCase=4_0 , _lowerCamelCase=2 , _lowerCamelCase=1 , _lowerCamelCase=0 , ): UpperCamelCase_: List[Any] = parent UpperCamelCase_: Dict = batch_size UpperCamelCase_: List[str] = seq_length UpperCamelCase_: List[str] = is_training UpperCamelCase_: Any = use_labels UpperCamelCase_: Optional[Any] = vocab_size UpperCamelCase_: Tuple = hidden_size UpperCamelCase_: List[Any] = num_hidden_layers UpperCamelCase_: Any = num_attention_heads UpperCamelCase_: Optional[Any] = intermediate_size UpperCamelCase_: Optional[int] = hidden_dropout_prob UpperCamelCase_: int = attention_probs_dropout_prob UpperCamelCase_: Union[str, Any] = max_position_embeddings UpperCamelCase_: Dict = eos_token_id UpperCamelCase_: Union[str, Any] = pad_token_id UpperCamelCase_: List[Any] = bos_token_id def _a ( self ): UpperCamelCase_: Union[str, Any] = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) UpperCamelCase_: int = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) UpperCamelCase_: List[str] = tf.concat([input_ids, eos_tensor] , axis=1 ) UpperCamelCase_: Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase_: Tuple = 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 , ) UpperCamelCase_: Optional[Any] = prepare_pegasus_inputs_dict(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) return config, inputs_dict def _a ( self , _lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: Optional[Any] = TFPegasusModel(config=_lowerCamelCase ).get_decoder() UpperCamelCase_: Optional[int] = inputs_dict['input_ids'] UpperCamelCase_: Optional[int] = input_ids[:1, :] UpperCamelCase_: int = inputs_dict['attention_mask'][:1, :] UpperCamelCase_: Optional[int] = inputs_dict['head_mask'] UpperCamelCase_: Optional[int] = 1 # first forward pass UpperCamelCase_: Union[str, Any] = model(_lowerCamelCase , attention_mask=_lowerCamelCase , head_mask=_lowerCamelCase , use_cache=_lowerCamelCase ) UpperCamelCase_ ,UpperCamelCase_: int = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids UpperCamelCase_: int = ids_tensor((self.batch_size, 3) , config.vocab_size ) UpperCamelCase_: List[Any] = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and UpperCamelCase_: Union[str, Any] = tf.concat([input_ids, next_tokens] , axis=-1 ) UpperCamelCase_: int = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) UpperCamelCase_: Any = model(_lowerCamelCase , attention_mask=_lowerCamelCase )[0] UpperCamelCase_: int = model(_lowerCamelCase , attention_mask=_lowerCamelCase , past_key_values=_lowerCamelCase )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice UpperCamelCase_: Optional[int] = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) UpperCamelCase_: Any = output_from_no_past[:, -3:, random_slice_idx] UpperCamelCase_: Union[str, Any] = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(_lowerCamelCase , _lowerCamelCase , rtol=1e-3 ) def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__=None , UpperCAmelCase__=None , UpperCAmelCase__=None , UpperCAmelCase__=None , UpperCAmelCase__=None , ) -> str: if attention_mask is None: UpperCamelCase_: Optional[Any] = tf.cast(tf.math.not_equal(UpperCAmelCase__ , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: UpperCamelCase_: int = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: UpperCamelCase_: str = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: UpperCamelCase_: Any = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: UpperCamelCase_: int = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class _lowerCAmelCase( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase ): """simple docstring""" a : Tuple =(TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else () a : int =(TFPegasusForConditionalGeneration,) if is_tf_available() else () a : Tuple =( { '''conversational''': TFPegasusForConditionalGeneration, '''feature-extraction''': TFPegasusModel, '''summarization''': TFPegasusForConditionalGeneration, '''text2text-generation''': TFPegasusForConditionalGeneration, '''translation''': TFPegasusForConditionalGeneration, } if is_tf_available() else {} ) a : List[str] =True a : List[str] =False a : Tuple =False def _a ( self ): UpperCamelCase_: Dict = TFPegasusModelTester(self ) UpperCamelCase_: Any = ConfigTester(self , config_class=_lowerCamelCase ) def _a ( self ): self.config_tester.run_common_tests() def _a ( self ): UpperCamelCase_: Any = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*_lowerCamelCase ) @require_sentencepiece @require_tokenizers @require_tf class _lowerCAmelCase( unittest.TestCase ): """simple docstring""" a : Dict =[ ''' 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!" ''', ] a : int =[ '''California\'s largest electricity provider has cut power to hundreds of thousands of customers in an effort to''' ''' reduce the risk of wildfires.''', '''N-Dubz have revealed they\'re "grateful" to have been nominated for four Mobo Awards.''', ] # differs slightly from pytorch, likely due to numerical differences in linear layers a : Union[str, Any] ='''google/pegasus-xsum''' @cached_property def _a ( self ): return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def _a ( self ): UpperCamelCase_: Optional[Any] = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def _a ( self , **_lowerCamelCase ): UpperCamelCase_: Dict = self.translate_src_text(**_lowerCamelCase ) assert self.expected_text == generated_words def _a ( self , **_lowerCamelCase ): UpperCamelCase_: Union[str, Any] = self.tokenizer(self.src_text , **_lowerCamelCase , padding=_lowerCamelCase , return_tensors='tf' ) UpperCamelCase_: Any = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=_lowerCamelCase , ) UpperCamelCase_: str = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=_lowerCamelCase ) return generated_words @slow def _a ( self ): self._assert_generated_batch_equal_expected()
57
0
import gc import math import unittest import torch from diffusers import UNetaDModel from diffusers.utils import floats_tensor, logging, slow, torch_all_close, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin snake_case__ : Dict = logging.get_logger(__name__) enable_full_determinism() class _a ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): """simple docstring""" A_ = UNetaDModel A_ = """sample""" @property def _UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase_ = 4 UpperCamelCase_ = 3 UpperCamelCase_ = (32, 32) UpperCamelCase_ = floats_tensor((batch_size, num_channels) + sizes ).to(_UpperCAmelCase ) UpperCamelCase_ = torch.tensor([10] ).to(_UpperCAmelCase ) return {"sample": noise, "timestep": time_step} @property def _UpperCAmelCase ( self ) -> Union[str, Any]: return (3, 32, 32) @property def _UpperCAmelCase ( self ) -> Union[str, Any]: return (3, 32, 32) def _UpperCAmelCase ( self ) -> str: UpperCamelCase_ = { 'block_out_channels': (32, 64), 'down_block_types': ('DownBlock2D', 'AttnDownBlock2D'), 'up_block_types': ('AttnUpBlock2D', 'UpBlock2D'), 'attention_head_dim': 3, 'out_channels': 3, 'in_channels': 3, 'layers_per_block': 2, 'sample_size': 32, } UpperCamelCase_ = self.dummy_input return init_dict, inputs_dict class _a ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): """simple docstring""" A_ = UNetaDModel A_ = """sample""" @property def _UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase_ = 4 UpperCamelCase_ = 4 UpperCamelCase_ = (32, 32) UpperCamelCase_ = floats_tensor((batch_size, num_channels) + sizes ).to(_UpperCAmelCase ) UpperCamelCase_ = torch.tensor([10] ).to(_UpperCAmelCase ) return {"sample": noise, "timestep": time_step} @property def _UpperCAmelCase ( self ) -> Any: return (4, 32, 32) @property def _UpperCAmelCase ( self ) -> str: return (4, 32, 32) def _UpperCAmelCase ( self ) -> Any: UpperCamelCase_ = { 'sample_size': 32, 'in_channels': 4, 'out_channels': 4, 'layers_per_block': 2, 'block_out_channels': (32, 64), 'attention_head_dim': 32, 'down_block_types': ('DownBlock2D', 'DownBlock2D'), 'up_block_types': ('UpBlock2D', 'UpBlock2D'), } UpperCamelCase_ = self.dummy_input return init_dict, inputs_dict def _UpperCAmelCase ( self ) -> str: UpperCamelCase_ , UpperCamelCase_ = UNetaDModel.from_pretrained('fusing/unet-ldm-dummy-update' , output_loading_info=_UpperCAmelCase ) self.assertIsNotNone(_UpperCAmelCase ) self.assertEqual(len(loading_info['missing_keys'] ) , 0 ) model.to(_UpperCAmelCase ) UpperCamelCase_ = model(**self.dummy_input ).sample assert image is not None, "Make sure output is not None" @unittest.skipIf(torch_device != 'cuda' , 'This test is supposed to run on GPU' ) def _UpperCAmelCase ( self ) -> Tuple: UpperCamelCase_ , UpperCamelCase_ = UNetaDModel.from_pretrained('fusing/unet-ldm-dummy-update' , output_loading_info=_UpperCAmelCase ) model.to(_UpperCAmelCase ) UpperCamelCase_ = model(**self.dummy_input ).sample assert image is not None, "Make sure output is not None" @unittest.skipIf(torch_device != 'cuda' , 'This test is supposed to run on GPU' ) def _UpperCAmelCase ( self ) -> Tuple: # by defautl model loading will use accelerate as `low_cpu_mem_usage=True` UpperCamelCase_ , UpperCamelCase_ = UNetaDModel.from_pretrained('fusing/unet-ldm-dummy-update' , output_loading_info=_UpperCAmelCase ) model_accelerate.to(_UpperCAmelCase ) model_accelerate.eval() UpperCamelCase_ = torch.randn( 1 , model_accelerate.config.in_channels , model_accelerate.config.sample_size , model_accelerate.config.sample_size , generator=torch.manual_seed(0 ) , ) UpperCamelCase_ = noise.to(_UpperCAmelCase ) UpperCamelCase_ = torch.tensor([10] * noise.shape[0] ).to(_UpperCAmelCase ) UpperCamelCase_ = model_accelerate(_UpperCAmelCase , _UpperCAmelCase )['sample'] # two models don't need to stay in the device at the same time del model_accelerate torch.cuda.empty_cache() gc.collect() UpperCamelCase_ , UpperCamelCase_ = UNetaDModel.from_pretrained( 'fusing/unet-ldm-dummy-update' , output_loading_info=_UpperCAmelCase , low_cpu_mem_usage=_UpperCAmelCase ) model_normal_load.to(_UpperCAmelCase ) model_normal_load.eval() UpperCamelCase_ = model_normal_load(_UpperCAmelCase , _UpperCAmelCase )['sample'] assert torch_all_close(_UpperCAmelCase , _UpperCAmelCase , rtol=1e-3 ) def _UpperCAmelCase ( self ) -> List[str]: UpperCamelCase_ = UNetaDModel.from_pretrained('fusing/unet-ldm-dummy-update' ) model.eval() model.to(_UpperCAmelCase ) UpperCamelCase_ = torch.randn( 1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0 ) , ) UpperCamelCase_ = noise.to(_UpperCAmelCase ) UpperCamelCase_ = torch.tensor([10] * noise.shape[0] ).to(_UpperCAmelCase ) with torch.no_grad(): UpperCamelCase_ = model(_UpperCAmelCase , _UpperCAmelCase ).sample UpperCamelCase_ = output[0, -1, -3:, -3:].flatten().cpu() # fmt: off UpperCamelCase_ = torch.tensor([-1_3.3_2_5_8, -2_0.1_1_0_0, -1_5.9_8_7_3, -1_7.6_6_1_7, -2_3.0_5_9_6, -1_7.9_4_1_9, -1_3.3_6_7_5, -1_6.1_8_8_9, -1_2.3_8_0_0] ) # fmt: on self.assertTrue(torch_all_close(_UpperCAmelCase , _UpperCAmelCase , rtol=1e-3 ) ) class _a ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): """simple docstring""" A_ = UNetaDModel A_ = """sample""" @property def _UpperCAmelCase ( self , _UpperCAmelCase=(32, 32) ) -> str: UpperCamelCase_ = 4 UpperCamelCase_ = 3 UpperCamelCase_ = floats_tensor((batch_size, num_channels) + sizes ).to(_UpperCAmelCase ) UpperCamelCase_ = torch.tensor(batch_size * [10] ).to(dtype=torch.intaa , device=_UpperCAmelCase ) return {"sample": noise, "timestep": time_step} @property def _UpperCAmelCase ( self ) -> Dict: return (3, 32, 32) @property def _UpperCAmelCase ( self ) -> Optional[int]: return (3, 32, 32) def _UpperCAmelCase ( self ) -> int: UpperCamelCase_ = { 'block_out_channels': [32, 64, 64, 64], 'in_channels': 3, 'layers_per_block': 1, 'out_channels': 3, 'time_embedding_type': 'fourier', 'norm_eps': 1e-6, 'mid_block_scale_factor': math.sqrt(2.0 ), 'norm_num_groups': None, 'down_block_types': [ 'SkipDownBlock2D', 'AttnSkipDownBlock2D', 'SkipDownBlock2D', 'SkipDownBlock2D', ], 'up_block_types': [ 'SkipUpBlock2D', 'SkipUpBlock2D', 'AttnSkipUpBlock2D', 'SkipUpBlock2D', ], } UpperCamelCase_ = self.dummy_input return init_dict, inputs_dict @slow def _UpperCAmelCase ( self ) -> int: UpperCamelCase_ , UpperCamelCase_ = UNetaDModel.from_pretrained('google/ncsnpp-celebahq-256' , output_loading_info=_UpperCAmelCase ) self.assertIsNotNone(_UpperCAmelCase ) self.assertEqual(len(loading_info['missing_keys'] ) , 0 ) model.to(_UpperCAmelCase ) UpperCamelCase_ = self.dummy_input UpperCamelCase_ = floats_tensor((4, 3) + (256, 256) ).to(_UpperCAmelCase ) UpperCamelCase_ = noise UpperCamelCase_ = model(**_UpperCAmelCase ) assert image is not None, "Make sure output is not None" @slow def _UpperCAmelCase ( self ) -> Optional[int]: UpperCamelCase_ = UNetaDModel.from_pretrained('google/ncsnpp-celebahq-256' ) model.to(_UpperCAmelCase ) UpperCamelCase_ = 4 UpperCamelCase_ = 3 UpperCamelCase_ = (256, 256) UpperCamelCase_ = torch.ones((batch_size, num_channels) + sizes ).to(_UpperCAmelCase ) UpperCamelCase_ = torch.tensor(batch_size * [1e-4] ).to(_UpperCAmelCase ) with torch.no_grad(): UpperCamelCase_ = model(_UpperCAmelCase , _UpperCAmelCase ).sample UpperCamelCase_ = output[0, -3:, -3:, -1].flatten().cpu() # fmt: off UpperCamelCase_ = torch.tensor([-4_8_4_2.8_6_9_1, -6_4_9_9.6_6_3_1, -3_8_0_0.1_9_5_3, -7_9_7_8.2_6_8_6, -1_0_9_8_0.7_1_2_9, -2_0_0_2_8.8_5_3_5, 8_1_4_8.2_8_2_2, 2_3_4_2.2_9_0_5, 5_6_7.7_6_0_8] ) # fmt: on self.assertTrue(torch_all_close(_UpperCAmelCase , _UpperCAmelCase , rtol=1e-2 ) ) def _UpperCAmelCase ( self ) -> Optional[Any]: UpperCamelCase_ = UNetaDModel.from_pretrained('fusing/ncsnpp-ffhq-ve-dummy-update' ) model.to(_UpperCAmelCase ) UpperCamelCase_ = 4 UpperCamelCase_ = 3 UpperCamelCase_ = (32, 32) UpperCamelCase_ = torch.ones((batch_size, num_channels) + sizes ).to(_UpperCAmelCase ) UpperCamelCase_ = torch.tensor(batch_size * [1e-4] ).to(_UpperCAmelCase ) with torch.no_grad(): UpperCamelCase_ = model(_UpperCAmelCase , _UpperCAmelCase ).sample UpperCamelCase_ = output[0, -3:, -3:, -1].flatten().cpu() # fmt: off UpperCamelCase_ = torch.tensor([-0.0_3_2_5, -0.0_9_0_0, -0.0_8_6_9, -0.0_3_3_2, -0.0_7_2_5, -0.0_2_7_0, -0.0_1_0_1, 0.0_2_2_7, 0.0_2_5_6] ) # fmt: on self.assertTrue(torch_all_close(_UpperCAmelCase , _UpperCAmelCase , rtol=1e-2 ) ) def _UpperCAmelCase ( self ) -> Dict: # not required for this model pass
23
import unittest import numpy as np def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ = None , ) -> np.ndarray: UpperCamelCase_: str = np.shape(UpperCAmelCase__ ) UpperCamelCase_: str = np.shape(UpperCAmelCase__ ) UpperCamelCase_: List[Any] = np.shape(UpperCAmelCase__ ) if shape_a[0] != shape_b[0]: UpperCamelCase_: Any = ( 'Expected the same number of rows for A and B. ' F'''Instead found A of size {shape_a} and B of size {shape_b}''' ) raise ValueError(UpperCAmelCase__ ) if shape_b[1] != shape_c[1]: UpperCamelCase_: int = ( 'Expected the same number of columns for B and C. ' F'''Instead found B of size {shape_b} and C of size {shape_c}''' ) raise ValueError(UpperCAmelCase__ ) UpperCamelCase_: Dict = pseudo_inv if a_inv is None: try: UpperCamelCase_: Optional[Any] = np.linalg.inv(UpperCAmelCase__ ) except np.linalg.LinAlgError: raise ValueError( 'Input matrix A is not invertible. Cannot compute Schur complement.' ) return mat_c - mat_b.T @ a_inv @ mat_b class _lowerCAmelCase( unittest.TestCase ): """simple docstring""" def _a ( self ): UpperCamelCase_: Any = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) UpperCamelCase_: Dict = np.array([[0, 3], [3, 0], [2, 3]] ) UpperCamelCase_: Tuple = np.array([[2, 1], [6, 3]] ) UpperCamelCase_: Tuple = schur_complement(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) UpperCamelCase_: Optional[Any] = np.block([[a, b], [b.T, c]] ) UpperCamelCase_: List[str] = np.linalg.det(_lowerCamelCase ) UpperCamelCase_: List[str] = np.linalg.det(_lowerCamelCase ) UpperCamelCase_: Dict = np.linalg.det(_lowerCamelCase ) self.assertAlmostEqual(_lowerCamelCase , det_a * det_s ) def _a ( self ): UpperCamelCase_: int = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) UpperCamelCase_: List[str] = np.array([[0, 3], [3, 0], [2, 3]] ) UpperCamelCase_: List[str] = np.array([[2, 1], [6, 3]] ) with self.assertRaises(_lowerCamelCase ): schur_complement(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def _a ( self ): UpperCamelCase_: List[Any] = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) UpperCamelCase_: str = np.array([[0, 3], [3, 0], [2, 3]] ) UpperCamelCase_: List[Any] = np.array([[2, 1, 3], [6, 3, 5]] ) with self.assertRaises(_lowerCamelCase ): schur_complement(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) if __name__ == "__main__": import doctest doctest.testmod() unittest.main()
57
0
'''simple docstring''' 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 ) UpperCAmelCase_ : Union[str, Any] = logging.getLogger(__name__) if __name__ == "__main__": UpperCAmelCase_ : Optional[int] = 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_0_5_2_2, type=int) UpperCAmelCase_ : Union[str, Any] = parser.parse_args() logger.info(F"""Loading data from {args.data_file}""") with open(args.data_file, '''rb''') as fp: UpperCAmelCase_ : Optional[int] = pickle.load(fp) logger.info('''Counting occurrences for MLM.''') UpperCAmelCase_ : Union[str, Any] = Counter() for tk_ids in data: counter.update(tk_ids) UpperCAmelCase_ : Dict = [0] * args.vocab_size for k, v in counter.items(): UpperCAmelCase_ : str = 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)
24
import argparse import json import os from collections import OrderedDict import torch from transformers import LukeConfig, LukeForMaskedLM, MLukeTokenizer, XLMRobertaTokenizer from transformers.tokenization_utils_base import AddedToken @torch.no_grad() def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) -> int: # Load configuration defined in the metadata file with open(UpperCAmelCase__ ) as metadata_file: UpperCamelCase_: Tuple = json.load(UpperCAmelCase__ ) UpperCamelCase_: List[str] = LukeConfig(use_entity_aware_attention=UpperCAmelCase__ , **metadata['model_config'] ) # Load in the weights from the checkpoint_path UpperCamelCase_: Optional[int] = torch.load(UpperCAmelCase__ , map_location='cpu' )['module'] # Load the entity vocab file UpperCamelCase_: Any = load_original_entity_vocab(UpperCAmelCase__ ) # add an entry for [MASK2] UpperCamelCase_: List[str] = max(entity_vocab.values() ) + 1 config.entity_vocab_size += 1 UpperCamelCase_: Union[str, Any] = XLMRobertaTokenizer.from_pretrained(metadata['model_config']['bert_model_name'] ) # Add special tokens to the token vocabulary for downstream tasks UpperCamelCase_: Any = AddedToken('<ent>' , lstrip=UpperCAmelCase__ , rstrip=UpperCAmelCase__ ) UpperCamelCase_: Optional[Any] = AddedToken('<ent2>' , lstrip=UpperCAmelCase__ , rstrip=UpperCAmelCase__ ) 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(UpperCAmelCase__ ) with open(os.path.join(UpperCAmelCase__ , 'tokenizer_config.json' ) , 'r' ) as f: UpperCamelCase_: Union[str, Any] = json.load(UpperCAmelCase__ ) UpperCamelCase_: str = 'MLukeTokenizer' with open(os.path.join(UpperCAmelCase__ , 'tokenizer_config.json' ) , 'w' ) as f: json.dump(UpperCAmelCase__ , UpperCAmelCase__ ) with open(os.path.join(UpperCAmelCase__ , MLukeTokenizer.vocab_files_names['entity_vocab_file'] ) , 'w' ) as f: json.dump(UpperCAmelCase__ , UpperCAmelCase__ ) UpperCamelCase_: Optional[Any] = MLukeTokenizer.from_pretrained(UpperCAmelCase__ ) # Initialize the embeddings of the special tokens UpperCamelCase_: Any = tokenizer.convert_tokens_to_ids(['@'] )[0] UpperCamelCase_: List[str] = tokenizer.convert_tokens_to_ids(['#'] )[0] UpperCamelCase_: Tuple = state_dict['embeddings.word_embeddings.weight'] UpperCamelCase_: int = word_emb[ent_init_index].unsqueeze(0 ) UpperCamelCase_: Any = word_emb[enta_init_index].unsqueeze(0 ) UpperCamelCase_: str = torch.cat([word_emb, ent_emb, enta_emb] ) # add special tokens for 'entity_predictions.bias' for bias_name in ["lm_head.decoder.bias", "lm_head.bias"]: UpperCamelCase_: Union[str, Any] = state_dict[bias_name] UpperCamelCase_: Tuple = decoder_bias[ent_init_index].unsqueeze(0 ) UpperCamelCase_: Any = decoder_bias[enta_init_index].unsqueeze(0 ) UpperCamelCase_: Optional[Any] = torch.cat([decoder_bias, ent_decoder_bias, enta_decoder_bias] ) # 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_: List[Any] = F'''encoder.layer.{layer_index}.attention.self.''' UpperCamelCase_: str = state_dict[prefix + matrix_name] UpperCamelCase_: Dict = state_dict[prefix + matrix_name] UpperCamelCase_: Dict = state_dict[prefix + matrix_name] # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks UpperCamelCase_: List[str] = state_dict['entity_embeddings.entity_embeddings.weight'] UpperCamelCase_: int = entity_emb[entity_vocab['[MASK]']].unsqueeze(0 ) UpperCamelCase_: Tuple = torch.cat([entity_emb, entity_mask_emb] ) # add [MASK2] for 'entity_predictions.bias' UpperCamelCase_: Optional[Any] = state_dict['entity_predictions.bias'] UpperCamelCase_: List[str] = entity_prediction_bias[entity_vocab['[MASK]']].unsqueeze(0 ) UpperCamelCase_: List[Any] = torch.cat([entity_prediction_bias, entity_mask_bias] ) UpperCamelCase_: List[Any] = LukeForMaskedLM(config=UpperCAmelCase__ ).eval() state_dict.pop('entity_predictions.decoder.weight' ) state_dict.pop('lm_head.decoder.weight' ) state_dict.pop('lm_head.decoder.bias' ) UpperCamelCase_: Optional[Any] = OrderedDict() for key, value in state_dict.items(): if not (key.startswith('lm_head' ) or key.startswith('entity_predictions' )): UpperCamelCase_: Union[str, Any] = state_dict[key] else: UpperCamelCase_: Dict = state_dict[key] UpperCamelCase_ ,UpperCamelCase_: Optional[int] = model.load_state_dict(UpperCAmelCase__ , strict=UpperCAmelCase__ ) if set(UpperCAmelCase__ ) != {"luke.embeddings.position_ids"}: raise ValueError(F'''Unexpected unexpected_keys: {unexpected_keys}''' ) if set(UpperCAmelCase__ ) != { "lm_head.decoder.weight", "lm_head.decoder.bias", "entity_predictions.decoder.weight", }: raise ValueError(F'''Unexpected missing_keys: {missing_keys}''' ) model.tie_weights() assert (model.luke.embeddings.word_embeddings.weight == model.lm_head.decoder.weight).all() assert (model.luke.entity_embeddings.entity_embeddings.weight == model.entity_predictions.decoder.weight).all() # Check outputs UpperCamelCase_: Optional[int] = MLukeTokenizer.from_pretrained(UpperCAmelCase__ , task='entity_classification' ) UpperCamelCase_: Tuple = 'ISO 639-3 uses the code fas for the dialects spoken across Iran and アフガニスタン (Afghanistan).' UpperCamelCase_: Optional[int] = (0, 9) UpperCamelCase_: Union[str, Any] = tokenizer(UpperCAmelCase__ , entity_spans=[span] , return_tensors='pt' ) UpperCamelCase_: str = model(**UpperCAmelCase__ ) # Verify word hidden states if model_size == "large": raise NotImplementedError else: # base UpperCamelCase_: int = torch.Size((1, 3_3, 7_6_8) ) UpperCamelCase_: Tuple = torch.tensor([[0.0892, 0.0596, -0.2819], [0.0134, 0.1199, 0.0573], [-0.0169, 0.0927, 0.0644]] ) 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] , UpperCAmelCase__ , atol=1E-4 ): raise ValueError # Verify entity hidden states if model_size == "large": raise NotImplementedError else: # base UpperCamelCase_: Dict = torch.Size((1, 1, 7_6_8) ) UpperCamelCase_: Tuple = torch.tensor([[-0.1482, 0.0609, 0.0322]] ) 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] , UpperCAmelCase__ , atol=1E-4 ): raise ValueError # Verify masked word/entity prediction UpperCamelCase_: str = MLukeTokenizer.from_pretrained(UpperCAmelCase__ ) UpperCamelCase_: int = 'Tokyo is the capital of <mask>.' UpperCamelCase_: Dict = (2_4, 3_0) UpperCamelCase_: int = tokenizer(UpperCAmelCase__ , entity_spans=[span] , return_tensors='pt' ) UpperCamelCase_: Dict = model(**UpperCAmelCase__ ) UpperCamelCase_: Optional[int] = encoding['input_ids'][0].tolist() UpperCamelCase_: List[Any] = input_ids.index(tokenizer.convert_tokens_to_ids('<mask>' ) ) UpperCamelCase_: Any = outputs.logits[0][mask_position_id].argmax(dim=-1 ) assert "Japan" == tokenizer.decode(UpperCAmelCase__ ) UpperCamelCase_: Union[str, Any] = outputs.entity_logits[0][0].argmax().item() UpperCamelCase_: Optional[Any] = [ entity for entity, entity_id in tokenizer.entity_vocab.items() if entity_id == predicted_entity_id ] assert [e for e in multilingual_predicted_entities if e.startswith('en:' )][0] == "en:Japan" # Finally, save our PyTorch model and tokenizer print('Saving PyTorch model to {}'.format(UpperCAmelCase__ ) ) model.save_pretrained(UpperCAmelCase__ ) def snake_case (UpperCAmelCase__ ) -> int: UpperCamelCase_: Optional[Any] = ['[MASK]', '[PAD]', '[UNK]'] UpperCamelCase_: Any = [json.loads(UpperCAmelCase__ ) for line in open(UpperCAmelCase__ )] UpperCamelCase_: Tuple = {} for entry in data: UpperCamelCase_: Optional[int] = entry['id'] for entity_name, language in entry["entities"]: if entity_name in SPECIAL_TOKENS: UpperCamelCase_: Union[str, Any] = entity_id break UpperCamelCase_: Dict = F'''{language}:{entity_name}''' UpperCamelCase_: Optional[int] = entity_id return new_mapping if __name__ == "__main__": A_ : Tuple = 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_ : List[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, )
57
0
from collections.abc import Callable import numpy as np def lowerCamelCase__ ( _a , _a , _a , _a , _a): SCREAMING_SNAKE_CASE : List[Any] = int(np.ceil((x_end - xa) / step_size)) SCREAMING_SNAKE_CASE : Tuple = np.zeros((n + 1,)) SCREAMING_SNAKE_CASE : List[Any] = ya SCREAMING_SNAKE_CASE : str = xa for k in range(_a): SCREAMING_SNAKE_CASE : Optional[int] = y[k] + step_size * ode_func(_a , y[k]) SCREAMING_SNAKE_CASE : Union[str, Any] = y[k] + ( (step_size / 2) * (ode_func(_a , y[k]) + ode_func(x + step_size , _a)) ) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
25
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A_ : Optional[Any] = logging.get_logger(__name__) A_ : Optional[Any] = { 'distilbert-base-uncased': 'https://huggingface.co/distilbert-base-uncased/resolve/main/config.json', 'distilbert-base-uncased-distilled-squad': ( 'https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/config.json' ), 'distilbert-base-cased': 'https://huggingface.co/distilbert-base-cased/resolve/main/config.json', 'distilbert-base-cased-distilled-squad': ( 'https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/config.json' ), 'distilbert-base-german-cased': 'https://huggingface.co/distilbert-base-german-cased/resolve/main/config.json', 'distilbert-base-multilingual-cased': ( 'https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/config.json' ), 'distilbert-base-uncased-finetuned-sst-2-english': ( 'https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-english/resolve/main/config.json' ), } class _lowerCAmelCase( UpperCAmelCase_ ): """simple docstring""" a : Dict ='''distilbert''' a : List[str] ={ '''hidden_size''': '''dim''', '''num_attention_heads''': '''n_heads''', '''num_hidden_layers''': '''n_layers''', } def __init__( self , _lowerCamelCase=3_0_5_2_2 , _lowerCamelCase=5_1_2 , _lowerCamelCase=False , _lowerCamelCase=6 , _lowerCamelCase=1_2 , _lowerCamelCase=7_6_8 , _lowerCamelCase=4 * 7_6_8 , _lowerCamelCase=0.1 , _lowerCamelCase=0.1 , _lowerCamelCase="gelu" , _lowerCamelCase=0.0_2 , _lowerCamelCase=0.1 , _lowerCamelCase=0.2 , _lowerCamelCase=0 , **_lowerCamelCase , ): UpperCamelCase_: Tuple = vocab_size UpperCamelCase_: str = max_position_embeddings UpperCamelCase_: Optional[int] = sinusoidal_pos_embds UpperCamelCase_: Union[str, Any] = n_layers UpperCamelCase_: Optional[int] = n_heads UpperCamelCase_: int = dim UpperCamelCase_: Tuple = hidden_dim UpperCamelCase_: Any = dropout UpperCamelCase_: Optional[Any] = attention_dropout UpperCamelCase_: List[str] = activation UpperCamelCase_: Optional[Any] = initializer_range UpperCamelCase_: Optional[Any] = qa_dropout UpperCamelCase_: List[str] = seq_classif_dropout super().__init__(**_lowerCamelCase , pad_token_id=_lowerCamelCase ) class _lowerCAmelCase( UpperCAmelCase_ ): """simple docstring""" @property def _a ( self ): if self.task == "multiple-choice": UpperCamelCase_: Any = {0: 'batch', 1: 'choice', 2: 'sequence'} else: UpperCamelCase_: List[Any] = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
57
0
'''simple docstring''' from typing import List, Optional, Tuple, Union import torch from ...utils import logging, randn_tensor from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline __UpperCamelCase = logging.get_logger(__name__) # pylint: disable=invalid-name class _A ( __lowercase ): def __init__( self : Optional[Any] , __magic_name__ : Optional[Any] , __magic_name__ : int ) -> Optional[int]: """simple docstring""" super().__init__() self.register_modules(unet=__magic_name__ , scheduler=__magic_name__ ) @torch.no_grad() def __call__( self : Any , __magic_name__ : int = 1 , __magic_name__ : int = 1_00 , __magic_name__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , __magic_name__ : Optional[float] = None , __magic_name__ : bool = True , ) -> Union[AudioPipelineOutput, Tuple]: """simple docstring""" if audio_length_in_s is None: __snake_case : Optional[Any] = self.unet.config.sample_size / self.unet.config.sample_rate __snake_case : Union[str, Any] = audio_length_in_s * self.unet.config.sample_rate __snake_case : List[str] = 2 ** len(self.unet.up_blocks ) if sample_size < 3 * down_scale_factor: raise ValueError( f'''{audio_length_in_s} is too small. Make sure it\'s bigger or equal to''' f''' {3 * down_scale_factor / self.unet.config.sample_rate}.''' ) __snake_case : List[str] = int(__magic_name__ ) if sample_size % down_scale_factor != 0: __snake_case : Tuple = ( (audio_length_in_s * self.unet.config.sample_rate) // down_scale_factor + 1 ) * down_scale_factor logger.info( f'''{audio_length_in_s} is increased to {sample_size / self.unet.config.sample_rate} so that it can be handled''' f''' by the model. It will be cut to {original_sample_size / self.unet.config.sample_rate} after the denoising''' """ process.""" ) __snake_case : List[str] = int(__magic_name__ ) __snake_case : Optional[int] = next(iter(self.unet.parameters() ) ).dtype __snake_case : Optional[Any] = (batch_size, self.unet.config.in_channels, sample_size) if isinstance(__magic_name__ , __magic_name__ ) and len(__magic_name__ ) != batch_size: raise ValueError( f'''You have passed a list of generators of length {len(__magic_name__ )}, but requested an effective batch''' f''' size of {batch_size}. Make sure the batch size matches the length of the generators.''' ) __snake_case : List[Any] = randn_tensor(__magic_name__ , generator=__magic_name__ , device=self.device , dtype=__magic_name__ ) # set step values self.scheduler.set_timesteps(__magic_name__ , device=audio.device ) __snake_case : Union[str, Any] = self.scheduler.timesteps.to(__magic_name__ ) for t in self.progress_bar(self.scheduler.timesteps ): # 1. predict noise model_output __snake_case : Tuple = self.unet(__magic_name__ , __magic_name__ ).sample # 2. compute previous image: x_t -> t_t-1 __snake_case : Optional[int] = self.scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ ).prev_sample __snake_case : int = audio.clamp(-1 , 1 ).float().cpu().numpy() __snake_case : str = audio[:, :, :original_sample_size] if not return_dict: return (audio,) return AudioPipelineOutput(audios=__magic_name__ )
26
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A_ : int = { 'configuration_lilt': ['LILT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LiltConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : Any = [ 'LILT_PRETRAINED_MODEL_ARCHIVE_LIST', 'LiltForQuestionAnswering', 'LiltForSequenceClassification', 'LiltForTokenClassification', 'LiltModel', 'LiltPreTrainedModel', ] if TYPE_CHECKING: from .configuration_lilt import LILT_PRETRAINED_CONFIG_ARCHIVE_MAP, LiltConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_lilt import ( LILT_PRETRAINED_MODEL_ARCHIVE_LIST, LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, LiltPreTrainedModel, ) else: import sys A_ : Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
57
0
import json import os import unittest from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES, BioGptTokenizer from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class lowerCamelCase( __snake_case , unittest.TestCase ): '''simple docstring''' __magic_name__ = BioGptTokenizer __magic_name__ = False def lowerCAmelCase__ ( self ): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt _A = [ 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'w</w>', 'r</w>', 't</w>', 'lo', 'low', 'er</w>', 'low</w>', 'lowest</w>', 'newer</w>', 'wider</w>', '<unk>', ] _A = dict(zip(snake_case_ , range(len(snake_case_ ) ) ) ) _A = ['l o 123', 'lo w 1456', 'e r</w> 1789', ''] _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' ) as fp: fp.write(json.dumps(snake_case_ ) ) with open(self.merges_file , 'w' ) as fp: fp.write('\n'.join(snake_case_ ) ) def lowerCAmelCase__ ( self , snake_case_ ): _A = 'lower newer' _A = 'lower newer' return input_text, output_text def lowerCAmelCase__ ( self ): _A = BioGptTokenizer(self.vocab_file , self.merges_file ) _A = 'lower' _A = ['low', 'er</w>'] _A = tokenizer.tokenize(snake_case_ ) self.assertListEqual(snake_case_ , snake_case_ ) _A = tokens + ['<unk>'] _A = [14, 15, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(snake_case_ ) , snake_case_ ) @slow def lowerCAmelCase__ ( self ): _A = BioGptTokenizer.from_pretrained('microsoft/biogpt' ) _A = tokenizer.encode('sequence builders' , add_special_tokens=snake_case_ ) _A = tokenizer.encode('multi-sequence build' , add_special_tokens=snake_case_ ) _A = tokenizer.build_inputs_with_special_tokens(snake_case_ ) _A = tokenizer.build_inputs_with_special_tokens(snake_case_ , snake_case_ ) self.assertTrue(encoded_sentence == [2] + text ) self.assertTrue(encoded_pair == [2] + text + [2] + text_a )
27
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available A_ : List[str] = { 'configuration_roc_bert': ['ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'RoCBertConfig'], 'tokenization_roc_bert': ['RoCBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: pass try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : Union[str, Any] = [ 'ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'RoCBertForCausalLM', 'RoCBertForMaskedLM', 'RoCBertForMultipleChoice', 'RoCBertForPreTraining', 'RoCBertForQuestionAnswering', 'RoCBertForSequenceClassification', 'RoCBertForTokenClassification', 'RoCBertLayer', 'RoCBertModel', 'RoCBertPreTrainedModel', 'load_tf_weights_in_roc_bert', ] if TYPE_CHECKING: from .configuration_roc_bert import ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RoCBertConfig from .tokenization_roc_bert import RoCBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: raise OptionalDependencyNotAvailable() try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roc_bert import ( ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, RoCBertForCausalLM, RoCBertForMaskedLM, RoCBertForMultipleChoice, RoCBertForPreTraining, RoCBertForQuestionAnswering, RoCBertForSequenceClassification, RoCBertForTokenClassification, RoCBertLayer, RoCBertModel, RoCBertPreTrainedModel, load_tf_weights_in_roc_bert, ) else: import sys A_ : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
57
0
'''simple docstring''' import os from collections import deque import torch from torch.utils.data import Dataset class _a ( SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self, A="", A="train" ): '''simple docstring''' assert os.path.isdir(A ) SCREAMING_SNAKE_CASE : Optional[int] = [] SCREAMING_SNAKE_CASE : str = os.listdir(A ) for story_filename in story_filenames_list: if "summary" in story_filename: continue SCREAMING_SNAKE_CASE : Tuple = os.path.join(A, A ) if not os.path.isfile(A ): continue self.documents.append(A ) def __len__( self ): '''simple docstring''' return len(self.documents ) def __getitem__( self, A ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.documents[idx] SCREAMING_SNAKE_CASE : List[str] = document_path.split('/' )[-1] with open(A, encoding='utf-8' ) as source: SCREAMING_SNAKE_CASE : Union[str, Any] = source.read() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = process_story(A ) return document_name, story_lines, summary_lines def lowercase__( __UpperCamelCase: Optional[Any] ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = list(filter(lambda __UpperCamelCase : len(__UpperCamelCase ) != 0 ,[line.strip() for line in raw_story.split('\n' )] ) ) # for some unknown reason some lines miss a period, add it SCREAMING_SNAKE_CASE : List[str] = [_add_missing_period(__UpperCamelCase ) for line in nonempty_lines] # gather article lines SCREAMING_SNAKE_CASE : Tuple = [] SCREAMING_SNAKE_CASE : int = deque(__UpperCamelCase ) while True: try: SCREAMING_SNAKE_CASE : Optional[Any] = lines.popleft() if element.startswith('@highlight' ): break story_lines.append(__UpperCamelCase ) except IndexError: # if "@highlight" is absent from the file we pop # all elements until there is None, raising an exception. return story_lines, [] # gather summary lines SCREAMING_SNAKE_CASE : int = list(filter(lambda __UpperCamelCase : not t.startswith('@highlight' ) ,__UpperCamelCase ) ) return story_lines, summary_lines def lowercase__( __UpperCamelCase: Dict ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = ['.', '!', '?', '...', '\'', '`', '"', '\u2019', '\u2019', ')'] if line.startswith('@highlight' ): return line if line[-1] in END_TOKENS: return line return line + "." def lowercase__( __UpperCamelCase: List[Any] ,__UpperCamelCase: Any ,__UpperCamelCase: Optional[Any] ): """simple docstring""" if len(__UpperCamelCase ) > block_size: return sequence[:block_size] else: sequence.extend([pad_token_id] * (block_size - len(__UpperCamelCase )) ) return sequence def lowercase__( __UpperCamelCase: Optional[int] ,__UpperCamelCase: Dict ): """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = torch.ones_like(__UpperCamelCase ) SCREAMING_SNAKE_CASE : Union[str, Any] = sequence == pad_token_id SCREAMING_SNAKE_CASE : List[Any] = 0 return mask def lowercase__( __UpperCamelCase: str ,__UpperCamelCase: Any ,__UpperCamelCase: Union[str, Any] ): """simple docstring""" SCREAMING_SNAKE_CASE : Dict = [tokenizer.encode(__UpperCamelCase ) for line in story_lines] SCREAMING_SNAKE_CASE : Optional[int] = [token for sentence in story_lines_token_ids for token in sentence] SCREAMING_SNAKE_CASE : str = [tokenizer.encode(__UpperCamelCase ) for line in summary_lines] SCREAMING_SNAKE_CASE : Dict = [token for sentence in summary_lines_token_ids for token in sentence] return story_token_ids, summary_token_ids def lowercase__( __UpperCamelCase: str ,__UpperCamelCase: Union[str, Any] ): """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = [] for sequence in batch: SCREAMING_SNAKE_CASE : Dict = -1 SCREAMING_SNAKE_CASE : List[Any] = [] for s in sequence: if s == separator_token_id: sentence_num += 1 embeddings.append(sentence_num % 2 ) batch_embeddings.append(__UpperCamelCase ) return torch.tensor(__UpperCamelCase )
28
from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import BaseOutput, is_torch_available, is_transformers_available @dataclass class _lowerCAmelCase( UpperCAmelCase_ ): """simple docstring""" a : Union[List[PIL.Image.Image], np.ndarray] a : Optional[List[bool]] if is_transformers_available() and is_torch_available(): from .pipeline_semantic_stable_diffusion import SemanticStableDiffusionPipeline
57
0
"""simple docstring""" from __future__ import annotations from collections.abc import Iterable, Iterator from dataclasses import dataclass A_ = (3, 9, -11, 0, 7, 5, 1, -1) A_ = (4, 6, 2, 0, 8, 10, 3, -2) @dataclass class __lowerCamelCase : a__: int a__: Node | None class __lowerCamelCase : def __init__( self , UpperCAmelCase ): lowerCamelCase_ = None for i in sorted(UpperCAmelCase , reverse=UpperCAmelCase ): lowerCamelCase_ = Node(UpperCAmelCase , self.head ) def __iter__( self ): lowerCamelCase_ = self.head while node: yield node.data lowerCamelCase_ = node.next_node def __len__( self ): return sum(1 for _ in self ) def __str__( self ): return " -> ".join([str(UpperCAmelCase ) for node in self] ) def lowercase ( lowerCAmelCase__ ,lowerCAmelCase__ ): return SortedLinkedList(list(lowerCAmelCase__ ) + list(lowerCAmelCase__ ) ) if __name__ == "__main__": import doctest doctest.testmod() A_ = SortedLinkedList print(merge_lists(SSL(test_data_odd), SSL(test_data_even)))
29
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConfig, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaForCTC, WavaVecaForPreTraining, WavaVecaProcessor, logging, ) from transformers.models.wavaveca.modeling_wavaveca import WavaVecaForSequenceClassification logging.set_verbosity_info() A_ : Tuple = logging.get_logger(__name__) A_ : Optional[int] = { 'post_extract_proj': 'feature_projection.projection', 'encoder.pos_conv.0': 'encoder.pos_conv_embed.conv', 'self_attn.k_proj': 'encoder.layers.*.attention.k_proj', 'self_attn.v_proj': 'encoder.layers.*.attention.v_proj', 'self_attn.q_proj': 'encoder.layers.*.attention.q_proj', 'self_attn.out_proj': 'encoder.layers.*.attention.out_proj', 'self_attn_layer_norm': 'encoder.layers.*.layer_norm', 'fc1': 'encoder.layers.*.feed_forward.intermediate_dense', 'fc2': 'encoder.layers.*.feed_forward.output_dense', 'final_layer_norm': 'encoder.layers.*.final_layer_norm', 'encoder.layer_norm': 'encoder.layer_norm', 'adapter_layer': 'encoder.layers.*.adapter_layer', 'w2v_model.layer_norm': 'feature_projection.layer_norm', 'quantizer.weight_proj': 'quantizer.weight_proj', 'quantizer.vars': 'quantizer.codevectors', 'project_q': 'project_q', 'final_proj': 'project_hid', 'w2v_encoder.proj': 'lm_head', 'mask_emb': 'masked_spec_embed', 'pooling_layer.linear': 'projector', 'pooling_layer.projection': 'classifier', } A_ : int = [ 'lm_head', 'quantizer.weight_proj', 'quantizer.codevectors', 'project_q', 'project_hid', 'projector', 'classifier', ] def snake_case (UpperCAmelCase__ ) -> str: UpperCamelCase_: Tuple = {} with open(UpperCAmelCase__ , 'r' ) as file: for line_number, line in enumerate(UpperCAmelCase__ ): UpperCamelCase_: List[Any] = line.strip() if line: UpperCamelCase_: List[Any] = line.split() UpperCamelCase_: Optional[Any] = line_number UpperCamelCase_: Any = words[0] UpperCamelCase_: List[Any] = value return result def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) -> List[str]: for attribute in key.split('.' ): UpperCamelCase_: str = getattr(UpperCAmelCase__ , UpperCAmelCase__ ) UpperCamelCase_: str = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(UpperCAmelCase__ ): UpperCamelCase_: Any = PARAM_MAPPING[full_name.split('.' )[-1]] UpperCamelCase_: Dict = 'param' if weight_type is not None and weight_type != "param": UpperCamelCase_: Optional[Any] = getattr(UpperCAmelCase__ , UpperCAmelCase__ ).shape elif weight_type is not None and weight_type == "param": UpperCamelCase_: Optional[Any] = hf_pointer for attribute in hf_param_name.split('.' ): UpperCamelCase_: str = getattr(UpperCAmelCase__ , UpperCAmelCase__ ) UpperCamelCase_: Tuple = shape_pointer.shape # let's reduce dimension UpperCamelCase_: int = value[0] else: UpperCamelCase_: Union[str, Any] = hf_pointer.shape if hf_shape != value.shape: raise ValueError( F'''Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be''' F''' {value.shape} for {full_name}''' ) if weight_type == "weight": UpperCamelCase_: Optional[int] = value elif weight_type == "weight_g": UpperCamelCase_: Any = value elif weight_type == "weight_v": UpperCamelCase_: Union[str, Any] = value elif weight_type == "bias": UpperCamelCase_: Union[str, Any] = value elif weight_type == "param": for attribute in hf_param_name.split('.' ): UpperCamelCase_: Dict = getattr(UpperCAmelCase__ , UpperCAmelCase__ ) UpperCamelCase_: Optional[Any] = value else: UpperCamelCase_: int = value logger.info(F'''{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.''' ) def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) -> Any: UpperCamelCase_: Union[str, Any] = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(UpperCAmelCase__ ): UpperCamelCase_: Dict = PARAM_MAPPING[full_name.split('.' )[-1]] UpperCamelCase_: List[Any] = 'param' if weight_type is not None and weight_type != "param": UpperCamelCase_: List[Any] = '.'.join([key, weight_type] ) elif weight_type is not None and weight_type == "param": UpperCamelCase_: Any = '.'.join([key, hf_param_name] ) else: UpperCamelCase_: Union[str, Any] = key UpperCamelCase_: Any = value if 'lm_head' in full_key else value[0] A_ : str = { 'W_a': 'linear_1.weight', 'W_b': 'linear_2.weight', 'b_a': 'linear_1.bias', 'b_b': 'linear_2.bias', 'ln_W': 'norm.weight', 'ln_b': 'norm.bias', } def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__=None , UpperCAmelCase__=None ) -> Any: UpperCamelCase_: Optional[int] = False for key, mapped_key in MAPPING.items(): UpperCamelCase_: Tuple = 'wav2vec2.' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]: UpperCamelCase_: Optional[Any] = True if "*" in mapped_key: UpperCamelCase_: Optional[int] = name.split(UpperCAmelCase__ )[0].split('.' )[-2] UpperCamelCase_: Any = mapped_key.replace('*' , UpperCAmelCase__ ) if "weight_g" in name: UpperCamelCase_: Union[str, Any] = 'weight_g' elif "weight_v" in name: UpperCamelCase_: Dict = 'weight_v' elif "bias" in name: UpperCamelCase_: int = 'bias' elif "weight" in name: # TODO: don't match quantizer.weight_proj UpperCamelCase_: str = 'weight' else: UpperCamelCase_: Union[str, Any] = None if hf_dict is not None: rename_dict(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) else: set_recursively(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) return is_used return is_used def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) -> List[str]: UpperCamelCase_: List[Any] = [] UpperCamelCase_: Dict = fairseq_model.state_dict() UpperCamelCase_: Optional[Any] = hf_model.wavaveca.feature_extractor for name, value in fairseq_dict.items(): UpperCamelCase_: Union[str, Any] = False if "conv_layers" in name: load_conv_layer( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , hf_model.config.feat_extract_norm == 'group' , ) UpperCamelCase_: List[Any] = True else: UpperCamelCase_: Tuple = load_wavaveca_layer(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) if not is_used: unused_weights.append(UpperCAmelCase__ ) logger.warning(F'''Unused weights: {unused_weights}''' ) def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) -> Any: UpperCamelCase_: Any = full_name.split('conv_layers.' )[-1] UpperCamelCase_: int = name.split('.' ) UpperCamelCase_: int = int(items[0] ) UpperCamelCase_: Union[str, Any] = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.''' ) UpperCamelCase_: Union[str, Any] = value logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.''' ) UpperCamelCase_: int = value logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.''' ) UpperCamelCase_: Union[str, Any] = value logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.''' ) UpperCamelCase_: List[Any] = value logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) else: unused_weights.append(UpperCAmelCase__ ) @torch.no_grad() def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__=None , UpperCAmelCase__=None , UpperCAmelCase__=True , UpperCAmelCase__=False ) -> Dict: if config_path is not None: UpperCamelCase_: Tuple = WavaVecaConfig.from_pretrained(UpperCAmelCase__ ) else: UpperCamelCase_: List[str] = WavaVecaConfig() if is_seq_class: UpperCamelCase_: int = read_txt_into_dict(UpperCAmelCase__ ) UpperCamelCase_: Tuple = idalabel UpperCamelCase_: str = WavaVecaForSequenceClassification(UpperCAmelCase__ ) UpperCamelCase_: Optional[int] = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6_0_0_0 , padding_value=0 , do_normalize=UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , ) feature_extractor.save_pretrained(UpperCAmelCase__ ) elif is_finetuned: if dict_path: UpperCamelCase_: List[Any] = Dictionary.load(UpperCAmelCase__ ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq UpperCamelCase_: Dict = target_dict.pad_index UpperCamelCase_: Tuple = target_dict.bos_index UpperCamelCase_: Optional[Any] = target_dict.eos_index UpperCamelCase_: Union[str, Any] = len(target_dict.symbols ) UpperCamelCase_: int = os.path.join(UpperCAmelCase__ , 'vocab.json' ) if not os.path.isdir(UpperCAmelCase__ ): logger.error('--pytorch_dump_folder_path ({}) should be a directory'.format(UpperCAmelCase__ ) ) return os.makedirs(UpperCAmelCase__ , exist_ok=UpperCAmelCase__ ) UpperCamelCase_: str = target_dict.indices # fairseq has the <pad> and <s> switched UpperCamelCase_: List[str] = 0 UpperCamelCase_: List[Any] = 1 with open(UpperCAmelCase__ , 'w' , encoding='utf-8' ) as vocab_handle: json.dump(UpperCAmelCase__ , UpperCAmelCase__ ) UpperCamelCase_: Union[str, Any] = WavaVecaCTCTokenizer( UpperCAmelCase__ , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token='|' , do_lower_case=UpperCAmelCase__ , ) UpperCamelCase_: Any = True if config.feat_extract_norm == 'layer' else False UpperCamelCase_: Tuple = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6_0_0_0 , padding_value=0 , do_normalize=UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , ) UpperCamelCase_: Dict = WavaVecaProcessor(feature_extractor=UpperCAmelCase__ , tokenizer=UpperCAmelCase__ ) processor.save_pretrained(UpperCAmelCase__ ) UpperCamelCase_: Any = WavaVecaForCTC(UpperCAmelCase__ ) else: UpperCamelCase_: Any = WavaVecaForPreTraining(UpperCAmelCase__ ) if is_finetuned or is_seq_class: UpperCamelCase_ ,UpperCamelCase_ ,UpperCamelCase_: Dict = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] )} ) else: UpperCamelCase_: List[str] = argparse.Namespace(task='audio_pretraining' ) UpperCamelCase_: Any = fairseq.tasks.setup_task(UpperCAmelCase__ ) UpperCamelCase_ ,UpperCamelCase_ ,UpperCamelCase_: Union[str, Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=UpperCAmelCase__ ) UpperCamelCase_: str = model[0].eval() recursively_load_weights(UpperCAmelCase__ , UpperCAmelCase__ , not is_finetuned ) hf_wavavec.save_pretrained(UpperCAmelCase__ ) if __name__ == "__main__": A_ : str = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint') parser.add_argument('--dict_path', default=None, type=str, help='Path to dict of fine-tuned model') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') parser.add_argument( '--not_finetuned', action='store_true', help='Whether the model to convert is a fine-tuned model or not' ) parser.add_argument( '--is_seq_class', action='store_true', help='Whether the model to convert is a fine-tuned sequence classification model or not', ) A_ : int = parser.parse_args() A_ : str = not args.not_finetuned and not args.is_seq_class convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, is_finetuned, args.is_seq_class, )
57
0
import inspect import math import tempfile import unittest import numpy as np from transformers import ViTMAEConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ViTMAEForPreTraining, ViTMAEModel from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class __a: """simple docstring""" def __init__( self ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE=13 ,_SCREAMING_SNAKE_CASE=30 ,_SCREAMING_SNAKE_CASE=2 ,_SCREAMING_SNAKE_CASE=3 ,_SCREAMING_SNAKE_CASE=True ,_SCREAMING_SNAKE_CASE=True ,_SCREAMING_SNAKE_CASE=32 ,_SCREAMING_SNAKE_CASE=5 ,_SCREAMING_SNAKE_CASE=4 ,_SCREAMING_SNAKE_CASE=37 ,_SCREAMING_SNAKE_CASE="gelu" ,_SCREAMING_SNAKE_CASE=0.1 ,_SCREAMING_SNAKE_CASE=0.1 ,_SCREAMING_SNAKE_CASE=10 ,_SCREAMING_SNAKE_CASE=0.02 ,_SCREAMING_SNAKE_CASE=3 ,_SCREAMING_SNAKE_CASE=0.6 ,_SCREAMING_SNAKE_CASE=None ,) -> Any: UpperCAmelCase_ : str = parent UpperCAmelCase_ : Optional[int] = batch_size UpperCAmelCase_ : Optional[int] = image_size UpperCAmelCase_ : Tuple = patch_size UpperCAmelCase_ : Dict = num_channels UpperCAmelCase_ : List[Any] = is_training UpperCAmelCase_ : str = use_labels UpperCAmelCase_ : Optional[int] = hidden_size UpperCAmelCase_ : Optional[int] = num_hidden_layers UpperCAmelCase_ : Optional[Any] = num_attention_heads UpperCAmelCase_ : List[Any] = intermediate_size UpperCAmelCase_ : Dict = hidden_act UpperCAmelCase_ : str = hidden_dropout_prob UpperCAmelCase_ : Dict = attention_probs_dropout_prob UpperCAmelCase_ : Dict = type_sequence_label_size UpperCAmelCase_ : Union[str, Any] = initializer_range UpperCAmelCase_ : Dict = mask_ratio UpperCAmelCase_ : Optional[Any] = scope # in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above # (we add 1 for the [CLS] token) UpperCAmelCase_ : Union[str, Any] = (image_size // patch_size) ** 2 UpperCAmelCase_ : str = int(math.ceil((1 - mask_ratio) * (num_patches + 1) ) ) def a__ ( self ) -> Optional[int]: UpperCAmelCase_ : Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCAmelCase_ : Optional[Any] = None if self.use_labels: UpperCAmelCase_ : Tuple = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) UpperCAmelCase_ : int = self.get_config() return config, pixel_values, labels def a__ ( self ) -> List[str]: return ViTMAEConfig( 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=_SCREAMING_SNAKE_CASE ,initializer_range=self.initializer_range ,mask_ratio=self.mask_ratio ,) def a__ ( self ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) -> List[str]: UpperCAmelCase_ : Any = ViTMAEModel(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() UpperCAmelCase_ : Any = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def a__ ( self ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) -> Any: UpperCAmelCase_ : str = ViTMAEForPreTraining(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() UpperCAmelCase_ : Dict = model(_SCREAMING_SNAKE_CASE ) UpperCAmelCase_ : List[Any] = (self.image_size // self.patch_size) ** 2 UpperCAmelCase_ : Dict = self.patch_size**2 * self.num_channels self.parent.assertEqual(result.logits.shape ,(self.batch_size, num_patches, expected_num_channels) ) # test greyscale images UpperCAmelCase_ : str = 1 UpperCAmelCase_ : Optional[Any] = ViTMAEForPreTraining(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() UpperCAmelCase_ : int = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) UpperCAmelCase_ : Dict = model(_SCREAMING_SNAKE_CASE ) UpperCAmelCase_ : Optional[Any] = self.patch_size**2 self.parent.assertEqual(result.logits.shape ,(self.batch_size, num_patches, expected_num_channels) ) def a__ ( self ) -> Optional[int]: UpperCAmelCase_ : Tuple = self.prepare_config_and_inputs() UpperCAmelCase_, UpperCAmelCase_, UpperCAmelCase_ : Any = config_and_inputs UpperCAmelCase_ : List[str] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class __a( _a , _a , unittest.TestCase ): """simple docstring""" lowerCAmelCase = (ViTMAEModel, ViTMAEForPreTraining) if is_torch_available() else () lowerCAmelCase = {'''feature-extraction''': ViTMAEModel} if is_torch_available() else {} lowerCAmelCase = False lowerCAmelCase = False lowerCAmelCase = False lowerCAmelCase = False def a__ ( self ) -> List[str]: UpperCAmelCase_ : Optional[Any] = ViTMAEModelTester(self ) UpperCAmelCase_ : List[str] = ConfigTester(self ,config_class=_SCREAMING_SNAKE_CASE ,has_text_modality=_SCREAMING_SNAKE_CASE ,hidden_size=37 ) def a__ ( self ) -> Dict: self.config_tester.run_common_tests() @unittest.skip(reason='''ViTMAE does not use inputs_embeds''' ) def a__ ( self ) -> Dict: pass def a__ ( self ) -> str: UpperCAmelCase_, UpperCAmelCase_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase_ : Tuple = model_class(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(model.get_input_embeddings() ,(nn.Module) ) UpperCAmelCase_ : int = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_SCREAMING_SNAKE_CASE ,nn.Linear ) ) def a__ ( self ) -> List[str]: UpperCAmelCase_, UpperCAmelCase_ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase_ : Any = model_class(_SCREAMING_SNAKE_CASE ) UpperCAmelCase_ : Dict = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCAmelCase_ : Tuple = [*signature.parameters.keys()] UpperCAmelCase_ : List[Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] ,_SCREAMING_SNAKE_CASE ) def a__ ( self ) -> Optional[int]: UpperCAmelCase_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE ) def a__ ( self ) -> Tuple: UpperCAmelCase_ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*_SCREAMING_SNAKE_CASE ) def a__ ( self ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) -> Tuple: # make masks reproducible np.random.seed(2 ) UpperCAmelCase_ : List[Any] = int((pt_model.config.image_size // pt_model.config.patch_size) ** 2 ) UpperCAmelCase_ : List[Any] = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) UpperCAmelCase_ : Any = torch.from_numpy(_SCREAMING_SNAKE_CASE ) # Add `noise` argument. # PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument UpperCAmelCase_ : Union[str, Any] = pt_noise super().check_pt_tf_models(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) def a__ ( self ) -> Tuple: UpperCAmelCase_, UpperCAmelCase_ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase_ : List[str] = model_class(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() # make random mask reproducible torch.manual_seed(2 ) with torch.no_grad(): UpperCAmelCase_ : Dict = model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) ) UpperCAmelCase_ : List[str] = outputs[0].cpu().numpy() UpperCAmelCase_ : str = 0 with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(_SCREAMING_SNAKE_CASE ) UpperCAmelCase_ : Any = model_class.from_pretrained(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) # make random mask reproducible torch.manual_seed(2 ) with torch.no_grad(): UpperCAmelCase_ : int = model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) ) # Make sure we don't have nans UpperCAmelCase_ : Tuple = after_outputs[0].cpu().numpy() UpperCAmelCase_ : Optional[int] = 0 UpperCAmelCase_ : Tuple = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(_SCREAMING_SNAKE_CASE ,1e-5 ) @unittest.skip( reason='''ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load to get deterministic results.''' ) def a__ ( self ) -> Union[str, Any]: pass @unittest.skip( reason='''ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load to get deterministic results.''' ) def a__ ( self ) -> str: pass @unittest.skip( reason='''ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load to get deterministic results.''' ) def a__ ( self ) -> Dict: pass @unittest.skip(reason='''ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load''' ) def a__ ( self ) -> Union[str, Any]: pass @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def a__ ( self ) -> str: pass @slow def a__ ( self ) -> Dict: for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase_ : Tuple = ViTMAEModel.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) def lowerCamelCase__ ( ): '''simple docstring''' UpperCAmelCase_ : str = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class __a( unittest.TestCase ): """simple docstring""" @cached_property def a__ ( self ) -> Any: return ViTImageProcessor.from_pretrained('''facebook/vit-mae-base''' ) if is_vision_available() else None @slow def a__ ( self ) -> List[str]: # make random mask reproducible across the PT and TF model np.random.seed(2 ) UpperCAmelCase_ : List[str] = ViTMAEForPreTraining.from_pretrained('''facebook/vit-mae-base''' ).to(_SCREAMING_SNAKE_CASE ) UpperCAmelCase_ : int = self.default_image_processor UpperCAmelCase_ : str = prepare_img() UpperCAmelCase_ : Union[str, Any] = image_processor(images=_SCREAMING_SNAKE_CASE ,return_tensors='''pt''' ).to(_SCREAMING_SNAKE_CASE ) # prepare a noise vector that will be also used for testing the TF model # (this way we can ensure that the PT and TF models operate on the same inputs) UpperCAmelCase_ : Any = ViTMAEConfig() UpperCAmelCase_ : Any = int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2 ) UpperCAmelCase_ : Optional[Any] = np.random.uniform(size=(1, num_patches) ) # forward pass with torch.no_grad(): UpperCAmelCase_ : int = model(**_SCREAMING_SNAKE_CASE ,noise=torch.from_numpy(_SCREAMING_SNAKE_CASE ).to(device=_SCREAMING_SNAKE_CASE ) ) # verify the logits UpperCAmelCase_ : Tuple = torch.Size((1, 196, 768) ) self.assertEqual(outputs.logits.shape ,_SCREAMING_SNAKE_CASE ) UpperCAmelCase_ : Optional[Any] = torch.tensor( [[-0.05_48, -1.70_23, -0.93_25], [0.37_21, -0.56_70, -0.22_33], [0.82_35, -1.38_78, -0.35_24]] ) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3] ,expected_slice.to(_SCREAMING_SNAKE_CASE ) ,atol=1e-4 ) )
30
import inspect import os import unittest import torch import accelerate from accelerate import debug_launcher from accelerate.test_utils import ( execute_subprocess_async, require_cpu, require_huggingface_suite, require_multi_gpu, require_single_gpu, ) from accelerate.utils import patch_environment @require_huggingface_suite class _lowerCAmelCase( unittest.TestCase ): """simple docstring""" def _a ( self ): UpperCamelCase_: Optional[int] = inspect.getfile(accelerate.test_utils ) UpperCamelCase_: Dict = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ['scripts', 'external_deps', 'test_metrics.py'] ) from accelerate.test_utils.scripts.external_deps import test_metrics # noqa: F401 UpperCamelCase_: Tuple = test_metrics @require_cpu def _a ( self ): debug_launcher(self.test_metrics.main , num_processes=1 ) @require_cpu def _a ( self ): debug_launcher(self.test_metrics.main ) @require_single_gpu def _a ( self ): self.test_metrics.main() @require_multi_gpu def _a ( self ): print(f'''Found {torch.cuda.device_count()} devices.''' ) UpperCamelCase_: List[Any] = ['torchrun', f'''--nproc_per_node={torch.cuda.device_count()}''', self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(_lowerCamelCase , env=os.environ.copy() )
57
0
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 UpperCAmelCase_ ( ) -> Any: SCREAMING_SNAKE_CASE_ = 10 SCREAMING_SNAKE_CASE_ = 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' ), } ) SCREAMING_SNAKE_CASE_ = datasets.Dataset.from_dict( { 'tokens': [['foo'] * 5] * n, 'labels': [[1] * 5] * n, 'answers': [{'answer_start': [97], 'text': ['1976']}] * 10, 'id': list(range(__UpperCAmelCase ) ), } , features=__UpperCAmelCase , ) return dataset @pytest.fixture(scope='session' ) def UpperCAmelCase_ ( __UpperCAmelCase : List[str] , __UpperCAmelCase : Dict ) -> Tuple: SCREAMING_SNAKE_CASE_ = str(tmp_path_factory.mktemp('data' ) / 'file.arrow' ) dataset.map(cache_file_name=__UpperCAmelCase ) return filename # FILE_CONTENT + files lowerCamelCase__ : Optional[Any] = '\\n Text data.\n Second line of data.' @pytest.fixture(scope='session' ) def UpperCAmelCase_ ( __UpperCAmelCase : Dict ) -> str: SCREAMING_SNAKE_CASE_ = tmp_path_factory.mktemp('data' ) / 'file.txt' SCREAMING_SNAKE_CASE_ = FILE_CONTENT with open(__UpperCAmelCase , 'w' ) as f: f.write(__UpperCAmelCase ) return filename @pytest.fixture(scope='session' ) def UpperCAmelCase_ ( __UpperCAmelCase : str ) -> Any: import bza SCREAMING_SNAKE_CASE_ = tmp_path_factory.mktemp('data' ) / 'file.txt.bz2' SCREAMING_SNAKE_CASE_ = bytes(__UpperCAmelCase , 'utf-8' ) with bza.open(__UpperCAmelCase , 'wb' ) as f: f.write(__UpperCAmelCase ) return path @pytest.fixture(scope='session' ) def UpperCAmelCase_ ( __UpperCAmelCase : str ) -> List[Any]: import gzip SCREAMING_SNAKE_CASE_ = str(tmp_path_factory.mktemp('data' ) / 'file.txt.gz' ) SCREAMING_SNAKE_CASE_ = bytes(__UpperCAmelCase , 'utf-8' ) with gzip.open(__UpperCAmelCase , 'wb' ) as f: f.write(__UpperCAmelCase ) return path @pytest.fixture(scope='session' ) def UpperCAmelCase_ ( __UpperCAmelCase : str ) -> Any: if datasets.config.LZ4_AVAILABLE: import lza.frame SCREAMING_SNAKE_CASE_ = tmp_path_factory.mktemp('data' ) / 'file.txt.lz4' SCREAMING_SNAKE_CASE_ = bytes(__UpperCAmelCase , 'utf-8' ) with lza.frame.open(__UpperCAmelCase , 'wb' ) as f: f.write(__UpperCAmelCase ) return path @pytest.fixture(scope='session' ) def UpperCAmelCase_ ( __UpperCAmelCase : str , __UpperCAmelCase : List[str] ) -> List[Any]: if datasets.config.PY7ZR_AVAILABLE: import pyazr SCREAMING_SNAKE_CASE_ = tmp_path_factory.mktemp('data' ) / 'file.txt.7z' with pyazr.SevenZipFile(__UpperCAmelCase , 'w' ) as archive: archive.write(__UpperCAmelCase , arcname=os.path.basename(__UpperCAmelCase ) ) return path @pytest.fixture(scope='session' ) def UpperCAmelCase_ ( __UpperCAmelCase : List[Any] , __UpperCAmelCase : Union[str, Any] ) -> Optional[int]: import tarfile SCREAMING_SNAKE_CASE_ = tmp_path_factory.mktemp('data' ) / 'file.txt.tar' with tarfile.TarFile(__UpperCAmelCase , 'w' ) as f: f.add(__UpperCAmelCase , arcname=os.path.basename(__UpperCAmelCase ) ) return path @pytest.fixture(scope='session' ) def UpperCAmelCase_ ( __UpperCAmelCase : Union[str, Any] ) -> Optional[Any]: import lzma SCREAMING_SNAKE_CASE_ = tmp_path_factory.mktemp('data' ) / 'file.txt.xz' SCREAMING_SNAKE_CASE_ = bytes(__UpperCAmelCase , 'utf-8' ) with lzma.open(__UpperCAmelCase , 'wb' ) as f: f.write(__UpperCAmelCase ) return path @pytest.fixture(scope='session' ) def UpperCAmelCase_ ( __UpperCAmelCase : Optional[int] , __UpperCAmelCase : List[str] ) -> Union[str, Any]: import zipfile SCREAMING_SNAKE_CASE_ = tmp_path_factory.mktemp('data' ) / 'file.txt.zip' with zipfile.ZipFile(__UpperCAmelCase , 'w' ) as f: f.write(__UpperCAmelCase , arcname=os.path.basename(__UpperCAmelCase ) ) return path @pytest.fixture(scope='session' ) def UpperCAmelCase_ ( __UpperCAmelCase : List[Any] ) -> str: if datasets.config.ZSTANDARD_AVAILABLE: import zstandard as zstd SCREAMING_SNAKE_CASE_ = tmp_path_factory.mktemp('data' ) / 'file.txt.zst' SCREAMING_SNAKE_CASE_ = bytes(__UpperCAmelCase , 'utf-8' ) with zstd.open(__UpperCAmelCase , 'wb' ) as f: f.write(__UpperCAmelCase ) return path @pytest.fixture(scope='session' ) def UpperCAmelCase_ ( __UpperCAmelCase : Union[str, Any] ) -> Any: SCREAMING_SNAKE_CASE_ = tmp_path_factory.mktemp('data' ) / 'file.xml' SCREAMING_SNAKE_CASE_ = 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(__UpperCAmelCase , 'w' ) as f: f.write(__UpperCAmelCase ) return filename lowerCamelCase__ : Dict = [ {'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__ : Optional[Any] = [ {'col_1': '4', 'col_2': 4, 'col_3': 4.0}, {'col_1': '5', 'col_2': 5, 'col_3': 5.0}, ] lowerCamelCase__ : List[str] = { 'col_1': ['0', '1', '2', '3'], 'col_2': [0, 1, 2, 3], 'col_3': [0.0, 1.0, 2.0, 3.0], } lowerCamelCase__ : str = [ {'col_3': 0.0, 'col_1': '0', 'col_2': 0}, {'col_3': 1.0, 'col_1': '1', 'col_2': 1}, ] lowerCamelCase__ : Union[str, Any] = [ {'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 UpperCAmelCase_ ( ) -> Any: return DATA_DICT_OF_LISTS @pytest.fixture(scope='session' ) def UpperCAmelCase_ ( __UpperCAmelCase : str ) -> List[str]: SCREAMING_SNAKE_CASE_ = datasets.Dataset.from_dict(__UpperCAmelCase ) SCREAMING_SNAKE_CASE_ = str(tmp_path_factory.mktemp('data' ) / 'dataset.arrow' ) dataset.map(cache_file_name=__UpperCAmelCase ) return path @pytest.fixture(scope='session' ) def UpperCAmelCase_ ( __UpperCAmelCase : Dict ) -> List[str]: SCREAMING_SNAKE_CASE_ = str(tmp_path_factory.mktemp('data' ) / 'dataset.sqlite' ) with contextlib.closing(sqlitea.connect(__UpperCAmelCase ) ) as con: SCREAMING_SNAKE_CASE_ = 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 UpperCAmelCase_ ( __UpperCAmelCase : Optional[Any] ) -> Tuple: SCREAMING_SNAKE_CASE_ = str(tmp_path_factory.mktemp('data' ) / 'dataset.csv' ) with open(__UpperCAmelCase , 'w' , newline='' ) as f: SCREAMING_SNAKE_CASE_ = csv.DictWriter(__UpperCAmelCase , fieldnames=['col_1', 'col_2', 'col_3'] ) writer.writeheader() for item in DATA: writer.writerow(__UpperCAmelCase ) return path @pytest.fixture(scope='session' ) def UpperCAmelCase_ ( __UpperCAmelCase : Dict ) -> Union[str, Any]: SCREAMING_SNAKE_CASE_ = str(tmp_path_factory.mktemp('data' ) / 'dataset2.csv' ) with open(__UpperCAmelCase , 'w' , newline='' ) as f: SCREAMING_SNAKE_CASE_ = csv.DictWriter(__UpperCAmelCase , fieldnames=['col_1', 'col_2', 'col_3'] ) writer.writeheader() for item in DATA: writer.writerow(__UpperCAmelCase ) return path @pytest.fixture(scope='session' ) def UpperCAmelCase_ ( __UpperCAmelCase : str , __UpperCAmelCase : Any ) -> List[str]: import bza SCREAMING_SNAKE_CASE_ = tmp_path_factory.mktemp('data' ) / 'dataset.csv.bz2' with open(__UpperCAmelCase , 'rb' ) as f: SCREAMING_SNAKE_CASE_ = f.read() # data = bytes(FILE_CONTENT, "utf-8") with bza.open(__UpperCAmelCase , 'wb' ) as f: f.write(__UpperCAmelCase ) return path @pytest.fixture(scope='session' ) def UpperCAmelCase_ ( __UpperCAmelCase : List[Any] , __UpperCAmelCase : Tuple , __UpperCAmelCase : Tuple ) -> Union[str, Any]: SCREAMING_SNAKE_CASE_ = tmp_path_factory.mktemp('data' ) / 'dataset.csv.zip' with zipfile.ZipFile(__UpperCAmelCase , 'w' ) as f: f.write(__UpperCAmelCase , arcname=os.path.basename(__UpperCAmelCase ) ) f.write(__UpperCAmelCase , arcname=os.path.basename(__UpperCAmelCase ) ) return path @pytest.fixture(scope='session' ) def UpperCAmelCase_ ( __UpperCAmelCase : List[Any] , __UpperCAmelCase : Any , __UpperCAmelCase : Dict ) -> Union[str, Any]: SCREAMING_SNAKE_CASE_ = tmp_path_factory.mktemp('data' ) / 'dataset.csv.zip' with zipfile.ZipFile(__UpperCAmelCase , 'w' ) as f: f.write(__UpperCAmelCase , arcname=os.path.basename(csv_path.replace('.csv' , '.CSV' ) ) ) f.write(__UpperCAmelCase , arcname=os.path.basename(csva_path.replace('.csv' , '.CSV' ) ) ) return path @pytest.fixture(scope='session' ) def UpperCAmelCase_ ( __UpperCAmelCase : Any , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : List[str] ) -> Any: SCREAMING_SNAKE_CASE_ = tmp_path_factory.mktemp('data' ) / 'dataset_with_dir.csv.zip' with zipfile.ZipFile(__UpperCAmelCase , 'w' ) as f: f.write(__UpperCAmelCase , arcname=os.path.join('main_dir' , os.path.basename(__UpperCAmelCase ) ) ) f.write(__UpperCAmelCase , arcname=os.path.join('main_dir' , os.path.basename(__UpperCAmelCase ) ) ) return path @pytest.fixture(scope='session' ) def UpperCAmelCase_ ( __UpperCAmelCase : int ) -> int: SCREAMING_SNAKE_CASE_ = str(tmp_path_factory.mktemp('data' ) / 'dataset.parquet' ) SCREAMING_SNAKE_CASE_ = pa.schema( { 'col_1': pa.string(), 'col_2': pa.intaa(), 'col_3': pa.floataa(), } ) with open(__UpperCAmelCase , 'wb' ) as f: SCREAMING_SNAKE_CASE_ = pq.ParquetWriter(__UpperCAmelCase , schema=__UpperCAmelCase ) SCREAMING_SNAKE_CASE_ = pa.Table.from_pydict({k: [DATA[i][k] for i in range(len(__UpperCAmelCase ) )] for k in DATA[0]} , schema=__UpperCAmelCase ) writer.write_table(__UpperCAmelCase ) writer.close() return path @pytest.fixture(scope='session' ) def UpperCAmelCase_ ( __UpperCAmelCase : Any ) -> List[str]: SCREAMING_SNAKE_CASE_ = str(tmp_path_factory.mktemp('data' ) / 'dataset.json' ) SCREAMING_SNAKE_CASE_ = {'data': DATA} with open(__UpperCAmelCase , 'w' ) as f: json.dump(__UpperCAmelCase , __UpperCAmelCase ) return path @pytest.fixture(scope='session' ) def UpperCAmelCase_ ( __UpperCAmelCase : Optional[int] ) -> Tuple: SCREAMING_SNAKE_CASE_ = str(tmp_path_factory.mktemp('data' ) / 'dataset.json' ) SCREAMING_SNAKE_CASE_ = {'data': DATA_DICT_OF_LISTS} with open(__UpperCAmelCase , 'w' ) as f: json.dump(__UpperCAmelCase , __UpperCAmelCase ) return path @pytest.fixture(scope='session' ) def UpperCAmelCase_ ( __UpperCAmelCase : Optional[int] ) -> Union[str, Any]: SCREAMING_SNAKE_CASE_ = str(tmp_path_factory.mktemp('data' ) / 'dataset.jsonl' ) with open(__UpperCAmelCase , 'w' ) as f: for item in DATA: f.write(json.dumps(__UpperCAmelCase ) + '\n' ) return path @pytest.fixture(scope='session' ) def UpperCAmelCase_ ( __UpperCAmelCase : Union[str, Any] ) -> int: SCREAMING_SNAKE_CASE_ = str(tmp_path_factory.mktemp('data' ) / 'dataset2.jsonl' ) with open(__UpperCAmelCase , 'w' ) as f: for item in DATA: f.write(json.dumps(__UpperCAmelCase ) + '\n' ) return path @pytest.fixture(scope='session' ) def UpperCAmelCase_ ( __UpperCAmelCase : List[str] ) -> Dict: SCREAMING_SNAKE_CASE_ = str(tmp_path_factory.mktemp('data' ) / 'dataset_312.jsonl' ) with open(__UpperCAmelCase , 'w' ) as f: for item in DATA_312: f.write(json.dumps(__UpperCAmelCase ) + '\n' ) return path @pytest.fixture(scope='session' ) def UpperCAmelCase_ ( __UpperCAmelCase : Tuple ) -> int: SCREAMING_SNAKE_CASE_ = str(tmp_path_factory.mktemp('data' ) / 'dataset-str.jsonl' ) with open(__UpperCAmelCase , 'w' ) as f: for item in DATA_STR: f.write(json.dumps(__UpperCAmelCase ) + '\n' ) return path @pytest.fixture(scope='session' ) def UpperCAmelCase_ ( __UpperCAmelCase : str , __UpperCAmelCase : Optional[int] ) -> Any: import gzip SCREAMING_SNAKE_CASE_ = str(tmp_path_factory.mktemp('data' ) / 'dataset.txt.gz' ) with open(__UpperCAmelCase , 'rb' ) as orig_file: with gzip.open(__UpperCAmelCase , 'wb' ) as zipped_file: zipped_file.writelines(__UpperCAmelCase ) return path @pytest.fixture(scope='session' ) def UpperCAmelCase_ ( __UpperCAmelCase : int , __UpperCAmelCase : Optional[int] ) -> Any: import gzip SCREAMING_SNAKE_CASE_ = str(tmp_path_factory.mktemp('data' ) / 'dataset.jsonl.gz' ) with open(__UpperCAmelCase , 'rb' ) as orig_file: with gzip.open(__UpperCAmelCase , 'wb' ) as zipped_file: zipped_file.writelines(__UpperCAmelCase ) return path @pytest.fixture(scope='session' ) def UpperCAmelCase_ ( __UpperCAmelCase : int , __UpperCAmelCase : List[str] , __UpperCAmelCase : List[str] ) -> Any: SCREAMING_SNAKE_CASE_ = tmp_path_factory.mktemp('data' ) / 'dataset.jsonl.zip' with zipfile.ZipFile(__UpperCAmelCase , 'w' ) as f: f.write(__UpperCAmelCase , arcname=os.path.basename(__UpperCAmelCase ) ) f.write(__UpperCAmelCase , arcname=os.path.basename(__UpperCAmelCase ) ) return path @pytest.fixture(scope='session' ) def UpperCAmelCase_ ( __UpperCAmelCase : Dict , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : Tuple , __UpperCAmelCase : Tuple ) -> int: SCREAMING_SNAKE_CASE_ = tmp_path_factory.mktemp('data' ) / 'dataset_nested.jsonl.zip' with zipfile.ZipFile(__UpperCAmelCase , 'w' ) as f: f.write(__UpperCAmelCase , arcname=os.path.join('nested' , os.path.basename(__UpperCAmelCase ) ) ) return path @pytest.fixture(scope='session' ) def UpperCAmelCase_ ( __UpperCAmelCase : int , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Optional[int] ) -> Tuple: SCREAMING_SNAKE_CASE_ = tmp_path_factory.mktemp('data' ) / 'dataset_with_dir.jsonl.zip' with zipfile.ZipFile(__UpperCAmelCase , 'w' ) as f: f.write(__UpperCAmelCase , arcname=os.path.join('main_dir' , os.path.basename(__UpperCAmelCase ) ) ) f.write(__UpperCAmelCase , arcname=os.path.join('main_dir' , os.path.basename(__UpperCAmelCase ) ) ) return path @pytest.fixture(scope='session' ) def UpperCAmelCase_ ( __UpperCAmelCase : str , __UpperCAmelCase : str , __UpperCAmelCase : List[str] ) -> Optional[Any]: SCREAMING_SNAKE_CASE_ = tmp_path_factory.mktemp('data' ) / 'dataset.jsonl.tar' with tarfile.TarFile(__UpperCAmelCase , 'w' ) as f: f.add(__UpperCAmelCase , arcname=os.path.basename(__UpperCAmelCase ) ) f.add(__UpperCAmelCase , arcname=os.path.basename(__UpperCAmelCase ) ) return path @pytest.fixture(scope='session' ) def UpperCAmelCase_ ( __UpperCAmelCase : Any , __UpperCAmelCase : List[Any] , __UpperCAmelCase : List[Any] , __UpperCAmelCase : List[str] ) -> Union[str, Any]: SCREAMING_SNAKE_CASE_ = tmp_path_factory.mktemp('data' ) / 'dataset_nested.jsonl.tar' with tarfile.TarFile(__UpperCAmelCase , 'w' ) as f: f.add(__UpperCAmelCase , arcname=os.path.join('nested' , os.path.basename(__UpperCAmelCase ) ) ) return path @pytest.fixture(scope='session' ) def UpperCAmelCase_ ( __UpperCAmelCase : List[str] ) -> Dict: SCREAMING_SNAKE_CASE_ = ['0', '1', '2', '3'] SCREAMING_SNAKE_CASE_ = str(tmp_path_factory.mktemp('data' ) / 'dataset.txt' ) with open(__UpperCAmelCase , 'w' ) as f: for item in data: f.write(item + '\n' ) return path @pytest.fixture(scope='session' ) def UpperCAmelCase_ ( __UpperCAmelCase : Tuple ) -> Union[str, Any]: SCREAMING_SNAKE_CASE_ = ['0', '1', '2', '3'] SCREAMING_SNAKE_CASE_ = str(tmp_path_factory.mktemp('data' ) / 'dataset2.txt' ) with open(__UpperCAmelCase , 'w' ) as f: for item in data: f.write(item + '\n' ) return path @pytest.fixture(scope='session' ) def UpperCAmelCase_ ( __UpperCAmelCase : Optional[int] ) -> Any: SCREAMING_SNAKE_CASE_ = ['0', '1', '2', '3'] SCREAMING_SNAKE_CASE_ = tmp_path_factory.mktemp('data' ) / 'dataset.abc' with open(__UpperCAmelCase , 'w' ) as f: for item in data: f.write(item + '\n' ) return path @pytest.fixture(scope='session' ) def UpperCAmelCase_ ( __UpperCAmelCase : Dict , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : List[str] ) -> Dict: SCREAMING_SNAKE_CASE_ = tmp_path_factory.mktemp('data' ) / 'dataset.text.zip' with zipfile.ZipFile(__UpperCAmelCase , 'w' ) as f: f.write(__UpperCAmelCase , arcname=os.path.basename(__UpperCAmelCase ) ) f.write(__UpperCAmelCase , arcname=os.path.basename(__UpperCAmelCase ) ) return path @pytest.fixture(scope='session' ) def UpperCAmelCase_ ( __UpperCAmelCase : Any , __UpperCAmelCase : List[str] , __UpperCAmelCase : Optional[int] ) -> Tuple: SCREAMING_SNAKE_CASE_ = tmp_path_factory.mktemp('data' ) / 'dataset_with_dir.text.zip' with zipfile.ZipFile(__UpperCAmelCase , 'w' ) as f: f.write(__UpperCAmelCase , arcname=os.path.join('main_dir' , os.path.basename(__UpperCAmelCase ) ) ) f.write(__UpperCAmelCase , arcname=os.path.join('main_dir' , os.path.basename(__UpperCAmelCase ) ) ) return path @pytest.fixture(scope='session' ) def UpperCAmelCase_ ( __UpperCAmelCase : List[Any] , __UpperCAmelCase : List[str] , __UpperCAmelCase : Optional[int] ) -> Tuple: SCREAMING_SNAKE_CASE_ = tmp_path_factory.mktemp('data' ) / 'dataset.ext.zip' with zipfile.ZipFile(__UpperCAmelCase , 'w' ) as f: f.write(__UpperCAmelCase , arcname=os.path.basename('unsupported.ext' ) ) f.write(__UpperCAmelCase , arcname=os.path.basename('unsupported_2.ext' ) ) return path @pytest.fixture(scope='session' ) def UpperCAmelCase_ ( __UpperCAmelCase : int ) -> Dict: SCREAMING_SNAKE_CASE_ = '\n'.join(['First', 'Second\u2029with Unicode new line', 'Third'] ) SCREAMING_SNAKE_CASE_ = str(tmp_path_factory.mktemp('data' ) / 'dataset_with_unicode_new_lines.txt' ) with open(__UpperCAmelCase , 'w' , encoding='utf-8' ) as f: f.write(__UpperCAmelCase ) return path @pytest.fixture(scope='session' ) def UpperCAmelCase_ ( ) -> str: return os.path.join('tests' , 'features' , 'data' , 'test_image_rgb.jpg' ) @pytest.fixture(scope='session' ) def UpperCAmelCase_ ( ) -> int: return os.path.join('tests' , 'features' , 'data' , 'test_audio_44100.wav' ) @pytest.fixture(scope='session' ) def UpperCAmelCase_ ( __UpperCAmelCase : Tuple , __UpperCAmelCase : List[str] ) -> List[Any]: SCREAMING_SNAKE_CASE_ = tmp_path_factory.mktemp('data' ) / 'dataset.img.zip' with zipfile.ZipFile(__UpperCAmelCase , 'w' ) as f: f.write(__UpperCAmelCase , arcname=os.path.basename(__UpperCAmelCase ) ) f.write(__UpperCAmelCase , arcname=os.path.basename(__UpperCAmelCase ).replace('.jpg' , '2.jpg' ) ) return path @pytest.fixture(scope='session' ) def UpperCAmelCase_ ( __UpperCAmelCase : List[str] ) -> Dict: SCREAMING_SNAKE_CASE_ = 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
31
import math class _lowerCAmelCase: """simple docstring""" def _a ( self , _lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: int = 0.0 UpperCamelCase_: Tuple = 0.0 for i in range(len(_lowerCamelCase ) ): da += math.pow((sample[i] - weights[0][i]) , 2 ) da += math.pow((sample[i] - weights[1][i]) , 2 ) return 0 if da > da else 1 return 0 def _a ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): for i in range(len(_lowerCamelCase ) ): weights[j][i] += alpha * (sample[i] - weights[j][i]) return weights def snake_case () -> None: # Training Examples ( m, n ) UpperCamelCase_: List[str] = [[1, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 1, 1]] # weight initialization ( n, C ) UpperCamelCase_: List[Any] = [[0.2, 0.6, 0.5, 0.9], [0.8, 0.4, 0.7, 0.3]] # training UpperCamelCase_: Dict = SelfOrganizingMap() UpperCamelCase_: List[Any] = 3 UpperCamelCase_: List[str] = 0.5 for _ in range(UpperCAmelCase__ ): for j in range(len(UpperCAmelCase__ ) ): # training sample UpperCamelCase_: int = training_samples[j] # Compute the winning vector UpperCamelCase_: Tuple = self_organizing_map.get_winner(UpperCAmelCase__ , UpperCAmelCase__ ) # Update the winning vector UpperCamelCase_: Union[str, Any] = self_organizing_map.update(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) # classify test sample UpperCamelCase_: Dict = [0, 0, 0, 1] UpperCamelCase_: Union[str, Any] = self_organizing_map.get_winner(UpperCAmelCase__ , UpperCAmelCase__ ) # results print(F'''Clusters that the test sample belongs to : {winner}''' ) print(F'''Weights that have been trained : {weights}''' ) # running the main() function if __name__ == "__main__": main()
57
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tensorflow_text_available, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase_ = { "configuration_bert": ["BERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "BertConfig", "BertOnnxConfig"], "tokenization_bert": ["BasicTokenizer", "BertTokenizer", "WordpieceTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ = ["BertTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ = [ "BERT_PRETRAINED_MODEL_ARCHIVE_LIST", "BertForMaskedLM", "BertForMultipleChoice", "BertForNextSentencePrediction", "BertForPreTraining", "BertForQuestionAnswering", "BertForSequenceClassification", "BertForTokenClassification", "BertLayer", "BertLMHeadModel", "BertModel", "BertPreTrainedModel", "load_tf_weights_in_bert", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ = [ "TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFBertEmbeddings", "TFBertForMaskedLM", "TFBertForMultipleChoice", "TFBertForNextSentencePrediction", "TFBertForPreTraining", "TFBertForQuestionAnswering", "TFBertForSequenceClassification", "TFBertForTokenClassification", "TFBertLMHeadModel", "TFBertMainLayer", "TFBertModel", "TFBertPreTrainedModel", ] try: if not is_tensorflow_text_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ = ["TFBertTokenizer"] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ = [ "FlaxBertForCausalLM", "FlaxBertForMaskedLM", "FlaxBertForMultipleChoice", "FlaxBertForNextSentencePrediction", "FlaxBertForPreTraining", "FlaxBertForQuestionAnswering", "FlaxBertForSequenceClassification", "FlaxBertForTokenClassification", "FlaxBertModel", "FlaxBertPreTrainedModel", ] if TYPE_CHECKING: from .configuration_bert import BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BertConfig, BertOnnxConfig from .tokenization_bert import BasicTokenizer, BertTokenizer, WordpieceTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bert_fast import BertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bert import ( BERT_PRETRAINED_MODEL_ARCHIVE_LIST, BertForMaskedLM, BertForMultipleChoice, BertForNextSentencePrediction, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, BertForTokenClassification, BertLayer, BertLMHeadModel, BertModel, BertPreTrainedModel, load_tf_weights_in_bert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_bert import ( TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFBertEmbeddings, TFBertForMaskedLM, TFBertForMultipleChoice, TFBertForNextSentencePrediction, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertForTokenClassification, TFBertLMHeadModel, TFBertMainLayer, TFBertModel, TFBertPreTrainedModel, ) try: if not is_tensorflow_text_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bert_tf import TFBertTokenizer try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_bert import ( FlaxBertForCausalLM, FlaxBertForMaskedLM, FlaxBertForMultipleChoice, FlaxBertForNextSentencePrediction, FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification, FlaxBertForTokenClassification, FlaxBertModel, FlaxBertPreTrainedModel, ) else: import sys UpperCAmelCase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
32
from collections import namedtuple A_ : Tuple = namedtuple('from_to', 'from_ to') A_ : int = { 'cubicmeter': from_to(1, 1), 'litre': from_to(0.001, 1000), 'kilolitre': from_to(1, 1), 'gallon': from_to(0.00454, 264.172), 'cubicyard': from_to(0.76455, 1.30795), 'cubicfoot': from_to(0.028, 35.3147), 'cup': from_to(0.000236588, 4226.75), } def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) -> float: if from_type not in METRIC_CONVERSION: raise ValueError( F'''Invalid \'from_type\' value: {from_type!r} Supported values are:\n''' + ', '.join(UpperCAmelCase__ ) ) if to_type not in METRIC_CONVERSION: raise ValueError( F'''Invalid \'to_type\' value: {to_type!r}. Supported values are:\n''' + ', '.join(UpperCAmelCase__ ) ) return value * METRIC_CONVERSION[from_type].from_ * METRIC_CONVERSION[to_type].to if __name__ == "__main__": import doctest doctest.testmod()
57
0
import argparse import json import os import pickle import shutil import numpy as np import torch from distiller import Distiller from lm_seqs_dataset import LmSeqsDataset from transformers import ( BertConfig, BertForMaskedLM, BertTokenizer, DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer, GPTaConfig, GPTaLMHeadModel, GPTaTokenizer, RobertaConfig, RobertaForMaskedLM, RobertaTokenizer, ) from utils import git_log, init_gpu_params, logger, set_seed lowerCamelCase__ : str = { """distilbert""": (DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer), """roberta""": (RobertaConfig, RobertaForMaskedLM, RobertaTokenizer), """bert""": (BertConfig, BertForMaskedLM, BertTokenizer), """gpt2""": (GPTaConfig, GPTaLMHeadModel, GPTaTokenizer), } def SCREAMING_SNAKE_CASE ( __lowerCAmelCase ) -> List[str]: assert (args.mlm and args.alpha_mlm > 0.0) or (not args.mlm and args.alpha_mlm == 0.0) assert (args.alpha_mlm > 0.0 and args.alpha_clm == 0.0) or (args.alpha_mlm == 0.0 and args.alpha_clm > 0.0) if args.mlm: assert os.path.isfile(args.token_counts ) assert (args.student_type in ["roberta", "distilbert"]) and (args.teacher_type in ["roberta", "bert"]) else: assert (args.student_type in ["gpt2"]) and (args.teacher_type in ["gpt2"]) assert args.teacher_type == args.student_type or ( args.student_type == "distilbert" and args.teacher_type == "bert" ) assert os.path.isfile(args.student_config ) if args.student_pretrained_weights is not None: assert os.path.isfile(args.student_pretrained_weights ) if args.freeze_token_type_embds: assert args.student_type in ["roberta"] assert args.alpha_ce >= 0.0 assert args.alpha_mlm >= 0.0 assert args.alpha_clm >= 0.0 assert args.alpha_mse >= 0.0 assert args.alpha_cos >= 0.0 assert args.alpha_ce + args.alpha_mlm + args.alpha_clm + args.alpha_mse + args.alpha_cos > 0.0 def SCREAMING_SNAKE_CASE ( __lowerCAmelCase , __lowerCAmelCase ) -> int: if args.student_type == "roberta": snake_case__ = False elif args.student_type == "gpt2": snake_case__ = False def SCREAMING_SNAKE_CASE ( __lowerCAmelCase , __lowerCAmelCase ) -> Any: if args.student_type == "roberta": snake_case__ = False def SCREAMING_SNAKE_CASE ( ) -> Union[str, Any]: snake_case__ = argparse.ArgumentParser(description='''Training''' ) parser.add_argument('''--force''' , action='''store_true''' , help='''Overwrite dump_path if it already exists.''' ) parser.add_argument( '''--dump_path''' , type=__lowerCAmelCase , required=__lowerCAmelCase , help='''The output directory (log, checkpoints, parameters, etc.)''' ) parser.add_argument( '''--data_file''' , type=__lowerCAmelCase , required=__lowerCAmelCase , help='''The binarized file (tokenized + tokens_to_ids) and grouped by sequence.''' , ) parser.add_argument( '''--student_type''' , type=__lowerCAmelCase , choices=['''distilbert''', '''roberta''', '''gpt2'''] , required=__lowerCAmelCase , help='''The student type (DistilBERT, RoBERTa).''' , ) parser.add_argument('''--student_config''' , type=__lowerCAmelCase , required=__lowerCAmelCase , help='''Path to the student configuration.''' ) parser.add_argument( '''--student_pretrained_weights''' , default=__lowerCAmelCase , type=__lowerCAmelCase , help='''Load student initialization checkpoint.''' ) parser.add_argument( '''--teacher_type''' , choices=['''bert''', '''roberta''', '''gpt2'''] , required=__lowerCAmelCase , help='''Teacher type (BERT, RoBERTa).''' ) parser.add_argument('''--teacher_name''' , type=__lowerCAmelCase , required=__lowerCAmelCase , help='''The teacher model.''' ) parser.add_argument('''--temperature''' , default=2.0 , type=__lowerCAmelCase , help='''Temperature for the softmax temperature.''' ) parser.add_argument( '''--alpha_ce''' , default=0.5 , type=__lowerCAmelCase , help='''Linear weight for the distillation loss. Must be >=0.''' ) parser.add_argument( '''--alpha_mlm''' , default=0.0 , type=__lowerCAmelCase , help='''Linear weight for the MLM loss. Must be >=0. Should be used in conjunction with `mlm` flag.''' , ) parser.add_argument('''--alpha_clm''' , default=0.5 , type=__lowerCAmelCase , help='''Linear weight for the CLM loss. Must be >=0.''' ) parser.add_argument('''--alpha_mse''' , default=0.0 , type=__lowerCAmelCase , help='''Linear weight of the MSE loss. Must be >=0.''' ) parser.add_argument( '''--alpha_cos''' , default=0.0 , type=__lowerCAmelCase , help='''Linear weight of the cosine embedding loss. Must be >=0.''' ) parser.add_argument( '''--mlm''' , action='''store_true''' , help='''The LM step: MLM or CLM. If `mlm` is True, the MLM is used over CLM.''' ) parser.add_argument( '''--mlm_mask_prop''' , default=0.15 , type=__lowerCAmelCase , help='''Proportion of tokens for which we need to make a prediction.''' , ) parser.add_argument('''--word_mask''' , default=0.8 , type=__lowerCAmelCase , help='''Proportion of tokens to mask out.''' ) parser.add_argument('''--word_keep''' , default=0.1 , type=__lowerCAmelCase , help='''Proportion of tokens to keep.''' ) parser.add_argument('''--word_rand''' , default=0.1 , type=__lowerCAmelCase , help='''Proportion of tokens to randomly replace.''' ) parser.add_argument( '''--mlm_smoothing''' , default=0.7 , type=__lowerCAmelCase , help='''Smoothing parameter to emphasize more rare tokens (see XLM, similar to word2vec).''' , ) parser.add_argument('''--token_counts''' , type=__lowerCAmelCase , help='''The token counts in the data_file for MLM.''' ) parser.add_argument( '''--restrict_ce_to_mask''' , action='''store_true''' , help='''If true, compute the distillation loss only the [MLM] prediction distribution.''' , ) parser.add_argument( '''--freeze_pos_embs''' , action='''store_true''' , help='''Freeze positional embeddings during distillation. For student_type in [\'roberta\', \'gpt2\'] only.''' , ) parser.add_argument( '''--freeze_token_type_embds''' , action='''store_true''' , help='''Freeze token type embeddings during distillation if existent. For student_type in [\'roberta\'] only.''' , ) parser.add_argument('''--n_epoch''' , type=__lowerCAmelCase , default=3 , help='''Number of pass on the whole dataset.''' ) parser.add_argument('''--batch_size''' , type=__lowerCAmelCase , default=5 , help='''Batch size (for each process).''' ) parser.add_argument( '''--group_by_size''' , action='''store_false''' , help='''If true, group sequences that have similar length into the same batch. Default is true.''' , ) parser.add_argument( '''--gradient_accumulation_steps''' , type=__lowerCAmelCase , default=50 , help='''Gradient accumulation for larger training batches.''' , ) parser.add_argument('''--warmup_prop''' , default=0.05 , type=__lowerCAmelCase , help='''Linear warmup proportion.''' ) parser.add_argument('''--weight_decay''' , default=0.0 , type=__lowerCAmelCase , help='''Weight decay if we apply some.''' ) parser.add_argument('''--learning_rate''' , default=5e-4 , type=__lowerCAmelCase , help='''The initial learning rate for Adam.''' ) parser.add_argument('''--adam_epsilon''' , default=1e-6 , type=__lowerCAmelCase , help='''Epsilon for Adam optimizer.''' ) parser.add_argument('''--max_grad_norm''' , default=5.0 , type=__lowerCAmelCase , help='''Max gradient norm.''' ) parser.add_argument('''--initializer_range''' , default=0.02 , type=__lowerCAmelCase , help='''Random initialization range.''' ) parser.add_argument( '''--fp16''' , action='''store_true''' , help='''Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit''' , ) parser.add_argument( '''--fp16_opt_level''' , type=__lowerCAmelCase , default='''O1''' , help=( '''For fp16: Apex AMP optimization level selected in [\'O0\', \'O1\', \'O2\', and \'O3\'].''' '''See details at https://nvidia.github.io/apex/amp.html''' ) , ) parser.add_argument('''--n_gpu''' , type=__lowerCAmelCase , default=1 , help='''Number of GPUs in the node.''' ) parser.add_argument('''--local_rank''' , type=__lowerCAmelCase , default=-1 , help='''Distributed training - Local rank''' ) parser.add_argument('''--seed''' , type=__lowerCAmelCase , default=56 , help='''Random seed''' ) parser.add_argument('''--log_interval''' , type=__lowerCAmelCase , default=500 , help='''Tensorboard logging interval.''' ) parser.add_argument('''--checkpoint_interval''' , type=__lowerCAmelCase , default=4000 , help='''Checkpoint interval.''' ) snake_case__ = parser.parse_args() sanity_checks(__lowerCAmelCase ) # ARGS # init_gpu_params(__lowerCAmelCase ) set_seed(__lowerCAmelCase ) if args.is_master: if os.path.exists(args.dump_path ): if not args.force: raise ValueError( F"""Serialization dir {args.dump_path} already exists, but you have not precised wheter to overwrite""" ''' itUse `--force` if you want to overwrite it''' ) else: shutil.rmtree(args.dump_path ) if not os.path.exists(args.dump_path ): os.makedirs(args.dump_path ) logger.info(F"""Experiment will be dumped and logged in {args.dump_path}""" ) # SAVE PARAMS # logger.info(F"""Param: {args}""" ) with open(os.path.join(args.dump_path , '''parameters.json''' ) , '''w''' ) as f: json.dump(vars(__lowerCAmelCase ) , __lowerCAmelCase , indent=4 ) git_log(args.dump_path ) snake_case__ , snake_case__ , snake_case__ = MODEL_CLASSES[args.student_type] snake_case__ , snake_case__ , snake_case__ = MODEL_CLASSES[args.teacher_type] # TOKENIZER # snake_case__ = teacher_tokenizer_class.from_pretrained(args.teacher_name ) snake_case__ = {} for tok_name, tok_symbol in tokenizer.special_tokens_map.items(): snake_case__ = tokenizer.all_special_tokens.index(__lowerCAmelCase ) snake_case__ = tokenizer.all_special_ids[idx] logger.info(F"""Special tokens {special_tok_ids}""" ) snake_case__ = special_tok_ids snake_case__ = tokenizer.max_model_input_sizes[args.teacher_name] # DATA LOADER # logger.info(F"""Loading data from {args.data_file}""" ) with open(args.data_file , '''rb''' ) as fp: snake_case__ = pickle.load(__lowerCAmelCase ) if args.mlm: logger.info(F"""Loading token counts from {args.token_counts} (already pre-computed)""" ) with open(args.token_counts , '''rb''' ) as fp: snake_case__ = pickle.load(__lowerCAmelCase ) snake_case__ = np.maximum(__lowerCAmelCase , 1 ) ** -args.mlm_smoothing for idx in special_tok_ids.values(): snake_case__ = 0.0 # do not predict special tokens snake_case__ = torch.from_numpy(__lowerCAmelCase ) else: snake_case__ = None snake_case__ = LmSeqsDataset(params=__lowerCAmelCase , data=__lowerCAmelCase ) logger.info('''Data loader created.''' ) # STUDENT # logger.info(F"""Loading student config from {args.student_config}""" ) snake_case__ = student_config_class.from_pretrained(args.student_config ) snake_case__ = True if args.student_pretrained_weights is not None: logger.info(F"""Loading pretrained weights from {args.student_pretrained_weights}""" ) snake_case__ = student_model_class.from_pretrained(args.student_pretrained_weights , config=__lowerCAmelCase ) else: snake_case__ = student_model_class(__lowerCAmelCase ) if args.n_gpu > 0: student.to(F"""cuda:{args.local_rank}""" ) logger.info('''Student loaded.''' ) # TEACHER # snake_case__ = teacher_model_class.from_pretrained(args.teacher_name , output_hidden_states=__lowerCAmelCase ) if args.n_gpu > 0: teacher.to(F"""cuda:{args.local_rank}""" ) logger.info(F"""Teacher loaded from {args.teacher_name}.""" ) # FREEZING # if args.freeze_pos_embs: freeze_pos_embeddings(__lowerCAmelCase , __lowerCAmelCase ) if args.freeze_token_type_embds: freeze_token_type_embeddings(__lowerCAmelCase , __lowerCAmelCase ) # SANITY CHECKS # assert student.config.vocab_size == teacher.config.vocab_size assert student.config.hidden_size == teacher.config.hidden_size assert student.config.max_position_embeddings == teacher.config.max_position_embeddings if args.mlm: assert token_probs.size(0 ) == stu_architecture_config.vocab_size # DISTILLER # torch.cuda.empty_cache() snake_case__ = Distiller( params=__lowerCAmelCase , dataset=__lowerCAmelCase , token_probs=__lowerCAmelCase , student=__lowerCAmelCase , teacher=__lowerCAmelCase ) distiller.train() logger.info('''Let\'s go get some drinks.''' ) if __name__ == "__main__": main()
33
import warnings from ...utils import logging from .image_processing_clip import CLIPImageProcessor A_ : int = logging.get_logger(__name__) class _lowerCAmelCase( UpperCAmelCase_ ): """simple docstring""" def __init__( self , *_lowerCamelCase , **_lowerCamelCase ): warnings.warn( 'The class CLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use CLIPImageProcessor instead.' , _lowerCamelCase , ) super().__init__(*_lowerCamelCase , **_lowerCamelCase )
57
0
"""simple docstring""" import gc import random import unittest import torch from diffusers import ( IFImgaImgPipeline, IFImgaImgSuperResolutionPipeline, IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, IFPipeline, IFSuperResolutionPipeline, ) from diffusers.models.attention_processor import AttnAddedKVProcessor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import floats_tensor, load_numpy, require_torch_gpu, skip_mps, slow, torch_device from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference from . import IFPipelineTesterMixin @skip_mps class snake_case_ ( lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): """simple docstring""" A_ = IFPipeline A_ = TEXT_TO_IMAGE_PARAMS - {'''width''', '''height''', '''latents'''} A_ = TEXT_TO_IMAGE_BATCH_PARAMS A_ = PipelineTesterMixin.required_optional_params - {'''latents'''} def UpperCAmelCase__ ( self) -> Optional[int]: return self._get_dummy_components() def UpperCAmelCase__ ( self , lowerCamelCase_ , lowerCamelCase_=0) -> Optional[int]: if str(lowerCamelCase_).startswith('''mps'''): UpperCamelCase = torch.manual_seed(lowerCamelCase_) else: UpperCamelCase = torch.Generator(device=lowerCamelCase_).manual_seed(lowerCamelCase_) UpperCamelCase = { '''prompt''': '''A painting of a squirrel eating a burger''', '''generator''': generator, '''num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs def UpperCAmelCase__ ( self) -> Optional[Any]: self._test_save_load_optional_components() @unittest.skipIf(torch_device != '''cuda''' , reason='''float16 requires CUDA''') def UpperCAmelCase__ ( self) -> Tuple: # Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder super().test_save_load_floataa(expected_max_diff=1e-1) def UpperCAmelCase__ ( self) -> Optional[int]: self._test_attention_slicing_forward_pass(expected_max_diff=1e-2) def UpperCAmelCase__ ( self) -> List[Any]: self._test_save_load_local() def UpperCAmelCase__ ( self) -> Any: self._test_inference_batch_single_identical( expected_max_diff=1e-2 , ) @unittest.skipIf( torch_device != '''cuda''' or not is_xformers_available() , reason='''XFormers attention is only available with CUDA and `xformers` installed''' , ) def UpperCAmelCase__ ( self) -> List[Any]: self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3) @slow @require_torch_gpu class snake_case_ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self) -> Any: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase__ ( self) -> int: # if UpperCamelCase = IFPipeline.from_pretrained('''DeepFloyd/IF-I-XL-v1.0''' , variant='''fp16''' , torch_dtype=torch.floataa) UpperCamelCase = IFSuperResolutionPipeline.from_pretrained( '''DeepFloyd/IF-II-L-v1.0''' , variant='''fp16''' , torch_dtype=torch.floataa , text_encoder=lowerCamelCase_ , tokenizer=lowerCamelCase_) # pre compute text embeddings and remove T5 to save memory pipe_a.text_encoder.to('''cuda''') UpperCamelCase , UpperCamelCase = pipe_a.encode_prompt('''anime turtle''' , device='''cuda''') del pipe_a.tokenizer del pipe_a.text_encoder gc.collect() UpperCamelCase = None UpperCamelCase = None pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()) self._test_if(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # img2img UpperCamelCase = IFImgaImgPipeline(**pipe_a.components) UpperCamelCase = IFImgaImgSuperResolutionPipeline(**pipe_a.components) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()) self._test_if_imgaimg(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # inpainting UpperCamelCase = IFInpaintingPipeline(**pipe_a.components) UpperCamelCase = IFInpaintingSuperResolutionPipeline(**pipe_a.components) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()) self._test_if_inpainting(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_) def UpperCAmelCase__ ( self , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_) -> Tuple: # pipeline 1 _start_torch_memory_measurement() UpperCamelCase = torch.Generator(device='''cpu''').manual_seed(0) UpperCamelCase = pipe_a( prompt_embeds=lowerCamelCase_ , negative_prompt_embeds=lowerCamelCase_ , num_inference_steps=2 , generator=lowerCamelCase_ , output_type='''np''' , ) UpperCamelCase = output.images[0] assert image.shape == (6_4, 6_4, 3) UpperCamelCase = torch.cuda.max_memory_allocated() assert mem_bytes < 1_3 * 1_0**9 UpperCamelCase = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if.npy''') assert_mean_pixel_difference(lowerCamelCase_ , lowerCamelCase_) # pipeline 2 _start_torch_memory_measurement() UpperCamelCase = torch.Generator(device='''cpu''').manual_seed(0) UpperCamelCase = floats_tensor((1, 3, 6_4, 6_4) , rng=random.Random(0)).to(lowerCamelCase_) UpperCamelCase = pipe_a( prompt_embeds=lowerCamelCase_ , negative_prompt_embeds=lowerCamelCase_ , image=lowerCamelCase_ , generator=lowerCamelCase_ , num_inference_steps=2 , output_type='''np''' , ) UpperCamelCase = output.images[0] assert image.shape == (2_5_6, 2_5_6, 3) UpperCamelCase = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 1_0**9 UpperCamelCase = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_superresolution_stage_II.npy''') assert_mean_pixel_difference(lowerCamelCase_ , lowerCamelCase_) def UpperCAmelCase__ ( self , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_) -> Tuple: # pipeline 1 _start_torch_memory_measurement() UpperCamelCase = floats_tensor((1, 3, 6_4, 6_4) , rng=random.Random(0)).to(lowerCamelCase_) UpperCamelCase = torch.Generator(device='''cpu''').manual_seed(0) UpperCamelCase = pipe_a( prompt_embeds=lowerCamelCase_ , negative_prompt_embeds=lowerCamelCase_ , image=lowerCamelCase_ , num_inference_steps=2 , generator=lowerCamelCase_ , output_type='''np''' , ) UpperCamelCase = output.images[0] assert image.shape == (6_4, 6_4, 3) UpperCamelCase = torch.cuda.max_memory_allocated() assert mem_bytes < 1_0 * 1_0**9 UpperCamelCase = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img.npy''') assert_mean_pixel_difference(lowerCamelCase_ , lowerCamelCase_) # pipeline 2 _start_torch_memory_measurement() UpperCamelCase = torch.Generator(device='''cpu''').manual_seed(0) UpperCamelCase = floats_tensor((1, 3, 2_5_6, 2_5_6) , rng=random.Random(0)).to(lowerCamelCase_) UpperCamelCase = floats_tensor((1, 3, 6_4, 6_4) , rng=random.Random(0)).to(lowerCamelCase_) UpperCamelCase = pipe_a( prompt_embeds=lowerCamelCase_ , negative_prompt_embeds=lowerCamelCase_ , image=lowerCamelCase_ , original_image=lowerCamelCase_ , generator=lowerCamelCase_ , num_inference_steps=2 , output_type='''np''' , ) UpperCamelCase = output.images[0] assert image.shape == (2_5_6, 2_5_6, 3) UpperCamelCase = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 1_0**9 UpperCamelCase = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img_superresolution_stage_II.npy''') assert_mean_pixel_difference(lowerCamelCase_ , lowerCamelCase_) def UpperCAmelCase__ ( self , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_) -> int: # pipeline 1 _start_torch_memory_measurement() UpperCamelCase = floats_tensor((1, 3, 6_4, 6_4) , rng=random.Random(0)).to(lowerCamelCase_) UpperCamelCase = floats_tensor((1, 3, 6_4, 6_4) , rng=random.Random(1)).to(lowerCamelCase_) UpperCamelCase = torch.Generator(device='''cpu''').manual_seed(0) UpperCamelCase = pipe_a( prompt_embeds=lowerCamelCase_ , negative_prompt_embeds=lowerCamelCase_ , image=lowerCamelCase_ , mask_image=lowerCamelCase_ , num_inference_steps=2 , generator=lowerCamelCase_ , output_type='''np''' , ) UpperCamelCase = output.images[0] assert image.shape == (6_4, 6_4, 3) UpperCamelCase = torch.cuda.max_memory_allocated() assert mem_bytes < 1_0 * 1_0**9 UpperCamelCase = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting.npy''') assert_mean_pixel_difference(lowerCamelCase_ , lowerCamelCase_) # pipeline 2 _start_torch_memory_measurement() UpperCamelCase = torch.Generator(device='''cpu''').manual_seed(0) UpperCamelCase = floats_tensor((1, 3, 6_4, 6_4) , rng=random.Random(0)).to(lowerCamelCase_) UpperCamelCase = floats_tensor((1, 3, 2_5_6, 2_5_6) , rng=random.Random(0)).to(lowerCamelCase_) UpperCamelCase = floats_tensor((1, 3, 2_5_6, 2_5_6) , rng=random.Random(1)).to(lowerCamelCase_) UpperCamelCase = pipe_a( prompt_embeds=lowerCamelCase_ , negative_prompt_embeds=lowerCamelCase_ , image=lowerCamelCase_ , mask_image=lowerCamelCase_ , original_image=lowerCamelCase_ , generator=lowerCamelCase_ , num_inference_steps=2 , output_type='''np''' , ) UpperCamelCase = output.images[0] assert image.shape == (2_5_6, 2_5_6, 3) UpperCamelCase = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 1_0**9 UpperCamelCase = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting_superresolution_stage_II.npy''') assert_mean_pixel_difference(lowerCamelCase_ , lowerCamelCase_) def __snake_case ( ): """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats()
34
import math from typing import Any, Callable, List, Optional, Tuple, Union import numpy as np import torch from ...models import TaFilmDecoder from ...schedulers import DDPMScheduler from ...utils import is_onnx_available, logging, randn_tensor if is_onnx_available(): from ..onnx_utils import OnnxRuntimeModel from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline from .continous_encoder import SpectrogramContEncoder from .notes_encoder import SpectrogramNotesEncoder A_ : List[Any] = logging.get_logger(__name__) # pylint: disable=invalid-name A_ : Optional[int] = 256 class _lowerCAmelCase( UpperCAmelCase_ ): """simple docstring""" a : Union[str, Any] =['''melgan'''] def __init__( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , ): super().__init__() # From MELGAN UpperCamelCase_: Any = math.log(1e-5 ) # Matches MelGAN training. UpperCamelCase_: List[Any] = 4.0 # Largest value for most examples UpperCamelCase_: Tuple = 1_2_8 self.register_modules( notes_encoder=_lowerCamelCase , continuous_encoder=_lowerCamelCase , decoder=_lowerCamelCase , scheduler=_lowerCamelCase , melgan=_lowerCamelCase , ) def _a ( self , _lowerCamelCase , _lowerCamelCase=(-1.0, 1.0) , _lowerCamelCase=False ): UpperCamelCase_ ,UpperCamelCase_: Union[str, Any] = output_range if clip: UpperCamelCase_: int = torch.clip(_lowerCamelCase , self.min_value , self.max_value ) # Scale to [0, 1]. UpperCamelCase_: List[Any] = (features - self.min_value) / (self.max_value - self.min_value) # Scale to [min_out, max_out]. return zero_one * (max_out - min_out) + min_out def _a ( self , _lowerCamelCase , _lowerCamelCase=(-1.0, 1.0) , _lowerCamelCase=False ): UpperCamelCase_ ,UpperCamelCase_: Dict = input_range UpperCamelCase_: List[str] = torch.clip(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) if clip else outputs # Scale to [0, 1]. UpperCamelCase_: Optional[Any] = (outputs - min_out) / (max_out - min_out) # Scale to [self.min_value, self.max_value]. return zero_one * (self.max_value - self.min_value) + self.min_value def _a ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: str = input_tokens > 0 UpperCamelCase_ ,UpperCamelCase_: Tuple = self.notes_encoder( encoder_input_tokens=_lowerCamelCase , encoder_inputs_mask=_lowerCamelCase ) UpperCamelCase_ ,UpperCamelCase_: Any = self.continuous_encoder( encoder_inputs=_lowerCamelCase , encoder_inputs_mask=_lowerCamelCase ) return [(tokens_encoded, tokens_mask), (continuous_encoded, continuous_mask)] def _a ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: Dict = noise_time if not torch.is_tensor(_lowerCamelCase ): UpperCamelCase_: List[str] = torch.tensor([timesteps] , dtype=torch.long , device=input_tokens.device ) elif torch.is_tensor(_lowerCamelCase ) and len(timesteps.shape ) == 0: UpperCamelCase_: Dict = timesteps[None].to(input_tokens.device ) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML UpperCamelCase_: Union[str, Any] = timesteps * torch.ones(input_tokens.shape[0] , dtype=timesteps.dtype , device=timesteps.device ) UpperCamelCase_: Any = self.decoder( encodings_and_masks=_lowerCamelCase , decoder_input_tokens=_lowerCamelCase , decoder_noise_time=_lowerCamelCase ) return logits @torch.no_grad() def __call__( self , _lowerCamelCase , _lowerCamelCase = None , _lowerCamelCase = 1_0_0 , _lowerCamelCase = True , _lowerCamelCase = "numpy" , _lowerCamelCase = None , _lowerCamelCase = 1 , ): if (callback_steps is None) or ( callback_steps is not None and (not isinstance(_lowerCamelCase , _lowerCamelCase ) or callback_steps <= 0) ): raise ValueError( f'''`callback_steps` has to be a positive integer but is {callback_steps} of type''' f''' {type(_lowerCamelCase )}.''' ) UpperCamelCase_: List[str] = np.zeros([1, TARGET_FEATURE_LENGTH, self.n_dims] , dtype=np.floataa ) UpperCamelCase_: str = np.zeros([1, 0, self.n_dims] , np.floataa ) UpperCamelCase_: Dict = torch.ones((1, TARGET_FEATURE_LENGTH) , dtype=_lowerCamelCase , device=self.device ) for i, encoder_input_tokens in enumerate(_lowerCamelCase ): if i == 0: UpperCamelCase_: str = torch.from_numpy(pred_mel[:1].copy() ).to( device=self.device , dtype=self.decoder.dtype ) # The first chunk has no previous context. UpperCamelCase_: Tuple = torch.zeros((1, TARGET_FEATURE_LENGTH) , dtype=_lowerCamelCase , device=self.device ) else: # The full song pipeline does not feed in a context feature, so the mask # will be all 0s after the feature converter. Because we know we're # feeding in a full context chunk from the previous prediction, set it # to all 1s. UpperCamelCase_: Any = ones UpperCamelCase_: str = self.scale_features( _lowerCamelCase , output_range=[-1.0, 1.0] , clip=_lowerCamelCase ) UpperCamelCase_: Union[str, Any] = self.encode( input_tokens=torch.IntTensor([encoder_input_tokens] ).to(device=self.device ) , continuous_inputs=_lowerCamelCase , continuous_mask=_lowerCamelCase , ) # Sample encoder_continuous_inputs shaped gaussian noise to begin loop UpperCamelCase_: List[str] = randn_tensor( shape=encoder_continuous_inputs.shape , generator=_lowerCamelCase , device=self.device , dtype=self.decoder.dtype , ) # set step values self.scheduler.set_timesteps(_lowerCamelCase ) # Denoising diffusion loop for j, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): UpperCamelCase_: int = self.decode( encodings_and_masks=_lowerCamelCase , input_tokens=_lowerCamelCase , noise_time=t / self.scheduler.config.num_train_timesteps , ) # Compute previous output: x_t -> x_t-1 UpperCamelCase_: Tuple = self.scheduler.step(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , generator=_lowerCamelCase ).prev_sample UpperCamelCase_: List[Any] = self.scale_to_features(_lowerCamelCase , input_range=[-1.0, 1.0] ) UpperCamelCase_: Any = mel[:1] UpperCamelCase_: List[str] = mel.cpu().float().numpy() UpperCamelCase_: Tuple = np.concatenate([full_pred_mel, pred_mel[:1]] , axis=1 ) # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(_lowerCamelCase , _lowerCamelCase ) logger.info('Generated segment' , _lowerCamelCase ) if output_type == "numpy" and not is_onnx_available(): raise ValueError( 'Cannot return output in \'np\' format if ONNX is not available. Make sure to have ONNX installed or set \'output_type\' to \'mel\'.' ) elif output_type == "numpy" and self.melgan is None: raise ValueError( 'Cannot return output in \'np\' format if melgan component is not defined. Make sure to define `self.melgan` or set \'output_type\' to \'mel\'.' ) if output_type == "numpy": UpperCamelCase_: int = self.melgan(input_features=full_pred_mel.astype(np.floataa ) ) else: UpperCamelCase_: int = full_pred_mel if not return_dict: return (output,) return AudioPipelineOutput(audios=_lowerCamelCase )
57
0
def a ( A__ , A__ , A__ , A__ , A__ , ) -> float: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = [redshift, radiation_density, matter_density, dark_energy] if any(p < 0 for p in parameters ): raise ValueError('''All input parameters must be positive''' ) if any(p > 1 for p in parameters[1:4] ): raise ValueError('''Relative densities cannot be greater than one''' ) else: SCREAMING_SNAKE_CASE__ : Any = 1 - (matter_density + radiation_density + dark_energy) SCREAMING_SNAKE_CASE__ : Optional[int] = ( radiation_density * (redshift + 1) ** 4 + matter_density * (redshift + 1) ** 3 + curvature * (redshift + 1) ** 2 + dark_energy ) SCREAMING_SNAKE_CASE__ : Tuple = hubble_constant * e_a ** (1 / 2) return hubble if __name__ == "__main__": import doctest # run doctest doctest.testmod() # demo LCDM approximation a_ :int = 0.3 print( hubble_parameter( hubble_constant=6_8.3, radiation_density=1e-4, matter_density=matter_density, dark_energy=1 - matter_density, redshift=0, ) )
35
import itertools from dataclasses import dataclass from typing import Any, Callable, Dict, List, Optional, Union import pandas as pd import pyarrow as pa import datasets import datasets.config from datasets.features.features import require_storage_cast from datasets.table import table_cast from datasets.utils.py_utils import Literal A_ : Union[str, Any] = datasets.utils.logging.get_logger(__name__) A_ : Optional[Any] = ['names', 'prefix'] A_ : List[str] = ['warn_bad_lines', 'error_bad_lines', 'mangle_dupe_cols'] A_ : List[Any] = ['encoding_errors', 'on_bad_lines'] A_ : Optional[Any] = ['date_format'] @dataclass class _lowerCAmelCase( datasets.BuilderConfig ): """simple docstring""" a : str ="," a : Optional[str] =None a : Optional[Union[int, List[int], str]] ="infer" a : Optional[List[str]] =None a : Optional[List[str]] =None a : Optional[Union[int, str, List[int], List[str]]] =None a : Optional[Union[List[int], List[str]]] =None a : Optional[str] =None a : bool =True a : Optional[Literal["c", "python", "pyarrow"]] =None a : Dict[Union[int, str], Callable[[Any], Any]] =None a : Optional[list] =None a : Optional[list] =None a : bool =False a : Optional[Union[int, List[int]]] =None a : Optional[int] =None a : Optional[Union[str, List[str]]] =None a : bool =True a : bool =True a : bool =False a : bool =True a : Optional[str] =None a : str ="." a : Optional[str] =None a : str ='"' a : int =0 a : Optional[str] =None a : Optional[str] =None a : Optional[str] =None a : Optional[str] =None a : bool =True a : bool =True a : int =0 a : bool =True a : bool =False a : Optional[str] =None a : int =10000 a : Optional[datasets.Features] =None a : Optional[str] ="strict" a : Literal["error", "warn", "skip"] ="error" a : Optional[str] =None def _a ( self ): if self.delimiter is not None: UpperCamelCase_: Optional[Any] = self.delimiter if self.column_names is not None: UpperCamelCase_: int = self.column_names @property def _a ( self ): UpperCamelCase_: Any = { 'sep': self.sep, 'header': self.header, 'names': self.names, 'index_col': self.index_col, 'usecols': self.usecols, 'prefix': self.prefix, 'mangle_dupe_cols': self.mangle_dupe_cols, 'engine': self.engine, 'converters': self.converters, 'true_values': self.true_values, 'false_values': self.false_values, 'skipinitialspace': self.skipinitialspace, 'skiprows': self.skiprows, 'nrows': self.nrows, 'na_values': self.na_values, 'keep_default_na': self.keep_default_na, 'na_filter': self.na_filter, 'verbose': self.verbose, 'skip_blank_lines': self.skip_blank_lines, 'thousands': self.thousands, 'decimal': self.decimal, 'lineterminator': self.lineterminator, 'quotechar': self.quotechar, 'quoting': self.quoting, 'escapechar': self.escapechar, 'comment': self.comment, 'encoding': self.encoding, 'dialect': self.dialect, 'error_bad_lines': self.error_bad_lines, 'warn_bad_lines': self.warn_bad_lines, 'skipfooter': self.skipfooter, 'doublequote': self.doublequote, 'memory_map': self.memory_map, 'float_precision': self.float_precision, 'chunksize': self.chunksize, 'encoding_errors': self.encoding_errors, 'on_bad_lines': self.on_bad_lines, 'date_format': self.date_format, } # some kwargs must not be passed if they don't have a default value # some others are deprecated and we can also not pass them if they are the default value for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS: if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig() , _lowerCamelCase ): del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 2.0 new arguments if not (datasets.config.PANDAS_VERSION.major >= 2): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 1.3 new arguments if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] return pd_read_csv_kwargs class _lowerCAmelCase( datasets.ArrowBasedBuilder ): """simple docstring""" a : Dict =CsvConfig def _a ( self ): return datasets.DatasetInfo(features=self.config.features ) def _a ( self , _lowerCamelCase ): if not self.config.data_files: raise ValueError(f'''At least one data file must be specified, but got data_files={self.config.data_files}''' ) UpperCamelCase_: Tuple = dl_manager.download_and_extract(self.config.data_files ) if isinstance(_lowerCamelCase , (str, list, tuple) ): UpperCamelCase_: List[Any] = data_files if isinstance(_lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: str = [files] UpperCamelCase_: Tuple = [dl_manager.iter_files(_lowerCamelCase ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'files': files} )] UpperCamelCase_: Tuple = [] for split_name, files in data_files.items(): if isinstance(_lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: Dict = [files] UpperCamelCase_: int = [dl_manager.iter_files(_lowerCamelCase ) for file in files] splits.append(datasets.SplitGenerator(name=_lowerCamelCase , gen_kwargs={'files': files} ) ) return splits def _a ( self , _lowerCamelCase ): if self.config.features is not None: UpperCamelCase_: List[Any] = self.config.features.arrow_schema if all(not require_storage_cast(_lowerCamelCase ) for feature in self.config.features.values() ): # cheaper cast UpperCamelCase_: Optional[int] = pa.Table.from_arrays([pa_table[field.name] for field in schema] , schema=_lowerCamelCase ) else: # more expensive cast; allows str <-> int/float or str to Audio for example UpperCamelCase_: int = table_cast(_lowerCamelCase , _lowerCamelCase ) return pa_table def _a ( self , _lowerCamelCase ): UpperCamelCase_: List[str] = self.config.features.arrow_schema if self.config.features else None # dtype allows reading an int column as str UpperCamelCase_: Dict = ( { name: dtype.to_pandas_dtype() if not require_storage_cast(_lowerCamelCase ) else object for name, dtype, feature in zip(schema.names , schema.types , self.config.features.values() ) } if schema is not None else None ) for file_idx, file in enumerate(itertools.chain.from_iterable(_lowerCamelCase ) ): UpperCamelCase_: Optional[Any] = pd.read_csv(_lowerCamelCase , iterator=_lowerCamelCase , dtype=_lowerCamelCase , **self.config.pd_read_csv_kwargs ) try: for batch_idx, df in enumerate(_lowerCamelCase ): UpperCamelCase_: Union[str, Any] = pa.Table.from_pandas(_lowerCamelCase ) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(_lowerCamelCase ) except ValueError as e: logger.error(f'''Failed to read file \'{file}\' with error {type(_lowerCamelCase )}: {e}''' ) raise
57
0
import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler __lowercase : List[str] = 16 __lowercase : List[str] = 32 def lowercase ( __A : Accelerator , __A : int = 16 , __A : str = "bert-base-cased" ) -> Any: '''simple docstring''' snake_case : Optional[Any] = AutoTokenizer.from_pretrained(__A ) snake_case : Optional[Any] = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(__A : List[Any] ): # max_length=None => use the model max length (it's actually the default) snake_case : List[Any] = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=__A , max_length=__A ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset snake_case : Optional[int] = datasets.map( __A , batched=__A , remove_columns=["""idx""", """sentence1""", """sentence2"""] , load_from_cache_file=__A ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library snake_case : Optional[Any] = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(__A : List[Any] ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(__A , padding="""max_length""" , max_length=128 , return_tensors="""pt""" ) return tokenizer.pad(__A , padding="""longest""" , return_tensors="""pt""" ) # Instantiate dataloaders. snake_case : Dict = DataLoader( tokenized_datasets["""train"""] , shuffle=__A , collate_fn=__A , batch_size=__A ) snake_case : Optional[int] = DataLoader( tokenized_datasets["""validation"""] , shuffle=__A , collate_fn=__A , batch_size=__A ) return train_dataloader, eval_dataloader def lowercase ( __A : Union[str, Any] , __A : Optional[Any] ) -> str: '''simple docstring''' snake_case : List[str] = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs snake_case : str = config["""lr"""] snake_case : int = int(config["""num_epochs"""] ) snake_case : List[Any] = int(config["""seed"""] ) snake_case : Any = int(config["""batch_size"""] ) snake_case : Any = args.model_name_or_path set_seed(__A ) snake_case , snake_case : str = get_dataloaders(__A , __A , __A ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) snake_case : Optional[Any] = AutoModelForSequenceClassification.from_pretrained(__A , return_dict=__A ) # Instantiate optimizer snake_case : Any = ( AdamW if accelerator.state.deepspeed_plugin is None or """optimizer""" not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) snake_case : str = optimizer_cls(params=model.parameters() , lr=__A ) if accelerator.state.deepspeed_plugin is not None: snake_case : List[str] = accelerator.state.deepspeed_plugin.deepspeed_config[ """gradient_accumulation_steps""" ] else: snake_case : Optional[int] = 1 snake_case : int = (len(__A ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): snake_case : Union[str, Any] = get_linear_schedule_with_warmup( optimizer=__A , num_warmup_steps=0 , num_training_steps=__A , ) else: snake_case : Union[str, Any] = DummyScheduler(__A , total_num_steps=__A , warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. snake_case , snake_case , snake_case , snake_case , snake_case : Optional[Any] = accelerator.prepare( __A , __A , __A , __A , __A ) # We need to keep track of how many total steps we have iterated over snake_case : Dict = 0 # We also need to keep track of the stating epoch so files are named properly snake_case : int = 0 # Now we train the model snake_case : Union[str, Any] = evaluate.load("""glue""" , """mrpc""" ) snake_case : List[str] = 0 snake_case : Dict = {} for epoch in range(__A , __A ): model.train() for step, batch in enumerate(__A ): snake_case : int = model(**__A ) snake_case : Optional[Any] = outputs.loss snake_case : List[str] = loss / gradient_accumulation_steps accelerator.backward(__A ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 model.eval() snake_case : Tuple = 0 for step, batch in enumerate(__A ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): snake_case : int = model(**__A ) snake_case : List[Any] = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times snake_case , snake_case : Union[str, Any] = accelerator.gather( (predictions, batch["""labels"""]) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(__A ) - 1: snake_case : List[Any] = predictions[: len(eval_dataloader.dataset ) - samples_seen] snake_case : Any = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=__A , references=__A , ) snake_case : List[str] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"""epoch {epoch}:""" , __A ) snake_case : Any = eval_metric["""accuracy"""] if best_performance < eval_metric["accuracy"]: snake_case : Union[str, Any] = eval_metric["""accuracy"""] if args.performance_lower_bound is not None: assert ( args.performance_lower_bound <= best_performance ), f"""Best performance metric {best_performance} is lower than the lower bound {args.performance_lower_bound}""" accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , """all_results.json""" ) , """w""" ) as f: json.dump(__A , __A ) def lowercase ( ) -> List[Any]: '''simple docstring''' snake_case : Optional[int] = argparse.ArgumentParser(description="""Simple example of training script tracking peak GPU memory usage.""" ) parser.add_argument( """--model_name_or_path""" , type=__A , default="""bert-base-cased""" , help="""Path to pretrained model or model identifier from huggingface.co/models.""" , required=__A , ) parser.add_argument( """--output_dir""" , type=__A , default=""".""" , help="""Optional save directory where all checkpoint folders will be stored. Default is the current working directory.""" , ) parser.add_argument( """--performance_lower_bound""" , type=__A , default=__A , help="""Optional lower bound for the performance metric. If set, the training will throw error when the performance metric drops below this value.""" , ) parser.add_argument( """--num_epochs""" , type=__A , default=3 , help="""Number of train epochs.""" , ) snake_case : List[str] = parser.parse_args() snake_case : str = {"""lr""": 2E-5, """num_epochs""": args.num_epochs, """seed""": 42, """batch_size""": 16} training_function(__A , __A ) if __name__ == "__main__": main()
36
from ...configuration_utils import PretrainedConfig from ...utils import logging A_ : str = logging.get_logger(__name__) A_ : Union[str, Any] = { 's-JoL/Open-Llama-V1': 'https://huggingface.co/s-JoL/Open-Llama-V1/blob/main/config.json', } class _lowerCAmelCase( UpperCAmelCase_ ): """simple docstring""" a : Tuple ='''open-llama''' def __init__( self , _lowerCamelCase=1_0_0_0_0_0 , _lowerCamelCase=4_0_9_6 , _lowerCamelCase=1_1_0_0_8 , _lowerCamelCase=3_2 , _lowerCamelCase=3_2 , _lowerCamelCase="silu" , _lowerCamelCase=2_0_4_8 , _lowerCamelCase=0.0_2 , _lowerCamelCase=1e-6 , _lowerCamelCase=True , _lowerCamelCase=0 , _lowerCamelCase=1 , _lowerCamelCase=2 , _lowerCamelCase=False , _lowerCamelCase=True , _lowerCamelCase=0.1 , _lowerCamelCase=0.1 , _lowerCamelCase=True , _lowerCamelCase=True , _lowerCamelCase=None , **_lowerCamelCase , ): UpperCamelCase_: int = vocab_size UpperCamelCase_: List[Any] = max_position_embeddings UpperCamelCase_: Dict = hidden_size UpperCamelCase_: Dict = intermediate_size UpperCamelCase_: Union[str, Any] = num_hidden_layers UpperCamelCase_: Dict = num_attention_heads UpperCamelCase_: Union[str, Any] = hidden_act UpperCamelCase_: Union[str, Any] = initializer_range UpperCamelCase_: List[Any] = rms_norm_eps UpperCamelCase_: Union[str, Any] = use_cache UpperCamelCase_: Dict = kwargs.pop( 'use_memorry_efficient_attention' , _lowerCamelCase ) UpperCamelCase_: Union[str, Any] = hidden_dropout_prob UpperCamelCase_: Any = attention_dropout_prob UpperCamelCase_: int = use_stable_embedding UpperCamelCase_: Tuple = shared_input_output_embedding UpperCamelCase_: str = rope_scaling self._rope_scaling_validation() super().__init__( pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , tie_word_embeddings=_lowerCamelCase , **_lowerCamelCase , ) def _a ( self ): if self.rope_scaling is None: return if not isinstance(self.rope_scaling , _lowerCamelCase ) or len(self.rope_scaling ) != 2: raise ValueError( '`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, ' f'''got {self.rope_scaling}''' ) UpperCamelCase_: str = self.rope_scaling.get('type' , _lowerCamelCase ) UpperCamelCase_: int = self.rope_scaling.get('factor' , _lowerCamelCase ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( f'''`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}''' ) if rope_scaling_factor is None or not isinstance(_lowerCamelCase , _lowerCamelCase ) or rope_scaling_factor <= 1.0: raise ValueError(f'''`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}''' )
57
0
import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ConvNextConfig, SegformerImageProcessor, UperNetConfig, UperNetForSemanticSegmentation def UpperCamelCase_ ( __a ) -> Tuple: a__ : Optional[Any] = 384 if "tiny" in model_name: a__ : Optional[int] = [3, 3, 9, 3] a__ : Optional[int] = [96, 192, 384, 768] if "small" in model_name: a__ : Optional[Any] = [3, 3, 27, 3] a__ : str = [96, 192, 384, 768] if "base" in model_name: a__ : Union[str, Any] = [3, 3, 27, 3] a__ : Any = [128, 256, 512, 1_024] a__ : Tuple = 512 if "large" in model_name: a__ : List[str] = [3, 3, 27, 3] a__ : List[str] = [192, 384, 768, 1_536] a__ : int = 768 if "xlarge" in model_name: a__ : Any = [3, 3, 27, 3] a__ : int = [256, 512, 1_024, 2_048] a__ : Optional[int] = 1_024 # set label information a__ : List[Any] = 150 a__ : Optional[Any] = "huggingface/label-files" a__ : Dict = "ade20k-id2label.json" a__ : List[Any] = json.load(open(hf_hub_download(__a , __a , repo_type="dataset" ) , "r" ) ) a__ : Optional[int] = {int(__a ): v for k, v in idalabel.items()} a__ : Dict = {v: k for k, v in idalabel.items()} a__ : str = ConvNextConfig( depths=__a , hidden_sizes=__a , out_features=["stage1", "stage2", "stage3", "stage4"] ) a__ : List[str] = UperNetConfig( backbone_config=__a , auxiliary_in_channels=__a , num_labels=__a , idalabel=__a , labelaid=__a , ) return config def UpperCamelCase_ ( __a ) -> Union[str, Any]: a__ : Optional[int] = [] # fmt: off # stem rename_keys.append(("backbone.downsample_layers.0.0.weight", "backbone.embeddings.patch_embeddings.weight") ) rename_keys.append(("backbone.downsample_layers.0.0.bias", "backbone.embeddings.patch_embeddings.bias") ) rename_keys.append(("backbone.downsample_layers.0.1.weight", "backbone.embeddings.layernorm.weight") ) rename_keys.append(("backbone.downsample_layers.0.1.bias", "backbone.embeddings.layernorm.bias") ) # stages for i in range(len(config.backbone_config.depths ) ): for j in range(config.backbone_config.depths[i] ): rename_keys.append((f'''backbone.stages.{i}.{j}.gamma''', f'''backbone.encoder.stages.{i}.layers.{j}.layer_scale_parameter''') ) rename_keys.append((f'''backbone.stages.{i}.{j}.depthwise_conv.weight''', f'''backbone.encoder.stages.{i}.layers.{j}.dwconv.weight''') ) rename_keys.append((f'''backbone.stages.{i}.{j}.depthwise_conv.bias''', f'''backbone.encoder.stages.{i}.layers.{j}.dwconv.bias''') ) rename_keys.append((f'''backbone.stages.{i}.{j}.norm.weight''', f'''backbone.encoder.stages.{i}.layers.{j}.layernorm.weight''') ) rename_keys.append((f'''backbone.stages.{i}.{j}.norm.bias''', f'''backbone.encoder.stages.{i}.layers.{j}.layernorm.bias''') ) rename_keys.append((f'''backbone.stages.{i}.{j}.pointwise_conv1.weight''', f'''backbone.encoder.stages.{i}.layers.{j}.pwconv1.weight''') ) rename_keys.append((f'''backbone.stages.{i}.{j}.pointwise_conv1.bias''', f'''backbone.encoder.stages.{i}.layers.{j}.pwconv1.bias''') ) rename_keys.append((f'''backbone.stages.{i}.{j}.pointwise_conv2.weight''', f'''backbone.encoder.stages.{i}.layers.{j}.pwconv2.weight''') ) rename_keys.append((f'''backbone.stages.{i}.{j}.pointwise_conv2.bias''', f'''backbone.encoder.stages.{i}.layers.{j}.pwconv2.bias''') ) if i > 0: rename_keys.append((f'''backbone.downsample_layers.{i}.0.weight''', f'''backbone.encoder.stages.{i}.downsampling_layer.0.weight''') ) rename_keys.append((f'''backbone.downsample_layers.{i}.0.bias''', f'''backbone.encoder.stages.{i}.downsampling_layer.0.bias''') ) rename_keys.append((f'''backbone.downsample_layers.{i}.1.weight''', f'''backbone.encoder.stages.{i}.downsampling_layer.1.weight''') ) rename_keys.append((f'''backbone.downsample_layers.{i}.1.bias''', f'''backbone.encoder.stages.{i}.downsampling_layer.1.bias''') ) rename_keys.append((f'''backbone.norm{i}.weight''', f'''backbone.hidden_states_norms.stage{i+1}.weight''') ) rename_keys.append((f'''backbone.norm{i}.bias''', f'''backbone.hidden_states_norms.stage{i+1}.bias''') ) # decode head rename_keys.extend( [ ("decode_head.conv_seg.weight", "decode_head.classifier.weight"), ("decode_head.conv_seg.bias", "decode_head.classifier.bias"), ("auxiliary_head.conv_seg.weight", "auxiliary_head.classifier.weight"), ("auxiliary_head.conv_seg.bias", "auxiliary_head.classifier.bias"), ] ) # fmt: on return rename_keys def UpperCamelCase_ ( __a , __a , __a ) -> List[str]: a__ : str = dct.pop(__a ) a__ : List[Any] = val def UpperCamelCase_ ( __a , __a , __a ) -> str: a__ : Union[str, Any] = { "upernet-convnext-tiny": "https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_tiny_fp16_512x512_160k_ade20k/upernet_convnext_tiny_fp16_512x512_160k_ade20k_20220227_124553-cad485de.pth", "upernet-convnext-small": "https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_small_fp16_512x512_160k_ade20k/upernet_convnext_small_fp16_512x512_160k_ade20k_20220227_131208-1b1e394f.pth", "upernet-convnext-base": "https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_base_fp16_512x512_160k_ade20k/upernet_convnext_base_fp16_512x512_160k_ade20k_20220227_181227-02a24fc6.pth", "upernet-convnext-large": "https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_large_fp16_640x640_160k_ade20k/upernet_convnext_large_fp16_640x640_160k_ade20k_20220226_040532-e57aa54d.pth", "upernet-convnext-xlarge": "https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_xlarge_fp16_640x640_160k_ade20k/upernet_convnext_xlarge_fp16_640x640_160k_ade20k_20220226_080344-95fc38c2.pth", } a__ : Tuple = model_name_to_url[model_name] a__ : List[Any] = torch.hub.load_state_dict_from_url(__a , map_location="cpu" )["state_dict"] a__ : List[Any] = get_upernet_config(__a ) a__ : Dict = UperNetForSemanticSegmentation(__a ) model.eval() # replace "bn" => "batch_norm" for key in state_dict.copy().keys(): a__ : Tuple = state_dict.pop(__a ) if "bn" in key: a__ : List[Any] = key.replace("bn" , "batch_norm" ) a__ : Dict = val # rename keys a__ : str = create_rename_keys(__a ) for src, dest in rename_keys: rename_key(__a , __a , __a ) model.load_state_dict(__a ) # verify on image a__ : Optional[Any] = "https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg" a__ : int = Image.open(requests.get(__a , stream=__a ).raw ).convert("RGB" ) a__ : Union[str, Any] = SegformerImageProcessor() a__ : Dict = processor(__a , return_tensors="pt" ).pixel_values with torch.no_grad(): a__ : Optional[int] = model(__a ) if model_name == "upernet-convnext-tiny": a__ : Tuple = torch.tensor( [[-8.8110, -8.8110, -8.6521], [-8.8110, -8.8110, -8.6521], [-8.7746, -8.7746, -8.6130]] ) elif model_name == "upernet-convnext-small": a__ : str = torch.tensor( [[-8.8236, -8.8236, -8.6771], [-8.8236, -8.8236, -8.6771], [-8.7638, -8.7638, -8.6240]] ) elif model_name == "upernet-convnext-base": a__ : List[str] = torch.tensor( [[-8.8558, -8.8558, -8.6905], [-8.8558, -8.8558, -8.6905], [-8.7669, -8.7669, -8.6021]] ) elif model_name == "upernet-convnext-large": a__ : Dict = torch.tensor( [[-8.6660, -8.6660, -8.6210], [-8.6660, -8.6660, -8.6210], [-8.6310, -8.6310, -8.5964]] ) elif model_name == "upernet-convnext-xlarge": a__ : Optional[Any] = torch.tensor( [[-8.4980, -8.4980, -8.3977], [-8.4980, -8.4980, -8.3977], [-8.4379, -8.4379, -8.3412]] ) print("Logits:" , outputs.logits[0, 0, :3, :3] ) assert torch.allclose(outputs.logits[0, 0, :3, :3] , __a , atol=1e-4 ) print("Looks ok!" ) if pytorch_dump_folder_path is not None: print(f'''Saving model {model_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(__a ) print(f'''Saving processor to {pytorch_dump_folder_path}''' ) processor.save_pretrained(__a ) if push_to_hub: print(f'''Pushing model and processor for {model_name} to hub''' ) model.push_to_hub(f'''openmmlab/{model_name}''' ) processor.push_to_hub(f'''openmmlab/{model_name}''' ) if __name__ == "__main__": UpperCamelCase : int = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default="""upernet-convnext-tiny""", type=str, choices=[f"""upernet-convnext-{size}""" for size in ["""tiny""", """small""", """base""", """large""", """xlarge"""]], help="""Name of the ConvNext UperNet model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model to the 🤗 hub.""" ) UpperCamelCase : Optional[int] = parser.parse_args() convert_upernet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
37
import collections import inspect import unittest from transformers import FocalNetConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( FocalNetBackbone, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetModel, ) from transformers.models.focalnet.modeling_focalnet import FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class _lowerCAmelCase: """simple docstring""" def __init__( self , _lowerCamelCase , _lowerCamelCase=1_3 , _lowerCamelCase=3_2 , _lowerCamelCase=2 , _lowerCamelCase=3 , _lowerCamelCase=1_6 , _lowerCamelCase=[3_2, 6_4, 1_2_8] , _lowerCamelCase=[1, 2, 1] , _lowerCamelCase=[2, 2, 4] , _lowerCamelCase=2 , _lowerCamelCase=2.0 , _lowerCamelCase=True , _lowerCamelCase=0.0 , _lowerCamelCase=0.0 , _lowerCamelCase=0.1 , _lowerCamelCase="gelu" , _lowerCamelCase=False , _lowerCamelCase=True , _lowerCamelCase=0.0_2 , _lowerCamelCase=1e-5 , _lowerCamelCase=True , _lowerCamelCase=None , _lowerCamelCase=True , _lowerCamelCase=1_0 , _lowerCamelCase=8 , _lowerCamelCase=["stage1", "stage2"] , _lowerCamelCase=[1, 2] , ): UpperCamelCase_: Tuple = parent UpperCamelCase_: Dict = batch_size UpperCamelCase_: List[str] = image_size UpperCamelCase_: Tuple = patch_size UpperCamelCase_: Tuple = num_channels UpperCamelCase_: Dict = embed_dim UpperCamelCase_: List[Any] = hidden_sizes UpperCamelCase_: List[str] = depths UpperCamelCase_: List[str] = num_heads UpperCamelCase_: Optional[int] = window_size UpperCamelCase_: Tuple = mlp_ratio UpperCamelCase_: Dict = qkv_bias UpperCamelCase_: str = hidden_dropout_prob UpperCamelCase_: Optional[Any] = attention_probs_dropout_prob UpperCamelCase_: int = drop_path_rate UpperCamelCase_: Dict = hidden_act UpperCamelCase_: List[str] = use_absolute_embeddings UpperCamelCase_: Dict = patch_norm UpperCamelCase_: Optional[Any] = layer_norm_eps UpperCamelCase_: List[str] = initializer_range UpperCamelCase_: List[Any] = is_training UpperCamelCase_: Optional[int] = scope UpperCamelCase_: str = use_labels UpperCamelCase_: List[str] = type_sequence_label_size UpperCamelCase_: Union[str, Any] = encoder_stride UpperCamelCase_: Dict = out_features UpperCamelCase_: str = out_indices def _a ( self ): UpperCamelCase_: int = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase_: List[Any] = None if self.use_labels: UpperCamelCase_: Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase_: Optional[Any] = self.get_config() return config, pixel_values, labels def _a ( self ): return FocalNetConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , hidden_sizes=self.hidden_sizes , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , out_features=self.out_features , out_indices=self.out_indices , ) def _a ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: Optional[int] = FocalNetModel(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() UpperCamelCase_: int = model(_lowerCamelCase ) UpperCamelCase_: int = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) UpperCamelCase_: int = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) ) def _a ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: List[str] = FocalNetBackbone(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() UpperCamelCase_: Optional[int] = model(_lowerCamelCase ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.image_size, 8, 8] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[:-1] ) # verify backbone works with out_features=None UpperCamelCase_: int = None UpperCamelCase_: List[Any] = FocalNetBackbone(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() UpperCamelCase_: Any = model(_lowerCamelCase ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.image_size * 2, 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def _a ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: Tuple = FocalNetForMaskedImageModeling(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() UpperCamelCase_: Any = model(_lowerCamelCase ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images UpperCamelCase_: List[Any] = 1 UpperCamelCase_: Dict = FocalNetForMaskedImageModeling(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() UpperCamelCase_: Optional[int] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) UpperCamelCase_: Union[str, Any] = model(_lowerCamelCase ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def _a ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: Tuple = self.type_sequence_label_size UpperCamelCase_: List[Any] = FocalNetForImageClassification(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() UpperCamelCase_: str = model(_lowerCamelCase , labels=_lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images UpperCamelCase_: Union[str, Any] = 1 UpperCamelCase_: Dict = FocalNetForImageClassification(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() UpperCamelCase_: Dict = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) UpperCamelCase_: Union[str, Any] = model(_lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def _a ( self ): UpperCamelCase_: Dict = self.prepare_config_and_inputs() UpperCamelCase_ ,UpperCamelCase_ ,UpperCamelCase_: List[str] = config_and_inputs UpperCamelCase_: int = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class _lowerCAmelCase( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase ): """simple docstring""" a : Optional[int] =( ( FocalNetModel, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetBackbone, ) if is_torch_available() else () ) a : Any =( {'''feature-extraction''': FocalNetModel, '''image-classification''': FocalNetForImageClassification} if is_torch_available() else {} ) a : Dict =False a : Union[str, Any] =False a : Tuple =False a : Optional[int] =False a : Union[str, Any] =False def _a ( self ): UpperCamelCase_: str = FocalNetModelTester(self ) UpperCamelCase_: Tuple = ConfigTester(self , config_class=_lowerCamelCase , embed_dim=3_7 , has_text_modality=_lowerCamelCase ) def _a ( self ): self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _a ( self ): return def _a ( self ): UpperCamelCase_: Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowerCamelCase ) def _a ( self ): UpperCamelCase_: List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*_lowerCamelCase ) def _a ( self ): UpperCamelCase_: Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*_lowerCamelCase ) def _a ( self ): UpperCamelCase_: Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_lowerCamelCase ) @unittest.skip(reason='FocalNet does not use inputs_embeds' ) def _a ( self ): pass @unittest.skip(reason='FocalNet does not use feedforward chunking' ) def _a ( self ): pass def _a ( self ): UpperCamelCase_ ,UpperCamelCase_: List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes[:-1]: UpperCamelCase_: Union[str, Any] = model_class(_lowerCamelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) UpperCamelCase_: List[str] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_lowerCamelCase , nn.Linear ) ) def _a ( self ): UpperCamelCase_ ,UpperCamelCase_: Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes[:-1]: UpperCamelCase_: List[Any] = model_class(_lowerCamelCase ) UpperCamelCase_: Optional[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase_: Any = [*signature.parameters.keys()] UpperCamelCase_: List[Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] , _lowerCamelCase ) def _a ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: Tuple = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() with torch.no_grad(): UpperCamelCase_: Tuple = model(**self._prepare_for_class(_lowerCamelCase , _lowerCamelCase ) ) UpperCamelCase_: Union[str, Any] = outputs.hidden_states UpperCamelCase_: Tuple = getattr( self.model_tester , 'expected_num_hidden_layers' , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(_lowerCamelCase ) , _lowerCamelCase ) # FocalNet has a different seq_length UpperCamelCase_: Optional[Any] = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) UpperCamelCase_: int = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) UpperCamelCase_: Dict = outputs.reshaped_hidden_states self.assertEqual(len(_lowerCamelCase ) , _lowerCamelCase ) UpperCamelCase_ ,UpperCamelCase_ ,UpperCamelCase_ ,UpperCamelCase_: int = reshaped_hidden_states[0].shape UpperCamelCase_: List[str] = ( reshaped_hidden_states[0].view(_lowerCamelCase , _lowerCamelCase , height * width ).permute(0 , 2 , 1 ) ) self.assertListEqual( list(reshaped_hidden_states.shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def _a ( self ): UpperCamelCase_ ,UpperCamelCase_: Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase_: int = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes[:-1]: UpperCamelCase_: int = True self.check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCamelCase_: Optional[Any] = True self.check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def _a ( self ): UpperCamelCase_ ,UpperCamelCase_: Dict = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase_: str = 3 UpperCamelCase_: Any = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) UpperCamelCase_: int = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) UpperCamelCase_: List[Any] = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) UpperCamelCase_: str = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes[:-1]: UpperCamelCase_: Dict = True self.check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCamelCase_: Optional[Any] = True self.check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , (padded_height, padded_width) ) @slow def _a ( self ): for model_name in FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase_: List[Any] = FocalNetModel.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) def _a ( self ): UpperCamelCase_ ,UpperCamelCase_: Dict = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase_: Dict = _config_zero_init(_lowerCamelCase ) for model_class in self.all_model_classes: UpperCamelCase_: List[str] = model_class(config=_lowerCamelCase ) for name, param in model.named_parameters(): if "embeddings" not in name and param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=f'''Parameter {name} of model {model_class} seems not properly initialized''' , ) @require_vision @require_torch class _lowerCAmelCase( unittest.TestCase ): """simple docstring""" @cached_property def _a ( self ): # TODO update organization return AutoImageProcessor.from_pretrained('microsoft/focalnet-tiny' ) if is_vision_available() else None @slow def _a ( self ): UpperCamelCase_: Optional[int] = FocalNetForImageClassification.from_pretrained('microsoft/focalnet-tiny' ).to(_lowerCamelCase ) UpperCamelCase_: Optional[Any] = self.default_image_processor UpperCamelCase_: str = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) UpperCamelCase_: str = image_processor(images=_lowerCamelCase , return_tensors='pt' ).to(_lowerCamelCase ) # forward pass with torch.no_grad(): UpperCamelCase_: List[str] = model(**_lowerCamelCase ) # verify the logits UpperCamelCase_: Optional[int] = torch.Size((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , _lowerCamelCase ) UpperCamelCase_: Optional[int] = torch.tensor([0.2_1_6_6, -0.4_3_6_8, 0.2_1_9_1] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _lowerCamelCase , atol=1e-4 ) ) self.assertTrue(outputs.logits.argmax(dim=-1 ).item() , 2_8_1 ) @require_torch class _lowerCAmelCase( UpperCAmelCase_ , unittest.TestCase ): """simple docstring""" a : Optional[Any] =(FocalNetBackbone,) if is_torch_available() else () a : List[str] =FocalNetConfig a : List[str] =False def _a ( self ): UpperCamelCase_: Any = FocalNetModelTester(self )
57
0
'''simple docstring''' import argparse import json import os import re import torch from transformers import BloomConfig, BloomModel from transformers.file_utils import CONFIG_NAME, WEIGHTS_NAME from transformers.utils import logging logging.set_verbosity_info() A_ : Optional[int] = [ "word_embeddings_layernorm.weight", "word_embeddings_layernorm.bias", "input_layernorm.weight", "input_layernorm.bias", "post_attention_layernorm.weight", "post_attention_layernorm.bias", "self_attention.dense.bias", "mlp.dense_4h_to_h.bias", "ln_f.weight", "ln_f.bias", ] A_ : Optional[int] = [ "mlp.dense_4h_to_h.weight", "self_attention.dense.weight", ] def UpperCamelCase__ ( __magic_name__ : str , __magic_name__ : Optional[Any] ) -> Tuple: '''simple docstring''' snake_case__ : Optional[Any] = { """word_embeddings.weight""": """word_embeddings.weight""", """word_embeddings.norm.weight""": """word_embeddings_layernorm.weight""", """word_embeddings.norm.bias""": """word_embeddings_layernorm.bias""", """weight""": """ln_f.weight""", """bias""": """ln_f.bias""", } if key in layer_rename_map: return layer_rename_map[key] # Handle transformer blocks snake_case__ : int = int(re.match(R""".*layer_(\d*).*""" , __magic_name__ )[1] ) layer_number -= 3 return f"h.{layer_number}." + key def UpperCamelCase__ ( __magic_name__ : List[str] ) -> Tuple: '''simple docstring''' if dtype == torch.bool: return 1 / 8 snake_case__ : List[Any] = re.search(R"""[^\d](\d+)$""" , str(__magic_name__ ) ) if bit_search is None: raise ValueError(f"`dtype` is not a valid dtype: {dtype}." ) snake_case__ : Optional[Any] = int(bit_search.groups()[0] ) return bit_size // 8 def UpperCamelCase__ ( __magic_name__ : Dict , __magic_name__ : Dict , __magic_name__ : List[Any] , __magic_name__ : Optional[int] , __magic_name__ : Optional[int] ) -> Optional[Any]: '''simple docstring''' if bloom_config_file == "": snake_case__ : Tuple = BloomConfig() else: snake_case__ : str = BloomConfig.from_json_file(__magic_name__ ) if shard_model: snake_case__ : str = os.listdir(__magic_name__ ) snake_case__ : Union[str, Any] = sorted(filter(lambda __magic_name__ : s.startswith("""layer""" ) and "model_00" in s , __magic_name__ ) ) snake_case__ : List[Any] = {"""weight_map""": {}, """metadata""": {}} snake_case__ : Any = 0 snake_case__ : Optional[int] = None snake_case__ : Tuple = BloomConfig() for j, file in enumerate(__magic_name__ ): print("""Processing file: {}""".format(__magic_name__ ) ) snake_case__ : Any = None for i in range(__magic_name__ ): # load all TP files snake_case__ : int = file.replace("""model_00""" , f"model_0{i}" ) snake_case__ : Union[str, Any] = torch.load(os.path.join(__magic_name__ , __magic_name__ ) , map_location="""cpu""" ) # Rename keys in the transformers names snake_case__ : Tuple = list(temp.keys() ) for key in keys: snake_case__ : str = temp.pop(__magic_name__ ) if tensors is None: snake_case__ : List[Any] = temp else: for key in tensors.keys(): if any(key.endswith(__magic_name__ ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ): # We average (sum and then divide) some weights accross TP ranks (see https://github.com/bigscience-workshop/Megatron-DeepSpeed/blob/olruwase/sync_layer_norms/megatron/training.py#L425) tensors[key] += temp[key] else: # Some weights are RowParallelLinear in Megatron-Deepspeed, others are ColumnParallel snake_case__ : str = 1 if any(text in key for text in WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN ) else 0 # We concatenate these weights accross TP ranks snake_case__ : str = torch.cat([tensors[key], temp[key]] , dim=__magic_name__ ) # Divide by the number of TP the weights we want to average for key in tensors.keys(): if any(key.endswith(__magic_name__ ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ): snake_case__ : Tuple = tensors[key] / pretraining_tp torch.save( __magic_name__ , os.path.join( __magic_name__ , """pytorch_model_{}-of-{}.bin""".format(str(j + 1 ).zfill(5 ) , str(len(__magic_name__ ) ).zfill(5 ) ) , ) , ) for key in tensors.keys(): snake_case__ : int = tensors[key] total_size += value.numel() * get_dtype_size(value.dtype ) if key not in index_dict["weight_map"]: snake_case__ : Union[str, Any] = """pytorch_model_{}-of-{}.bin""".format( str(j + 1 ).zfill(5 ) , str(len(__magic_name__ ) ).zfill(5 ) ) snake_case__ : Dict = BloomConfig() snake_case__ : Dict = pytorch_dump_folder_path + """/""" + CONFIG_NAME snake_case__ : int = total_size with open(__magic_name__ , """w""" , encoding="""utf-8""" ) as f: f.write(config.to_json_string() ) with open(os.path.join(__magic_name__ , WEIGHTS_NAME + """.index.json""" ) , """w""" , encoding="""utf-8""" ) as f: snake_case__ : Tuple = json.dumps(__magic_name__ , indent=2 , sort_keys=__magic_name__ ) + """\n""" f.write(__magic_name__ ) else: snake_case__ : Optional[Any] = BloomModel(__magic_name__ ) snake_case__ : Optional[Any] = os.listdir(__magic_name__ ) snake_case__ : Union[str, Any] = sorted(filter(lambda __magic_name__ : s.startswith("""layer""" ) and "model_00" in s , __magic_name__ ) ) snake_case__ : Tuple = None for i, file in enumerate(__magic_name__ ): snake_case__ : Dict = None for i in range(__magic_name__ ): # load all TP files snake_case__ : List[str] = file.replace("""model_00""" , f"model_0{i}" ) snake_case__ : Optional[int] = torch.load(os.path.join(__magic_name__ , __magic_name__ ) , map_location="""cpu""" ) # Rename keys in the transformers names snake_case__ : Optional[int] = list(temp.keys() ) for key in keys: snake_case__ : int = temp.pop(__magic_name__ ) if tensors is None: snake_case__ : str = temp else: for key in tensors.keys(): # We average (sum and then divide) some weights accross TP ranks (see https://github.com/bigscience-workshop/Megatron-DeepSpeed/blob/olruwase/sync_layer_norms/megatron/training.py#L425) if any(key.endswith(__magic_name__ ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ): tensors[key] += temp[key] else: # Some weights are RowParallelLinear in Megatron-Deepspeed, others are ColumnParallel snake_case__ : Optional[int] = 1 if any(text in key for text in WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN ) else 0 # We concatenate these weights accross TP ranks snake_case__ : Tuple = torch.cat([tensors[key], temp[key]] , dim=__magic_name__ ) # Divide by the number of TP the weights we want to average for key in tensors.keys(): if any(key.endswith(__magic_name__ ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ): snake_case__ : str = tensors[key] / pretraining_tp snake_case__ : Any = model.load_state_dict(__magic_name__ , strict=__magic_name__ ) assert not other_keys.unexpected_keys, f"The keys {other_keys.unexpected_keys} are unexpected" if missing_keys is None: snake_case__ : Optional[int] = set(other_keys.missing_keys ) else: snake_case__ : Optional[int] = missing_keys.intersection(set(other_keys.missing_keys ) ) assert not missing_keys, f"The keys {missing_keys} are missing" # Save pytorch-model os.makedirs(__magic_name__ , exist_ok=__magic_name__ ) snake_case__ : Tuple = pytorch_dump_folder_path + """/""" + WEIGHTS_NAME snake_case__ : List[Any] = pytorch_dump_folder_path + """/""" + CONFIG_NAME print(f"Save PyTorch model to {pytorch_weights_dump_path} with dtype {config.torch_dtype}" ) if config.torch_dtype is not None: snake_case__ : int = model.to(config.torch_dtype ) torch.save(model.state_dict() , __magic_name__ ) print(f"Save configuration file to {pytorch_config_dump_path}" ) with open(__magic_name__ , """w""" , encoding="""utf-8""" ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": A_ : Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( "--bloom_checkpoint_path", default=None, type=str, required=True, help="Path to the Megatron-LM checkpoint path.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) parser.add_argument( "--bloom_config_file", default="", type=str, help=( "An optional config json file corresponding to the pre-trained model. \n" "This specifies the model architecture." ), ) parser.add_argument( "--shard_model", action="store_true", help="An optional setting to shard the output model \nThis enables sharding the converted checkpoint", ) parser.add_argument( "--pretraining_tp", default=4, type=int, help="Pretraining TP rank that has been used when training the model in Megatron-LM \n", ) A_ : Optional[int] = parser.parse_args() convert_bloom_checkpoint_to_pytorch( args.bloom_checkpoint_path, args.bloom_config_file, args.pytorch_dump_folder_path, args.shard_model, args.pretraining_tp, )
38
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) A_ : Tuple = { 'configuration_distilbert': [ 'DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'DistilBertConfig', 'DistilBertOnnxConfig', ], 'tokenization_distilbert': ['DistilBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : Optional[Any] = ['DistilBertTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : int = [ 'DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'DistilBertForMaskedLM', 'DistilBertForMultipleChoice', 'DistilBertForQuestionAnswering', 'DistilBertForSequenceClassification', 'DistilBertForTokenClassification', 'DistilBertModel', 'DistilBertPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : List[Any] = [ 'TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFDistilBertForMaskedLM', 'TFDistilBertForMultipleChoice', 'TFDistilBertForQuestionAnswering', 'TFDistilBertForSequenceClassification', 'TFDistilBertForTokenClassification', 'TFDistilBertMainLayer', 'TFDistilBertModel', 'TFDistilBertPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : int = [ 'FlaxDistilBertForMaskedLM', 'FlaxDistilBertForMultipleChoice', 'FlaxDistilBertForQuestionAnswering', 'FlaxDistilBertForSequenceClassification', 'FlaxDistilBertForTokenClassification', 'FlaxDistilBertModel', 'FlaxDistilBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_distilbert import ( DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DistilBertConfig, DistilBertOnnxConfig, ) from .tokenization_distilbert import DistilBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_distilbert_fast import DistilBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_distilbert import ( DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, DistilBertModel, DistilBertPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_distilbert import ( TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDistilBertForMaskedLM, TFDistilBertForMultipleChoice, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertMainLayer, TFDistilBertModel, TFDistilBertPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, FlaxDistilBertPreTrainedModel, ) else: import sys A_ : Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
57
0
from ..utils import DummyObject, requires_backends class snake_case_ ( metaclass=__A ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = ["flax", "transformers"] def __init__( self : Union[str, Any] , *_UpperCamelCase : Optional[int] , **_UpperCamelCase : Dict ) ->int: requires_backends(self , ['''flax''', '''transformers'''] ) @classmethod def snake_case__( cls : Any , *_UpperCamelCase : Optional[Any] , **_UpperCamelCase : str ) ->str: requires_backends(cls , ['''flax''', '''transformers'''] ) @classmethod def snake_case__( cls : Tuple , *_UpperCamelCase : Any , **_UpperCamelCase : Union[str, Any] ) ->Union[str, Any]: requires_backends(cls , ['''flax''', '''transformers'''] ) class snake_case_ ( metaclass=__A ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = ["flax", "transformers"] def __init__( self : Tuple , *_UpperCamelCase : Optional[int] , **_UpperCamelCase : str ) ->Optional[Any]: requires_backends(self , ['''flax''', '''transformers'''] ) @classmethod def snake_case__( cls : str , *_UpperCamelCase : Any , **_UpperCamelCase : Any ) ->str: requires_backends(cls , ['''flax''', '''transformers'''] ) @classmethod def snake_case__( cls : Optional[int] , *_UpperCamelCase : int , **_UpperCamelCase : Optional[int] ) ->int: requires_backends(cls , ['''flax''', '''transformers'''] ) class snake_case_ ( metaclass=__A ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = ["flax", "transformers"] def __init__( self : Optional[Any] , *_UpperCamelCase : Dict , **_UpperCamelCase : Union[str, Any] ) ->str: requires_backends(self , ['''flax''', '''transformers'''] ) @classmethod def snake_case__( cls : Dict , *_UpperCamelCase : str , **_UpperCamelCase : str ) ->int: requires_backends(cls , ['''flax''', '''transformers'''] ) @classmethod def snake_case__( cls : List[Any] , *_UpperCamelCase : Tuple , **_UpperCamelCase : int ) ->Tuple: requires_backends(cls , ['''flax''', '''transformers'''] ) class snake_case_ ( metaclass=__A ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = ["flax", "transformers"] def __init__( self : Tuple , *_UpperCamelCase : str , **_UpperCamelCase : Any ) ->Union[str, Any]: requires_backends(self , ['''flax''', '''transformers'''] ) @classmethod def snake_case__( cls : List[str] , *_UpperCamelCase : Dict , **_UpperCamelCase : List[Any] ) ->Any: requires_backends(cls , ['''flax''', '''transformers'''] ) @classmethod def snake_case__( cls : str , *_UpperCamelCase : Optional[int] , **_UpperCamelCase : str ) ->str: requires_backends(cls , ['''flax''', '''transformers'''] )
39
import os import socket from contextlib import contextmanager import torch from ..commands.config.default import write_basic_config # noqa: F401 from ..state import PartialState from .dataclasses import DistributedType from .imports import is_deepspeed_available, is_tpu_available from .transformer_engine import convert_model from .versions import is_torch_version if is_deepspeed_available(): from deepspeed import DeepSpeedEngine if is_tpu_available(check_device=False): import torch_xla.core.xla_model as xm def snake_case (UpperCAmelCase__ ) -> Union[str, Any]: if is_torch_version('<' , '2.0.0' ) or not hasattr(UpperCAmelCase__ , '_dynamo' ): return False return isinstance(UpperCAmelCase__ , torch._dynamo.eval_frame.OptimizedModule ) def snake_case (UpperCAmelCase__ , UpperCAmelCase__ = True ) -> Any: UpperCamelCase_: Optional[Any] = (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel) UpperCamelCase_: int = is_compiled_module(UpperCAmelCase__ ) if is_compiled: UpperCamelCase_: List[str] = model UpperCamelCase_: Dict = model._orig_mod if is_deepspeed_available(): options += (DeepSpeedEngine,) while isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): UpperCamelCase_: Dict = model.module if not keep_fpaa_wrapper: UpperCamelCase_: int = getattr(UpperCAmelCase__ , 'forward' ) UpperCamelCase_: List[str] = model.__dict__.pop('_original_forward' , UpperCAmelCase__ ) if original_forward is not None: while hasattr(UpperCAmelCase__ , '__wrapped__' ): UpperCamelCase_: Any = forward.__wrapped__ if forward == original_forward: break UpperCamelCase_: Optional[int] = forward if getattr(UpperCAmelCase__ , '_converted_to_transformer_engine' , UpperCAmelCase__ ): convert_model(UpperCAmelCase__ , to_transformer_engine=UpperCAmelCase__ ) if is_compiled: UpperCamelCase_: Union[str, Any] = model UpperCamelCase_: Tuple = compiled_model return model def snake_case () -> List[str]: PartialState().wait_for_everyone() def snake_case (UpperCAmelCase__ , UpperCAmelCase__ ) -> Dict: if PartialState().distributed_type == DistributedType.TPU: xm.save(UpperCAmelCase__ , UpperCAmelCase__ ) elif PartialState().local_process_index == 0: torch.save(UpperCAmelCase__ , UpperCAmelCase__ ) @contextmanager def snake_case (**UpperCAmelCase__ ) -> Any: for key, value in kwargs.items(): UpperCamelCase_: int = str(UpperCAmelCase__ ) yield for key in kwargs: if key.upper() in os.environ: del os.environ[key.upper()] def snake_case (UpperCAmelCase__ ) -> str: if not hasattr(UpperCAmelCase__ , '__qualname__' ) and not hasattr(UpperCAmelCase__ , '__name__' ): UpperCamelCase_: List[Any] = getattr(UpperCAmelCase__ , '__class__' , UpperCAmelCase__ ) if hasattr(UpperCAmelCase__ , '__qualname__' ): return obj.__qualname__ if hasattr(UpperCAmelCase__ , '__name__' ): return obj.__name__ return str(UpperCAmelCase__ ) def snake_case (UpperCAmelCase__ , UpperCAmelCase__ ) -> Any: for key, value in source.items(): if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): UpperCamelCase_: Any = destination.setdefault(UpperCAmelCase__ , {} ) merge_dicts(UpperCAmelCase__ , UpperCAmelCase__ ) else: UpperCamelCase_: str = value return destination def snake_case (UpperCAmelCase__ = None ) -> bool: if port is None: UpperCamelCase_: List[str] = 2_9_5_0_0 with socket.socket(socket.AF_INET , socket.SOCK_STREAM ) as s: return s.connect_ex(('localhost', port) ) == 0
57
0
import contextlib import copy import random from typing import Any, Dict, Iterable, Optional, Union import numpy as np import torch from .utils import deprecate, is_transformers_available if is_transformers_available(): import transformers def UpperCamelCase ( snake_case__ : int ) -> Optional[int]: random.seed(snake_case__ ) np.random.seed(snake_case__ ) torch.manual_seed(snake_case__ ) torch.cuda.manual_seed_all(snake_case__ ) # ^^ safe to call this function even if cuda is not available class lowerCAmelCase_ : def __init__( self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ = 0.99_99, SCREAMING_SNAKE_CASE_ = 0.0, SCREAMING_SNAKE_CASE_ = 0, SCREAMING_SNAKE_CASE_ = False, SCREAMING_SNAKE_CASE_ = 1.0, SCREAMING_SNAKE_CASE_ = 2 / 3, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = None, **SCREAMING_SNAKE_CASE_, ) -> str: if isinstance(SCREAMING_SNAKE_CASE_, torch.nn.Module ): UpperCamelCase : int = ( 'Passing a `torch.nn.Module` to `ExponentialMovingAverage` is deprecated. ' 'Please pass the parameters of the module instead.' ) deprecate( 'passing a `torch.nn.Module` to `ExponentialMovingAverage`', '1.0.0', SCREAMING_SNAKE_CASE_, standard_warn=SCREAMING_SNAKE_CASE_, ) UpperCamelCase : Optional[Any] = parameters.parameters() # set use_ema_warmup to True if a torch.nn.Module is passed for backwards compatibility UpperCamelCase : List[str] = True if kwargs.get('max_value', SCREAMING_SNAKE_CASE_ ) is not None: UpperCamelCase : str = 'The `max_value` argument is deprecated. Please use `decay` instead.' deprecate('max_value', '1.0.0', SCREAMING_SNAKE_CASE_, standard_warn=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = kwargs['max_value'] if kwargs.get('min_value', SCREAMING_SNAKE_CASE_ ) is not None: UpperCamelCase : int = 'The `min_value` argument is deprecated. Please use `min_decay` instead.' deprecate('min_value', '1.0.0', SCREAMING_SNAKE_CASE_, standard_warn=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = kwargs['min_value'] UpperCamelCase : Optional[int] = list(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = [p.clone().detach() for p in parameters] if kwargs.get('device', SCREAMING_SNAKE_CASE_ ) is not None: UpperCamelCase : Any = 'The `device` argument is deprecated. Please use `to` instead.' deprecate('device', '1.0.0', SCREAMING_SNAKE_CASE_, standard_warn=SCREAMING_SNAKE_CASE_ ) self.to(device=kwargs['device'] ) UpperCamelCase : Optional[int] = None UpperCamelCase : List[str] = decay UpperCamelCase : int = min_decay UpperCamelCase : int = update_after_step UpperCamelCase : str = use_ema_warmup UpperCamelCase : Optional[Any] = inv_gamma UpperCamelCase : Tuple = power UpperCamelCase : Union[str, Any] = 0 UpperCamelCase : Tuple = None # set in `step()` UpperCamelCase : Dict = model_cls UpperCamelCase : Union[str, Any] = model_config @classmethod def snake_case_ ( cls, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) -> "EMAModel": UpperCamelCase , UpperCamelCase : Union[str, Any] = model_cls.load_config(SCREAMING_SNAKE_CASE_, return_unused_kwargs=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = model_cls.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = cls(model.parameters(), model_cls=SCREAMING_SNAKE_CASE_, model_config=model.config ) ema_model.load_state_dict(SCREAMING_SNAKE_CASE_ ) return ema_model def snake_case_ ( self, SCREAMING_SNAKE_CASE_ ) -> List[Any]: if self.model_cls is None: raise ValueError('`save_pretrained` can only be used if `model_cls` was defined at __init__.' ) if self.model_config is None: raise ValueError('`save_pretrained` can only be used if `model_config` was defined at __init__.' ) UpperCamelCase : Union[str, Any] = self.model_cls.from_config(self.model_config ) UpperCamelCase : Optional[int] = self.state_dict() state_dict.pop('shadow_params', SCREAMING_SNAKE_CASE_ ) model.register_to_config(**SCREAMING_SNAKE_CASE_ ) self.copy_to(model.parameters() ) model.save_pretrained(SCREAMING_SNAKE_CASE_ ) def snake_case_ ( self, SCREAMING_SNAKE_CASE_ ) -> float: UpperCamelCase : Optional[Any] = max(0, optimization_step - self.update_after_step - 1 ) if step <= 0: return 0.0 if self.use_ema_warmup: UpperCamelCase : List[Any] = 1 - (1 + step / self.inv_gamma) ** -self.power else: UpperCamelCase : List[str] = (1 + step) / (10 + step) UpperCamelCase : Tuple = min(SCREAMING_SNAKE_CASE_, self.decay ) # make sure decay is not smaller than min_decay UpperCamelCase : Tuple = max(SCREAMING_SNAKE_CASE_, self.min_decay ) return cur_decay_value @torch.no_grad() def snake_case_ ( self, SCREAMING_SNAKE_CASE_ ) -> Tuple: if isinstance(SCREAMING_SNAKE_CASE_, torch.nn.Module ): UpperCamelCase : Optional[int] = ( 'Passing a `torch.nn.Module` to `ExponentialMovingAverage.step` is deprecated. ' 'Please pass the parameters of the module instead.' ) deprecate( 'passing a `torch.nn.Module` to `ExponentialMovingAverage.step`', '1.0.0', SCREAMING_SNAKE_CASE_, standard_warn=SCREAMING_SNAKE_CASE_, ) UpperCamelCase : Optional[Any] = parameters.parameters() UpperCamelCase : Optional[Any] = list(SCREAMING_SNAKE_CASE_ ) self.optimization_step += 1 # Compute the decay factor for the exponential moving average. UpperCamelCase : Any = self.get_decay(self.optimization_step ) UpperCamelCase : Any = decay UpperCamelCase : str = 1 - decay UpperCamelCase : Union[str, Any] = contextlib.nullcontext if is_transformers_available() and transformers.deepspeed.is_deepspeed_zeroa_enabled(): import deepspeed for s_param, param in zip(self.shadow_params, SCREAMING_SNAKE_CASE_ ): if is_transformers_available() and transformers.deepspeed.is_deepspeed_zeroa_enabled(): UpperCamelCase : Dict = deepspeed.zero.GatheredParameters(SCREAMING_SNAKE_CASE_, modifier_rank=SCREAMING_SNAKE_CASE_ ) with context_manager(): if param.requires_grad: s_param.sub_(one_minus_decay * (s_param - param) ) else: s_param.copy_(SCREAMING_SNAKE_CASE_ ) def snake_case_ ( self, SCREAMING_SNAKE_CASE_ ) -> None: UpperCamelCase : Union[str, Any] = list(SCREAMING_SNAKE_CASE_ ) for s_param, param in zip(self.shadow_params, SCREAMING_SNAKE_CASE_ ): param.data.copy_(s_param.to(param.device ).data ) def snake_case_ ( self, SCREAMING_SNAKE_CASE_=None, SCREAMING_SNAKE_CASE_=None ) -> None: UpperCamelCase : str = [ p.to(device=SCREAMING_SNAKE_CASE_, dtype=SCREAMING_SNAKE_CASE_ ) if p.is_floating_point() else p.to(device=SCREAMING_SNAKE_CASE_ ) for p in self.shadow_params ] def snake_case_ ( self ) -> dict: return { "decay": self.decay, "min_decay": self.min_decay, "optimization_step": self.optimization_step, "update_after_step": self.update_after_step, "use_ema_warmup": self.use_ema_warmup, "inv_gamma": self.inv_gamma, "power": self.power, "shadow_params": self.shadow_params, } def snake_case_ ( self, SCREAMING_SNAKE_CASE_ ) -> None: UpperCamelCase : List[Any] = [param.detach().cpu().clone() for param in parameters] def snake_case_ ( self, SCREAMING_SNAKE_CASE_ ) -> None: if self.temp_stored_params is None: raise RuntimeError('This ExponentialMovingAverage has no `store()`ed weights ' 'to `restore()`' ) for c_param, param in zip(self.temp_stored_params, SCREAMING_SNAKE_CASE_ ): param.data.copy_(c_param.data ) # Better memory-wise. UpperCamelCase : Optional[int] = None def snake_case_ ( self, SCREAMING_SNAKE_CASE_ ) -> None: UpperCamelCase : List[Any] = copy.deepcopy(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = state_dict.get('decay', self.decay ) if self.decay < 0.0 or self.decay > 1.0: raise ValueError('Decay must be between 0 and 1' ) UpperCamelCase : int = state_dict.get('min_decay', self.min_decay ) if not isinstance(self.min_decay, SCREAMING_SNAKE_CASE_ ): raise ValueError('Invalid min_decay' ) UpperCamelCase : Union[str, Any] = state_dict.get('optimization_step', self.optimization_step ) if not isinstance(self.optimization_step, SCREAMING_SNAKE_CASE_ ): raise ValueError('Invalid optimization_step' ) UpperCamelCase : Dict = state_dict.get('update_after_step', self.update_after_step ) if not isinstance(self.update_after_step, SCREAMING_SNAKE_CASE_ ): raise ValueError('Invalid update_after_step' ) UpperCamelCase : Any = state_dict.get('use_ema_warmup', self.use_ema_warmup ) if not isinstance(self.use_ema_warmup, SCREAMING_SNAKE_CASE_ ): raise ValueError('Invalid use_ema_warmup' ) UpperCamelCase : Optional[Any] = state_dict.get('inv_gamma', self.inv_gamma ) if not isinstance(self.inv_gamma, (float, int) ): raise ValueError('Invalid inv_gamma' ) UpperCamelCase : Tuple = state_dict.get('power', self.power ) if not isinstance(self.power, (float, int) ): raise ValueError('Invalid power' ) UpperCamelCase : Tuple = state_dict.get('shadow_params', SCREAMING_SNAKE_CASE_ ) if shadow_params is not None: UpperCamelCase : Optional[int] = shadow_params if not isinstance(self.shadow_params, SCREAMING_SNAKE_CASE_ ): raise ValueError('shadow_params must be a list' ) if not all(isinstance(SCREAMING_SNAKE_CASE_, torch.Tensor ) for p in self.shadow_params ): raise ValueError('shadow_params must all be Tensors' )
40
import argparse import os import pickle import sys import torch from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() # We do this to be able to load python 2 datasets pickles # See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918 A_ : Optional[Any] = data_utils.TransfoXLTokenizer A_ : Union[str, Any] = data_utils.TransfoXLCorpus A_ : Any = data_utils A_ : Optional[Any] = data_utils def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) -> List[str]: if transfo_xl_dataset_file: # Convert a pre-processed corpus (see original TensorFlow repo) with open(UpperCAmelCase__ , 'rb' ) as fp: UpperCamelCase_: Union[str, Any] = pickle.load(UpperCAmelCase__ , encoding='latin1' ) # Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term) UpperCamelCase_: Any = pytorch_dump_folder_path + '/' + VOCAB_FILES_NAMES['pretrained_vocab_file'] print(F'''Save vocabulary to {pytorch_vocab_dump_path}''' ) UpperCamelCase_: Union[str, Any] = corpus.vocab.__dict__ torch.save(UpperCAmelCase__ , UpperCAmelCase__ ) UpperCamelCase_: str = corpus.__dict__ corpus_dict_no_vocab.pop('vocab' , UpperCAmelCase__ ) UpperCamelCase_: str = pytorch_dump_folder_path + '/' + CORPUS_NAME print(F'''Save dataset to {pytorch_dataset_dump_path}''' ) torch.save(UpperCAmelCase__ , UpperCAmelCase__ ) if tf_checkpoint_path: # Convert a pre-trained TensorFlow model UpperCamelCase_: Any = os.path.abspath(UpperCAmelCase__ ) UpperCamelCase_: Dict = os.path.abspath(UpperCAmelCase__ ) print(F'''Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.''' ) # Initialise PyTorch model if transfo_xl_config_file == "": UpperCamelCase_: List[str] = TransfoXLConfig() else: UpperCamelCase_: Optional[int] = TransfoXLConfig.from_json_file(UpperCAmelCase__ ) print(F'''Building PyTorch model from configuration: {config}''' ) UpperCamelCase_: Union[str, Any] = TransfoXLLMHeadModel(UpperCAmelCase__ ) UpperCamelCase_: Tuple = load_tf_weights_in_transfo_xl(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) # Save pytorch-model UpperCamelCase_: str = os.path.join(UpperCAmelCase__ , UpperCAmelCase__ ) UpperCamelCase_: Union[str, Any] = os.path.join(UpperCAmelCase__ , UpperCAmelCase__ ) print(F'''Save PyTorch model to {os.path.abspath(UpperCAmelCase__ )}''' ) torch.save(model.state_dict() , UpperCAmelCase__ ) print(F'''Save configuration file to {os.path.abspath(UpperCAmelCase__ )}''' ) with open(UpperCAmelCase__ , 'w' , encoding='utf-8' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": A_ : int = argparse.ArgumentParser() parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the folder to store the PyTorch model or dataset/vocab.', ) parser.add_argument( '--tf_checkpoint_path', default='', type=str, help='An optional path to a TensorFlow checkpoint path to be converted.', ) parser.add_argument( '--transfo_xl_config_file', default='', type=str, help=( 'An optional config json file corresponding to the pre-trained BERT model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--transfo_xl_dataset_file', default='', type=str, help='An optional dataset file to be converted in a vocabulary.', ) A_ : Tuple = parser.parse_args() convert_transfo_xl_checkpoint_to_pytorch( args.tf_checkpoint_path, args.transfo_xl_config_file, args.pytorch_dump_folder_path, args.transfo_xl_dataset_file, )
57
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_torch_available, ) lowerCAmelCase__ = { '''configuration_speecht5''': [ '''SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP''', '''SpeechT5Config''', '''SpeechT5HifiGanConfig''', ], '''feature_extraction_speecht5''': ['''SpeechT5FeatureExtractor'''], '''processing_speecht5''': ['''SpeechT5Processor'''], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = ['''SpeechT5Tokenizer'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ '''SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST''', '''SpeechT5ForSpeechToText''', '''SpeechT5ForSpeechToSpeech''', '''SpeechT5ForTextToSpeech''', '''SpeechT5Model''', '''SpeechT5PreTrainedModel''', '''SpeechT5HifiGan''', ] if TYPE_CHECKING: from .configuration_speechta import ( SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP, SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP, SpeechTaConfig, SpeechTaHifiGanConfig, ) from .feature_extraction_speechta import SpeechTaFeatureExtractor from .processing_speechta import SpeechTaProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speechta import SpeechTaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speechta import ( SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechTaForSpeechToSpeech, SpeechTaForSpeechToText, SpeechTaForTextToSpeech, SpeechTaHifiGan, SpeechTaModel, SpeechTaPreTrainedModel, ) else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
41
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL A_ : List[str] = logging.get_logger(__name__) def snake_case (UpperCAmelCase__ , UpperCAmelCase__ ) -> Union[str, Any]: UpperCamelCase_: Tuple = b.T UpperCamelCase_: Tuple = np.sum(np.square(UpperCAmelCase__ ) , axis=1 ) UpperCamelCase_: Optional[Any] = np.sum(np.square(UpperCAmelCase__ ) , axis=0 ) UpperCamelCase_: Optional[int] = np.matmul(UpperCAmelCase__ , UpperCAmelCase__ ) UpperCamelCase_: List[Any] = aa[:, None] - 2 * ab + ba[None, :] return d def snake_case (UpperCAmelCase__ , UpperCAmelCase__ ) -> Optional[Any]: UpperCamelCase_: List[str] = x.reshape(-1 , 3 ) UpperCamelCase_: Union[str, Any] = squared_euclidean_distance(UpperCAmelCase__ , UpperCAmelCase__ ) return np.argmin(UpperCAmelCase__ , axis=1 ) class _lowerCAmelCase( UpperCAmelCase_ ): """simple docstring""" a : Any =['''pixel_values'''] def __init__( self , _lowerCamelCase = None , _lowerCamelCase = True , _lowerCamelCase = None , _lowerCamelCase = PILImageResampling.BILINEAR , _lowerCamelCase = True , _lowerCamelCase = True , **_lowerCamelCase , ): super().__init__(**_lowerCamelCase ) UpperCamelCase_: List[str] = size if size is not None else {'height': 2_5_6, 'width': 2_5_6} UpperCamelCase_: str = get_size_dict(_lowerCamelCase ) UpperCamelCase_: Any = np.array(_lowerCamelCase ) if clusters is not None else None UpperCamelCase_: Optional[int] = do_resize UpperCamelCase_: List[Any] = size UpperCamelCase_: Optional[int] = resample UpperCamelCase_: str = do_normalize UpperCamelCase_: str = do_color_quantize def _a ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = PILImageResampling.BILINEAR , _lowerCamelCase = None , **_lowerCamelCase , ): UpperCamelCase_: Any = get_size_dict(_lowerCamelCase ) if "height" not in size or "width" not in size: raise ValueError(f'''Size dictionary must contain both height and width keys. Got {size.keys()}''' ) return resize( _lowerCamelCase , size=(size['height'], size['width']) , resample=_lowerCamelCase , data_format=_lowerCamelCase , **_lowerCamelCase ) def _a ( self , _lowerCamelCase , _lowerCamelCase = None , ): UpperCamelCase_: Optional[Any] = rescale(image=_lowerCamelCase , scale=1 / 1_2_7.5 , data_format=_lowerCamelCase ) UpperCamelCase_: Optional[Any] = image - 1 return image def _a ( self , _lowerCamelCase , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = ChannelDimension.FIRST , **_lowerCamelCase , ): UpperCamelCase_: Optional[Any] = do_resize if do_resize is not None else self.do_resize UpperCamelCase_: Tuple = size if size is not None else self.size UpperCamelCase_: Union[str, Any] = get_size_dict(_lowerCamelCase ) UpperCamelCase_: Union[str, Any] = resample if resample is not None else self.resample UpperCamelCase_: Any = do_normalize if do_normalize is not None else self.do_normalize UpperCamelCase_: str = do_color_quantize if do_color_quantize is not None else self.do_color_quantize UpperCamelCase_: Dict = clusters if clusters is not None else self.clusters UpperCamelCase_: Dict = np.array(_lowerCamelCase ) UpperCamelCase_: Optional[int] = make_list_of_images(_lowerCamelCase ) if not valid_images(_lowerCamelCase ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None or resample is None: raise ValueError('Size and resample must be specified if do_resize is True.' ) if do_color_quantize and clusters is None: raise ValueError('Clusters must be specified if do_color_quantize is True.' ) # All transformations expect numpy arrays. UpperCamelCase_: Union[str, Any] = [to_numpy_array(_lowerCamelCase ) for image in images] if do_resize: UpperCamelCase_: Union[str, Any] = [self.resize(image=_lowerCamelCase , size=_lowerCamelCase , resample=_lowerCamelCase ) for image in images] if do_normalize: UpperCamelCase_: Optional[Any] = [self.normalize(image=_lowerCamelCase ) for image in images] if do_color_quantize: UpperCamelCase_: Any = [to_channel_dimension_format(_lowerCamelCase , ChannelDimension.LAST ) for image in images] # color quantize from (batch_size, height, width, 3) to (batch_size, height, width) UpperCamelCase_: Optional[Any] = np.array(_lowerCamelCase ) UpperCamelCase_: Optional[Any] = color_quantize(_lowerCamelCase , _lowerCamelCase ).reshape(images.shape[:-1] ) # flatten to (batch_size, height*width) UpperCamelCase_: Dict = images.shape[0] UpperCamelCase_: Any = images.reshape(_lowerCamelCase , -1 ) # We need to convert back to a list of images to keep consistent behaviour across processors. UpperCamelCase_: List[Any] = list(_lowerCamelCase ) else: UpperCamelCase_: int = [to_channel_dimension_format(_lowerCamelCase , _lowerCamelCase ) for image in images] UpperCamelCase_: str = {'input_ids': images} return BatchFeature(data=_lowerCamelCase , tensor_type=_lowerCamelCase )
57
0
'''simple docstring''' import itertools from dataclasses import dataclass from typing import Optional import pandas as pd import pyarrow as pa import datasets from datasets.table import table_cast @dataclass class UpperCAmelCase ( datasets.BuilderConfig ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = None class UpperCAmelCase ( datasets.ArrowBasedBuilder ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = PandasConfig def UpperCamelCase( self ) -> str: '''simple docstring''' return datasets.DatasetInfo(features=self.config.features ) def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Dict: '''simple docstring''' if not self.config.data_files: raise ValueError(f'''At least one data file must be specified, but got data_files={self.config.data_files}''' ) lowerCamelCase_ = dl_manager.download_and_extract(self.config.data_files ) if isinstance(SCREAMING_SNAKE_CASE_ , (str, list, tuple) ): lowerCamelCase_ = data_files if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): lowerCamelCase_ = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive lowerCamelCase_ = [dl_manager.iter_files(SCREAMING_SNAKE_CASE_ ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'files': files} )] lowerCamelCase_ = [] for split_name, files in data_files.items(): if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): lowerCamelCase_ = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive lowerCamelCase_ = [dl_manager.iter_files(SCREAMING_SNAKE_CASE_ ) for file in files] splits.append(datasets.SplitGenerator(name=SCREAMING_SNAKE_CASE_ , gen_kwargs={'files': files} ) ) return splits def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> pa.Table: '''simple docstring''' if self.config.features is not None: # more expensive cast to support nested features with keys in a different order # allows str <-> int/float or str to Audio for example lowerCamelCase_ = table_cast(SCREAMING_SNAKE_CASE_ , self.config.features.arrow_schema ) return pa_table def UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> str: '''simple docstring''' for i, file in enumerate(itertools.chain.from_iterable(SCREAMING_SNAKE_CASE_ ) ): with open(SCREAMING_SNAKE_CASE_ , 'rb' ) as f: lowerCamelCase_ = pa.Table.from_pandas(pd.read_pickle(SCREAMING_SNAKE_CASE_ ) ) yield i, self._cast_table(SCREAMING_SNAKE_CASE_ )
42
import numpy # List of input, output pairs A_ : Any = ( ((5, 2, 3), 15), ((6, 5, 9), 25), ((11, 12, 13), 41), ((1, 1, 1), 8), ((11, 12, 13), 41), ) A_ : List[Any] = (((515, 22, 13), 555), ((61, 35, 49), 150)) A_ : Any = [2, 4, 1, 5] A_ : List[Any] = len(train_data) A_ : List[Any] = 0.009 def snake_case (UpperCAmelCase__ , UpperCAmelCase__="train" ) -> Optional[int]: return calculate_hypothesis_value(UpperCAmelCase__ , UpperCAmelCase__ ) - output( UpperCAmelCase__ , UpperCAmelCase__ ) def snake_case (UpperCAmelCase__ ) -> Optional[Any]: UpperCamelCase_: Optional[Any] = 0 for i in range(len(UpperCAmelCase__ ) - 1 ): hyp_val += data_input_tuple[i] * parameter_vector[i + 1] hyp_val += parameter_vector[0] return hyp_val def snake_case (UpperCAmelCase__ , UpperCAmelCase__ ) -> List[Any]: if data_set == "train": return train_data[example_no][1] elif data_set == "test": return test_data[example_no][1] return None def snake_case (UpperCAmelCase__ , UpperCAmelCase__ ) -> Optional[Any]: if data_set == "train": return _hypothesis_value(train_data[example_no][0] ) elif data_set == "test": return _hypothesis_value(test_data[example_no][0] ) return None def snake_case (UpperCAmelCase__ , UpperCAmelCase__=m ) -> Optional[Any]: UpperCamelCase_: Any = 0 for i in range(UpperCAmelCase__ ): if index == -1: summation_value += _error(UpperCAmelCase__ ) else: summation_value += _error(UpperCAmelCase__ ) * train_data[i][0][index] return summation_value def snake_case (UpperCAmelCase__ ) -> Optional[Any]: UpperCamelCase_: Optional[int] = summation_of_cost_derivative(UpperCAmelCase__ , UpperCAmelCase__ ) / m return cost_derivative_value def snake_case () -> Union[str, Any]: global parameter_vector # Tune these values to set a tolerance value for predicted output UpperCamelCase_: str = 0.00_0002 UpperCamelCase_: Any = 0 UpperCamelCase_: int = 0 while True: j += 1 UpperCamelCase_: int = [0, 0, 0, 0] for i in range(0 , len(UpperCAmelCase__ ) ): UpperCamelCase_: Any = get_cost_derivative(i - 1 ) UpperCamelCase_: Optional[int] = ( parameter_vector[i] - LEARNING_RATE * cost_derivative ) if numpy.allclose( UpperCAmelCase__ , UpperCAmelCase__ , atol=UpperCAmelCase__ , rtol=UpperCAmelCase__ , ): break UpperCamelCase_: Optional[int] = temp_parameter_vector print(('Number of iterations:', j) ) def snake_case () -> int: for i in range(len(UpperCAmelCase__ ) ): print(('Actual output value:', output(UpperCAmelCase__ , 'test' )) ) print(('Hypothesis output:', calculate_hypothesis_value(UpperCAmelCase__ , 'test' )) ) if __name__ == "__main__": run_gradient_descent() print('\nTesting gradient descent for a linear hypothesis function.\n') test_gradient_descent()
57
0
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCAmelCase = logging.get_logger(__name__) lowerCAmelCase = { 'google/mobilenet_v1_1.0_224': 'https://huggingface.co/google/mobilenet_v1_1.0_224/resolve/main/config.json', 'google/mobilenet_v1_0.75_192': 'https://huggingface.co/google/mobilenet_v1_0.75_192/resolve/main/config.json', # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1 } class _a ( UpperCamelCase__ ): _lowercase : Optional[Any] = '''mobilenet_v1''' def __init__( self: List[Any] , UpperCamelCase_: Any=3 , UpperCamelCase_: int=224 , UpperCamelCase_: Optional[int]=1.0 , UpperCamelCase_: int=8 , UpperCamelCase_: str="relu6" , UpperCamelCase_: Optional[Any]=True , UpperCamelCase_: List[Any]=0.999 , UpperCamelCase_: List[Any]=0.02 , UpperCamelCase_: Union[str, Any]=0.001 , **UpperCamelCase_: Optional[int] , ) -> List[Any]: """simple docstring""" super().__init__(**UpperCamelCase_ ) if depth_multiplier <= 0: raise ValueError('''depth_multiplier must be greater than zero.''' ) lowercase__ = num_channels lowercase__ = image_size lowercase__ = depth_multiplier lowercase__ = min_depth lowercase__ = hidden_act lowercase__ = tf_padding lowercase__ = classifier_dropout_prob lowercase__ = initializer_range lowercase__ = layer_norm_eps class _a ( UpperCamelCase__ ): _lowercase : List[str] = version.parse('''1.11''' ) @property def lowerCamelCase_ ( self: List[str] ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" return OrderedDict([('''pixel_values''', {0: '''batch'''})] ) @property def lowerCamelCase_ ( self: Dict ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" if self.task == "image-classification": return OrderedDict([('''logits''', {0: '''batch'''})] ) else: return OrderedDict([('''last_hidden_state''', {0: '''batch'''}), ('''pooler_output''', {0: '''batch'''})] ) @property def lowerCamelCase_ ( self: Any ) -> float: """simple docstring""" return 1E-4
43
from ...utils import ( OptionalDependencyNotAvailable, is_flax_available, is_torch_available, is_transformers_available, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .multicontrolnet import MultiControlNetModel from .pipeline_controlnet import StableDiffusionControlNetPipeline from .pipeline_controlnet_imgaimg import StableDiffusionControlNetImgaImgPipeline from .pipeline_controlnet_inpaint import StableDiffusionControlNetInpaintPipeline if is_transformers_available() and is_flax_available(): from .pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline
57
0
'''simple docstring''' import os import textwrap import pyarrow as pa import pytest from datasets import ClassLabel, Features, Image from datasets.packaged_modules.csv.csv import Csv from ..utils import require_pil @pytest.fixture def A_ ( _lowerCAmelCase : Optional[Any] ): """simple docstring""" _lowerCamelCase : Tuple = tmp_path / "file.csv" _lowerCamelCase : Optional[int] = textwrap.dedent( "\\n header1,header2\n 1,2\n 10,20\n " ) with open(_lowerCAmelCase , "w" ) as f: f.write(_lowerCAmelCase ) return str(_lowerCAmelCase ) @pytest.fixture def A_ ( _lowerCAmelCase : List[Any] ): """simple docstring""" _lowerCamelCase : Any = tmp_path / "malformed_file.csv" _lowerCamelCase : Any = textwrap.dedent( "\\n header1,header2\n 1,2\n 10,20,\n " ) with open(_lowerCAmelCase , "w" ) as f: f.write(_lowerCAmelCase ) return str(_lowerCAmelCase ) @pytest.fixture def A_ ( _lowerCAmelCase : Any , _lowerCAmelCase : Dict ): """simple docstring""" _lowerCamelCase : int = tmp_path / "csv_with_image.csv" _lowerCamelCase : int = textwrap.dedent( F'\\n image\n {image_file}\n ' ) with open(_lowerCAmelCase , "w" ) as f: f.write(_lowerCAmelCase ) return str(_lowerCAmelCase ) @pytest.fixture def A_ ( _lowerCAmelCase : List[str] ): """simple docstring""" _lowerCamelCase : Dict = tmp_path / "csv_with_label.csv" _lowerCamelCase : int = textwrap.dedent( "\\n label\n good\n bad\n good\n " ) with open(_lowerCAmelCase , "w" ) as f: f.write(_lowerCAmelCase ) return str(_lowerCAmelCase ) @pytest.fixture def A_ ( _lowerCAmelCase : Dict ): """simple docstring""" _lowerCamelCase : Dict = tmp_path / "csv_with_int_list.csv" _lowerCamelCase : Any = textwrap.dedent( "\\n int_list\n 1 2 3\n 4 5 6\n 7 8 9\n " ) with open(_lowerCAmelCase , "w" ) as f: f.write(_lowerCAmelCase ) return str(_lowerCAmelCase ) def A_ ( _lowerCAmelCase : List[Any] , _lowerCAmelCase : int , _lowerCAmelCase : Tuple ): """simple docstring""" _lowerCamelCase : List[Any] = Csv() _lowerCamelCase : Any = csv._generate_tables([[csv_file, malformed_csv_file]] ) with pytest.raises(_lowerCAmelCase , match="Error tokenizing data" ): for _ in generator: pass assert any( record.levelname == "ERROR" and "Failed to read file" in record.message and os.path.basename(_lowerCAmelCase ) in record.message for record in caplog.records ) @require_pil def A_ ( _lowerCAmelCase : Union[str, Any] ): """simple docstring""" with open(_lowerCAmelCase , encoding="utf-8" ) as f: _lowerCamelCase : Any = f.read().splitlines()[1] _lowerCamelCase : Optional[Any] = Csv(encoding="utf-8" , features=Features({"image": Image()} ) ) _lowerCamelCase : Union[str, Any] = csv._generate_tables([[csv_file_with_image]] ) _lowerCamelCase : List[str] = pa.concat_tables([table for _, table in generator] ) assert pa_table.schema.field("image" ).type == Image()() _lowerCamelCase : int = pa_table.to_pydict()["image"] assert generated_content == [{"path": image_file, "bytes": None}] def A_ ( _lowerCAmelCase : List[Any] ): """simple docstring""" with open(_lowerCAmelCase , encoding="utf-8" ) as f: _lowerCamelCase : List[Any] = f.read().splitlines()[1:] _lowerCamelCase : int = Csv(encoding="utf-8" , features=Features({"label": ClassLabel(names=["good", "bad"] )} ) ) _lowerCamelCase : Tuple = csv._generate_tables([[csv_file_with_label]] ) _lowerCamelCase : int = pa.concat_tables([table for _, table in generator] ) assert pa_table.schema.field("label" ).type == ClassLabel(names=["good", "bad"] )() _lowerCamelCase : Union[str, Any] = pa_table.to_pydict()["label"] assert generated_content == [ClassLabel(names=["good", "bad"] ).straint(_lowerCAmelCase ) for label in labels] def A_ ( _lowerCAmelCase : str ): """simple docstring""" _lowerCamelCase : Dict = Csv(encoding="utf-8" , sep="," , converters={"int_list": lambda _lowerCAmelCase : [int(_lowerCAmelCase ) for i in x.split()]} ) _lowerCamelCase : List[Any] = csv._generate_tables([[csv_file_with_int_list]] ) _lowerCamelCase : Optional[int] = pa.concat_tables([table for _, table in generator] ) assert pa.types.is_list(pa_table.schema.field("int_list" ).type ) _lowerCamelCase : Optional[Any] = pa_table.to_pydict()["int_list"] assert generated_content == [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
44
from __future__ import annotations import unittest from transformers import AutoTokenizer, PegasusConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFPegasusForConditionalGeneration, TFPegasusModel @require_tf class _lowerCAmelCase: """simple docstring""" a : int =PegasusConfig a : List[str] ={} a : Optional[int] ='''gelu''' def __init__( self , _lowerCamelCase , _lowerCamelCase=1_3 , _lowerCamelCase=7 , _lowerCamelCase=True , _lowerCamelCase=False , _lowerCamelCase=9_9 , _lowerCamelCase=3_2 , _lowerCamelCase=2 , _lowerCamelCase=4 , _lowerCamelCase=3_7 , _lowerCamelCase=0.1 , _lowerCamelCase=0.1 , _lowerCamelCase=4_0 , _lowerCamelCase=2 , _lowerCamelCase=1 , _lowerCamelCase=0 , ): UpperCamelCase_: List[Any] = parent UpperCamelCase_: Dict = batch_size UpperCamelCase_: List[str] = seq_length UpperCamelCase_: List[str] = is_training UpperCamelCase_: Any = use_labels UpperCamelCase_: Optional[Any] = vocab_size UpperCamelCase_: Tuple = hidden_size UpperCamelCase_: List[Any] = num_hidden_layers UpperCamelCase_: Any = num_attention_heads UpperCamelCase_: Optional[Any] = intermediate_size UpperCamelCase_: Optional[int] = hidden_dropout_prob UpperCamelCase_: int = attention_probs_dropout_prob UpperCamelCase_: Union[str, Any] = max_position_embeddings UpperCamelCase_: Dict = eos_token_id UpperCamelCase_: Union[str, Any] = pad_token_id UpperCamelCase_: List[Any] = bos_token_id def _a ( self ): UpperCamelCase_: Union[str, Any] = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) UpperCamelCase_: int = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) UpperCamelCase_: List[str] = tf.concat([input_ids, eos_tensor] , axis=1 ) UpperCamelCase_: Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase_: Tuple = 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 , ) UpperCamelCase_: Optional[Any] = prepare_pegasus_inputs_dict(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) return config, inputs_dict def _a ( self , _lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: Optional[Any] = TFPegasusModel(config=_lowerCamelCase ).get_decoder() UpperCamelCase_: Optional[int] = inputs_dict['input_ids'] UpperCamelCase_: Optional[int] = input_ids[:1, :] UpperCamelCase_: int = inputs_dict['attention_mask'][:1, :] UpperCamelCase_: Optional[int] = inputs_dict['head_mask'] UpperCamelCase_: Optional[int] = 1 # first forward pass UpperCamelCase_: Union[str, Any] = model(_lowerCamelCase , attention_mask=_lowerCamelCase , head_mask=_lowerCamelCase , use_cache=_lowerCamelCase ) UpperCamelCase_ ,UpperCamelCase_: int = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids UpperCamelCase_: int = ids_tensor((self.batch_size, 3) , config.vocab_size ) UpperCamelCase_: List[Any] = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and UpperCamelCase_: Union[str, Any] = tf.concat([input_ids, next_tokens] , axis=-1 ) UpperCamelCase_: int = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) UpperCamelCase_: Any = model(_lowerCamelCase , attention_mask=_lowerCamelCase )[0] UpperCamelCase_: int = model(_lowerCamelCase , attention_mask=_lowerCamelCase , past_key_values=_lowerCamelCase )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice UpperCamelCase_: Optional[int] = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) UpperCamelCase_: Any = output_from_no_past[:, -3:, random_slice_idx] UpperCamelCase_: Union[str, Any] = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(_lowerCamelCase , _lowerCamelCase , rtol=1e-3 ) def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__=None , UpperCAmelCase__=None , UpperCAmelCase__=None , UpperCAmelCase__=None , UpperCAmelCase__=None , ) -> str: if attention_mask is None: UpperCamelCase_: Optional[Any] = tf.cast(tf.math.not_equal(UpperCAmelCase__ , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: UpperCamelCase_: int = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: UpperCamelCase_: str = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: UpperCamelCase_: Any = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: UpperCamelCase_: int = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class _lowerCAmelCase( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase ): """simple docstring""" a : Tuple =(TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else () a : int =(TFPegasusForConditionalGeneration,) if is_tf_available() else () a : Tuple =( { '''conversational''': TFPegasusForConditionalGeneration, '''feature-extraction''': TFPegasusModel, '''summarization''': TFPegasusForConditionalGeneration, '''text2text-generation''': TFPegasusForConditionalGeneration, '''translation''': TFPegasusForConditionalGeneration, } if is_tf_available() else {} ) a : List[str] =True a : List[str] =False a : Tuple =False def _a ( self ): UpperCamelCase_: Dict = TFPegasusModelTester(self ) UpperCamelCase_: Any = ConfigTester(self , config_class=_lowerCamelCase ) def _a ( self ): self.config_tester.run_common_tests() def _a ( self ): UpperCamelCase_: Any = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*_lowerCamelCase ) @require_sentencepiece @require_tokenizers @require_tf class _lowerCAmelCase( unittest.TestCase ): """simple docstring""" a : Dict =[ ''' 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!" ''', ] a : int =[ '''California\'s largest electricity provider has cut power to hundreds of thousands of customers in an effort to''' ''' reduce the risk of wildfires.''', '''N-Dubz have revealed they\'re "grateful" to have been nominated for four Mobo Awards.''', ] # differs slightly from pytorch, likely due to numerical differences in linear layers a : Union[str, Any] ='''google/pegasus-xsum''' @cached_property def _a ( self ): return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def _a ( self ): UpperCamelCase_: Optional[Any] = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def _a ( self , **_lowerCamelCase ): UpperCamelCase_: Dict = self.translate_src_text(**_lowerCamelCase ) assert self.expected_text == generated_words def _a ( self , **_lowerCamelCase ): UpperCamelCase_: Union[str, Any] = self.tokenizer(self.src_text , **_lowerCamelCase , padding=_lowerCamelCase , return_tensors='tf' ) UpperCamelCase_: Any = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=_lowerCamelCase , ) UpperCamelCase_: str = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=_lowerCamelCase ) return generated_words @slow def _a ( self ): self._assert_generated_batch_equal_expected()
57
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCamelCase = { "configuration_xlm_roberta_xl": [ "XLM_ROBERTA_XL_PRETRAINED_CONFIG_ARCHIVE_MAP", "XLMRobertaXLConfig", "XLMRobertaXLOnnxConfig", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = [ "XLM_ROBERTA_XL_PRETRAINED_MODEL_ARCHIVE_LIST", "XLMRobertaXLForCausalLM", "XLMRobertaXLForMaskedLM", "XLMRobertaXLForMultipleChoice", "XLMRobertaXLForQuestionAnswering", "XLMRobertaXLForSequenceClassification", "XLMRobertaXLForTokenClassification", "XLMRobertaXLModel", "XLMRobertaXLPreTrainedModel", ] if TYPE_CHECKING: from .configuration_xlm_roberta_xl import ( XLM_ROBERTA_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMRobertaXLConfig, XLMRobertaXLOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm_roberta_xl import ( XLM_ROBERTA_XL_PRETRAINED_MODEL_ARCHIVE_LIST, XLMRobertaXLForCausalLM, XLMRobertaXLForMaskedLM, XLMRobertaXLForMultipleChoice, XLMRobertaXLForQuestionAnswering, XLMRobertaXLForSequenceClassification, XLMRobertaXLForTokenClassification, XLMRobertaXLModel, XLMRobertaXLPreTrainedModel, ) else: import sys UpperCamelCase = _LazyModule(__name__, globals()["__file__"], _import_structure)
45
import unittest import numpy as np def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ = None , ) -> np.ndarray: UpperCamelCase_: str = np.shape(UpperCAmelCase__ ) UpperCamelCase_: str = np.shape(UpperCAmelCase__ ) UpperCamelCase_: List[Any] = np.shape(UpperCAmelCase__ ) if shape_a[0] != shape_b[0]: UpperCamelCase_: Any = ( 'Expected the same number of rows for A and B. ' F'''Instead found A of size {shape_a} and B of size {shape_b}''' ) raise ValueError(UpperCAmelCase__ ) if shape_b[1] != shape_c[1]: UpperCamelCase_: int = ( 'Expected the same number of columns for B and C. ' F'''Instead found B of size {shape_b} and C of size {shape_c}''' ) raise ValueError(UpperCAmelCase__ ) UpperCamelCase_: Dict = pseudo_inv if a_inv is None: try: UpperCamelCase_: Optional[Any] = np.linalg.inv(UpperCAmelCase__ ) except np.linalg.LinAlgError: raise ValueError( 'Input matrix A is not invertible. Cannot compute Schur complement.' ) return mat_c - mat_b.T @ a_inv @ mat_b class _lowerCAmelCase( unittest.TestCase ): """simple docstring""" def _a ( self ): UpperCamelCase_: Any = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) UpperCamelCase_: Dict = np.array([[0, 3], [3, 0], [2, 3]] ) UpperCamelCase_: Tuple = np.array([[2, 1], [6, 3]] ) UpperCamelCase_: Tuple = schur_complement(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) UpperCamelCase_: Optional[Any] = np.block([[a, b], [b.T, c]] ) UpperCamelCase_: List[str] = np.linalg.det(_lowerCamelCase ) UpperCamelCase_: List[str] = np.linalg.det(_lowerCamelCase ) UpperCamelCase_: Dict = np.linalg.det(_lowerCamelCase ) self.assertAlmostEqual(_lowerCamelCase , det_a * det_s ) def _a ( self ): UpperCamelCase_: int = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) UpperCamelCase_: List[str] = np.array([[0, 3], [3, 0], [2, 3]] ) UpperCamelCase_: List[str] = np.array([[2, 1], [6, 3]] ) with self.assertRaises(_lowerCamelCase ): schur_complement(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def _a ( self ): UpperCamelCase_: List[Any] = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) UpperCamelCase_: str = np.array([[0, 3], [3, 0], [2, 3]] ) UpperCamelCase_: List[Any] = np.array([[2, 1, 3], [6, 3, 5]] ) with self.assertRaises(_lowerCamelCase ): schur_complement(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) if __name__ == "__main__": import doctest doctest.testmod() unittest.main()
57
0
"""simple docstring""" import unittest from parameterized import parameterized from transformers import LlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaTokenizer class A_ : def __init__( self: str ,__lowerCAmelCase: Tuple ,__lowerCAmelCase: List[str]=13 ,__lowerCAmelCase: Optional[Any]=7 ,__lowerCAmelCase: Union[str, Any]=True ,__lowerCAmelCase: Any=True ,__lowerCAmelCase: int=False ,__lowerCAmelCase: Dict=True ,__lowerCAmelCase: Any=99 ,__lowerCAmelCase: List[str]=32 ,__lowerCAmelCase: Tuple=5 ,__lowerCAmelCase: List[str]=4 ,__lowerCAmelCase: Dict=37 ,__lowerCAmelCase: Tuple="gelu" ,__lowerCAmelCase: List[str]=0.1 ,__lowerCAmelCase: Optional[int]=0.1 ,__lowerCAmelCase: Tuple=512 ,__lowerCAmelCase: List[Any]=16 ,__lowerCAmelCase: List[Any]=2 ,__lowerCAmelCase: Tuple=0.02 ,__lowerCAmelCase: Tuple=3 ,__lowerCAmelCase: Tuple=4 ,__lowerCAmelCase: str=None ,): '''simple docstring''' _lowerCamelCase : Any = parent _lowerCamelCase : Optional[Any] = batch_size _lowerCamelCase : Optional[Any] = seq_length _lowerCamelCase : Any = is_training _lowerCamelCase : Union[str, Any] = use_input_mask _lowerCamelCase : int = use_token_type_ids _lowerCamelCase : Tuple = use_labels _lowerCamelCase : Optional[Any] = vocab_size _lowerCamelCase : Any = hidden_size _lowerCamelCase : Optional[Any] = num_hidden_layers _lowerCamelCase : Optional[Any] = num_attention_heads _lowerCamelCase : Any = intermediate_size _lowerCamelCase : Dict = hidden_act _lowerCamelCase : str = hidden_dropout_prob _lowerCamelCase : Dict = attention_probs_dropout_prob _lowerCamelCase : Tuple = max_position_embeddings _lowerCamelCase : Any = type_vocab_size _lowerCamelCase : Any = type_sequence_label_size _lowerCamelCase : Union[str, Any] = initializer_range _lowerCamelCase : Dict = num_labels _lowerCamelCase : Union[str, Any] = num_choices _lowerCamelCase : str = scope def _lowercase ( self: Dict ): '''simple docstring''' _lowerCamelCase : Tuple = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) _lowerCamelCase : str = None if self.use_input_mask: _lowerCamelCase : Dict = random_attention_mask([self.batch_size, self.seq_length] ) _lowerCamelCase : str = None if self.use_token_type_ids: _lowerCamelCase : str = ids_tensor([self.batch_size, self.seq_length] ,self.type_vocab_size ) _lowerCamelCase : Any = None _lowerCamelCase : Union[str, Any] = None _lowerCamelCase : List[Any] = None if self.use_labels: _lowerCamelCase : Optional[int] = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) _lowerCamelCase : Any = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) _lowerCamelCase : Optional[int] = ids_tensor([self.batch_size] ,self.num_choices ) _lowerCamelCase : Dict = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _lowercase ( self: List[str] ): '''simple docstring''' return LlamaConfig( vocab_size=self.vocab_size ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,hidden_act=self.hidden_act ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,type_vocab_size=self.type_vocab_size ,is_decoder=__lowerCAmelCase ,initializer_range=self.initializer_range ,) def _lowercase ( self: int ,__lowerCAmelCase: Tuple ,__lowerCAmelCase: Union[str, Any] ,__lowerCAmelCase: int ,__lowerCAmelCase: Tuple ,__lowerCAmelCase: List[str] ,__lowerCAmelCase: List[Any] ,__lowerCAmelCase: Dict ): '''simple docstring''' _lowerCamelCase : Optional[int] = LlamaModel(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : int = model(__lowerCAmelCase ,attention_mask=__lowerCAmelCase ) _lowerCamelCase : Dict = model(__lowerCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _lowercase ( self: int ,__lowerCAmelCase: List[Any] ,__lowerCAmelCase: Any ,__lowerCAmelCase: int ,__lowerCAmelCase: str ,__lowerCAmelCase: Dict ,__lowerCAmelCase: Union[str, Any] ,__lowerCAmelCase: Optional[Any] ,__lowerCAmelCase: Tuple ,__lowerCAmelCase: int ,): '''simple docstring''' _lowerCamelCase : Union[str, Any] = True _lowerCamelCase : List[Any] = LlamaModel(__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Tuple = model( __lowerCAmelCase ,attention_mask=__lowerCAmelCase ,encoder_hidden_states=__lowerCAmelCase ,encoder_attention_mask=__lowerCAmelCase ,) _lowerCamelCase : List[str] = model( __lowerCAmelCase ,attention_mask=__lowerCAmelCase ,encoder_hidden_states=__lowerCAmelCase ,) _lowerCamelCase : Dict = model(__lowerCAmelCase ,attention_mask=__lowerCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _lowercase ( self: Optional[Any] ,__lowerCAmelCase: Tuple ,__lowerCAmelCase: Optional[Any] ,__lowerCAmelCase: List[Any] ,__lowerCAmelCase: Optional[int] ,__lowerCAmelCase: List[Any] ,__lowerCAmelCase: Union[str, Any] ,__lowerCAmelCase: Tuple ,__lowerCAmelCase: Any ,__lowerCAmelCase: List[str] ,): '''simple docstring''' _lowerCamelCase : Tuple = LlamaForCausalLM(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Any = model(__lowerCAmelCase ,attention_mask=__lowerCAmelCase ,labels=__lowerCAmelCase ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def _lowercase ( self: Union[str, Any] ,__lowerCAmelCase: int ,__lowerCAmelCase: Union[str, Any] ,__lowerCAmelCase: List[str] ,__lowerCAmelCase: Dict ,__lowerCAmelCase: Union[str, Any] ,__lowerCAmelCase: Optional[int] ,__lowerCAmelCase: Union[str, Any] ,__lowerCAmelCase: Any ,__lowerCAmelCase: Union[str, Any] ,): '''simple docstring''' _lowerCamelCase : Union[str, Any] = True _lowerCamelCase : Dict = True _lowerCamelCase : int = LlamaForCausalLM(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() # first forward pass _lowerCamelCase : Any = model( __lowerCAmelCase ,attention_mask=__lowerCAmelCase ,encoder_hidden_states=__lowerCAmelCase ,encoder_attention_mask=__lowerCAmelCase ,use_cache=__lowerCAmelCase ,) _lowerCamelCase : Union[str, Any] = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids _lowerCamelCase : Tuple = ids_tensor((self.batch_size, 3) ,config.vocab_size ) _lowerCamelCase : int = ids_tensor((self.batch_size, 3) ,vocab_size=2 ) # append to next input_ids and _lowerCamelCase : Optional[int] = torch.cat([input_ids, next_tokens] ,dim=-1 ) _lowerCamelCase : Optional[Any] = torch.cat([input_mask, next_mask] ,dim=-1 ) _lowerCamelCase : Tuple = model( __lowerCAmelCase ,attention_mask=__lowerCAmelCase ,encoder_hidden_states=__lowerCAmelCase ,encoder_attention_mask=__lowerCAmelCase ,output_hidden_states=__lowerCAmelCase ,)["hidden_states"][0] _lowerCamelCase : List[str] = model( __lowerCAmelCase ,attention_mask=__lowerCAmelCase ,encoder_hidden_states=__lowerCAmelCase ,encoder_attention_mask=__lowerCAmelCase ,past_key_values=__lowerCAmelCase ,output_hidden_states=__lowerCAmelCase ,)["hidden_states"][0] # select random slice _lowerCamelCase : Any = ids_tensor((1,) ,output_from_past.shape[-1] ).item() _lowerCamelCase : Tuple = output_from_no_past[:, -3:, random_slice_idx].detach() _lowerCamelCase : Dict = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(__lowerCAmelCase ,__lowerCAmelCase ,atol=1e-3 ) ) def _lowercase ( self: Optional[Any] ): '''simple docstring''' _lowerCamelCase : Optional[Any] = self.prepare_config_and_inputs() ( ( _lowerCamelCase ), ( _lowerCamelCase ), ( _lowerCamelCase ), ( _lowerCamelCase ), ( _lowerCamelCase ), ( _lowerCamelCase ), ( _lowerCamelCase ), ) : Dict = config_and_inputs _lowerCamelCase : Dict = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class A_ ( _a , _a , _a , unittest.TestCase ): lowerCAmelCase__ = (LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else () lowerCAmelCase__ = (LlamaForCausalLM,) if is_torch_available() else () lowerCAmelCase__ = ( { 'feature-extraction': LlamaModel, 'text-classification': LlamaForSequenceClassification, 'text-generation': LlamaForCausalLM, 'zero-shot': LlamaForSequenceClassification, } if is_torch_available() else {} ) lowerCAmelCase__ = False lowerCAmelCase__ = False def _lowercase ( self: str ): '''simple docstring''' _lowerCamelCase : List[str] = LlamaModelTester(self ) _lowerCamelCase : Optional[Any] = ConfigTester(self ,config_class=__lowerCAmelCase ,hidden_size=37 ) def _lowercase ( self: Union[str, Any] ): '''simple docstring''' self.config_tester.run_common_tests() def _lowercase ( self: Optional[int] ): '''simple docstring''' _lowerCamelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCAmelCase ) def _lowercase ( self: List[str] ): '''simple docstring''' _lowerCamelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: _lowerCamelCase : Any = type self.model_tester.create_and_check_model(*__lowerCAmelCase ) def _lowercase ( self: List[Any] ): '''simple docstring''' _lowerCamelCase, _lowerCamelCase : str = self.model_tester.prepare_config_and_inputs_for_common() _lowerCamelCase : List[Any] = 3 _lowerCamelCase : Optional[Any] = input_dict["input_ids"] _lowerCamelCase : List[str] = input_ids.ne(1 ).to(__lowerCAmelCase ) _lowerCamelCase : Any = ids_tensor([self.model_tester.batch_size] ,self.model_tester.type_sequence_label_size ) _lowerCamelCase : int = LlamaForSequenceClassification(__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Any = model(__lowerCAmelCase ,attention_mask=__lowerCAmelCase ,labels=__lowerCAmelCase ) self.assertEqual(result.logits.shape ,(self.model_tester.batch_size, self.model_tester.num_labels) ) def _lowercase ( self: str ): '''simple docstring''' _lowerCamelCase, _lowerCamelCase : Dict = self.model_tester.prepare_config_and_inputs_for_common() _lowerCamelCase : List[str] = 3 _lowerCamelCase : Optional[Any] = "single_label_classification" _lowerCamelCase : Union[str, Any] = input_dict["input_ids"] _lowerCamelCase : List[Any] = input_ids.ne(1 ).to(__lowerCAmelCase ) _lowerCamelCase : List[Any] = ids_tensor([self.model_tester.batch_size] ,self.model_tester.type_sequence_label_size ) _lowerCamelCase : Tuple = LlamaForSequenceClassification(__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : List[str] = model(__lowerCAmelCase ,attention_mask=__lowerCAmelCase ,labels=__lowerCAmelCase ) self.assertEqual(result.logits.shape ,(self.model_tester.batch_size, self.model_tester.num_labels) ) def _lowercase ( self: Optional[int] ): '''simple docstring''' _lowerCamelCase, _lowerCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() _lowerCamelCase : Any = 3 _lowerCamelCase : List[str] = "multi_label_classification" _lowerCamelCase : Union[str, Any] = input_dict["input_ids"] _lowerCamelCase : int = input_ids.ne(1 ).to(__lowerCAmelCase ) _lowerCamelCase : Optional[Any] = ids_tensor( [self.model_tester.batch_size, config.num_labels] ,self.model_tester.type_sequence_label_size ).to(torch.float ) _lowerCamelCase : Any = LlamaForSequenceClassification(__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : str = model(__lowerCAmelCase ,attention_mask=__lowerCAmelCase ,labels=__lowerCAmelCase ) self.assertEqual(result.logits.shape ,(self.model_tester.batch_size, self.model_tester.num_labels) ) @unittest.skip("LLaMA buffers include complex numbers, which breaks this test" ) def _lowercase ( self: Any ): '''simple docstring''' pass @parameterized.expand([("linear",), ("dynamic",)] ) def _lowercase ( self: Dict ,__lowerCAmelCase: Optional[Any] ): '''simple docstring''' _lowerCamelCase, _lowerCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() _lowerCamelCase : str = ids_tensor([1, 10] ,config.vocab_size ) _lowerCamelCase : Dict = ids_tensor([1, int(config.max_position_embeddings * 1.5 )] ,config.vocab_size ) set_seed(42 ) # Fixed seed at init time so the two models get the same random weights _lowerCamelCase : int = LlamaModel(__lowerCAmelCase ) original_model.to(__lowerCAmelCase ) original_model.eval() _lowerCamelCase : List[str] = original_model(__lowerCAmelCase ).last_hidden_state _lowerCamelCase : Any = original_model(__lowerCAmelCase ).last_hidden_state set_seed(42 ) # Fixed seed at init time so the two models get the same random weights _lowerCamelCase : List[Any] = {"type": scaling_type, "factor": 10.0} _lowerCamelCase : str = LlamaModel(__lowerCAmelCase ) scaled_model.to(__lowerCAmelCase ) scaled_model.eval() _lowerCamelCase : Any = scaled_model(__lowerCAmelCase ).last_hidden_state _lowerCamelCase : List[str] = scaled_model(__lowerCAmelCase ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(__lowerCAmelCase ,__lowerCAmelCase ,atol=1e-5 ) ) else: self.assertFalse(torch.allclose(__lowerCAmelCase ,__lowerCAmelCase ,atol=1e-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(__lowerCAmelCase ,__lowerCAmelCase ,atol=1e-5 ) ) @require_torch class A_ ( unittest.TestCase ): @unittest.skip("Logits are not exactly the same, once we fix the instabalities somehow, will update!" ) @slow def _lowercase ( self: Optional[int] ): '''simple docstring''' _lowerCamelCase : Tuple = [1, 306, 4_658, 278, 6_593, 310, 2_834, 338] _lowerCamelCase : List[Any] = LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf" ,device_map="auto" ) _lowerCamelCase : List[str] = model(torch.tensor([input_ids] ) ) # Expected mean on dim = -1 _lowerCamelCase : Any = torch.tensor([[-6.65_50, -4.12_27, -4.98_59, -3.24_06, 0.82_62, -3.00_33, 1.29_64, -3.36_99]] ) torch.testing.assert_close(out.mean(-1 ) ,__lowerCAmelCase ,atol=1e-2 ,rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off _lowerCamelCase : Dict = torch.tensor([-12.82_81, -7.44_53, -0.46_39, -8.06_25, -7.25_00, -8.00_00, -6.48_83, -7.76_95, -7.84_38, -7.03_12, -6.21_88, -7.13_28, -1.84_96, 1.99_61, -8.62_50, -6.72_27, -12.82_81, -6.94_92, -7.07_42, -7.78_52, -7.58_20, -7.90_62, -6.93_75, -7.98_05, -8.34_38, -8.15_62, -8.04_69, -7.62_50, -7.74_22, -7.33_98,] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] ,__lowerCAmelCase ,atol=1e-5 ,rtol=1e-5 ) @unittest.skip("Logits are not exactly the same, once we fix the instabalities somehow, will update!" ) @slow def _lowercase ( self: int ): '''simple docstring''' _lowerCamelCase : List[str] = [1, 306, 4_658, 278, 6_593, 310, 2_834, 338] _lowerCamelCase : Dict = LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-13b-hf" ,device_map="auto" ) _lowerCamelCase : Dict = model(torch.tensor(__lowerCAmelCase ) ) # Expected mean on dim = -1 _lowerCamelCase : List[str] = torch.tensor([[-2.06_22, -1.27_94, -1.16_38, -0.97_88, -1.46_03, -1.02_38, -1.78_93, -1.44_11]] ) torch.testing.assert_close(out.mean(-1 ) ,__lowerCAmelCase ,atol=1e-2 ,rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off _lowerCamelCase : Union[str, Any] = torch.tensor([-8.14_06, -8.05_47, 2.74_61, -1.23_44, -0.14_48, -1.82_62, -1.00_20, -1.81_54, -1.68_95, -1.85_16, -2.35_74, -0.92_77, 3.75_98, 6.57_42, -1.29_98, -0.11_77, -8.14_06, -2.96_88, -2.91_99, -3.16_99, -3.52_54, -2.35_55, -2.79_88, -3.41_41, -2.82_62, -4.51_95, -3.33_79, -3.31_64, -2.78_32, -3.02_73] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] ,__lowerCAmelCase ,atol=1e-5 ,rtol=1e-5 ) @unittest.skip("Logits are not exactly the same, once we fix the instabalities somehow, will update!" ) @slow def _lowercase ( self: Optional[int] ): '''simple docstring''' _lowerCamelCase : Optional[int] = [1, 306, 4_658, 278, 6_593, 310, 2_834, 338] _lowerCamelCase : Union[str, Any] = LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-13b-chat-hf" ,device_map="auto" ) _lowerCamelCase : List[Any] = model(torch.tensor(__lowerCAmelCase ) ) # Expected mean on dim = -1 _lowerCamelCase : Union[str, Any] = torch.tensor([[-0.85_62, -1.85_20, -0.75_51, -0.41_62, -1.51_61, -1.20_38, -2.48_23, -2.32_54]] ) torch.testing.assert_close(out.mean(-1 ) ,__lowerCAmelCase ,atol=1e-2 ,rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off _lowerCamelCase : Any = torch.tensor([-2.22_27, 4.88_28, 0.90_23, -0.45_78, -0.78_71, -0.10_33, -0.62_21, -0.57_86, -0.78_03, -1.06_74, -1.29_20, -0.15_70, 0.80_08, 2.07_23, -0.94_97, 0.27_71, -2.22_27, -0.76_12, -1.43_46, -1.20_61, -1.64_26, -0.30_00, -0.71_39, -1.19_34, -1.86_91, -1.69_73, -1.59_47, -1.27_05, -0.35_23, -0.55_13] ) # fmt: on torch.testing.assert_close(out.mean(-1 ) ,__lowerCAmelCase ,atol=1e-2 ,rtol=1e-2 ) @unittest.skip( "Logits are not exactly the same, once we fix the instabalities somehow, will update! Also it is gonna be a `too_slow` test" ) @slow def _lowercase ( self: Tuple ): '''simple docstring''' _lowerCamelCase : str = [1, 306, 4_658, 278, 6_593, 310, 2_834, 338] _lowerCamelCase : List[Any] = LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-70b-hf" ,device_map="auto" ) _lowerCamelCase : Dict = model(torch.tensor(__lowerCAmelCase ) ) _lowerCamelCase : Any = torch.tensor( [[-4.23_27, -3.33_60, -4.66_65, -4.76_31, -1.81_80, -3.41_70, -1.42_11, -3.18_10]] ,dtype=torch.floataa ) torch.testing.assert_close(out.mean(-1 ) ,__lowerCAmelCase ,atol=1e-2 ,rtol=1e-2 ) # fmt: off _lowerCamelCase : str = torch.tensor([-9.49_22, -3.95_51, 1.79_98, -5.67_58, -5.10_55, -5.89_84, -4.83_20, -6.80_86, -6.53_91, -5.61_72, -5.58_20, -5.53_52, 1.78_81, 3.62_89, -6.51_17, -3.47_85, -9.50_00, -6.03_52, -6.81_25, -6.01_95, -6.68_36, -5.47_27, -6.28_12, -6.03_91, -7.33_98, -7.42_97, -7.48_44, -6.58_20, -5.87_89, -5.53_12] ) # fmt: on torch.testing.assert_close(out[0, 0, :30] ,__lowerCAmelCase ,atol=1e-5 ,rtol=1e-5 ) @unittest.skip("Model is curently gated" ) @slow def _lowercase ( self: Dict ): '''simple docstring''' _lowerCamelCase : Optional[int] = "Simply put, the theory of relativity states that 1) the laws of physics are the same everywhere in the universe and 2) the passage of time and the length of objects can vary depending on the observer\'s frame of reference.\n\nThe first part of the theory, that the laws of physics are the same everywhere, is known as the \"princi" _lowerCamelCase : Tuple = "Simply put, the theory of relativity states that " _lowerCamelCase : Tuple = LlamaTokenizer.from_pretrained("meta-llama/Llama-2-13b-chat-hf" ) _lowerCamelCase : List[str] = tokenizer.encode(__lowerCAmelCase ,return_tensors="pt" ) _lowerCamelCase : Optional[Any] = LlamaForCausalLM.from_pretrained( "meta-llama/Llama-2-13b-chat-hf" ,device_map="sequential" ,use_safetensors=__lowerCAmelCase ) # greedy generation outputs _lowerCamelCase : Optional[Any] = model.generate(__lowerCAmelCase ,max_new_tokens=64 ,top_p=__lowerCAmelCase ,temperature=1 ,do_sample=__lowerCAmelCase ) _lowerCamelCase : Union[str, Any] = tokenizer.decode(generated_ids[0] ,skip_special_tokens=__lowerCAmelCase ) self.assertEqual(__lowerCAmelCase ,__lowerCAmelCase )
46
import argparse import json import os from collections import OrderedDict import torch from transformers import LukeConfig, LukeForMaskedLM, MLukeTokenizer, XLMRobertaTokenizer from transformers.tokenization_utils_base import AddedToken @torch.no_grad() def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) -> int: # Load configuration defined in the metadata file with open(UpperCAmelCase__ ) as metadata_file: UpperCamelCase_: Tuple = json.load(UpperCAmelCase__ ) UpperCamelCase_: List[str] = LukeConfig(use_entity_aware_attention=UpperCAmelCase__ , **metadata['model_config'] ) # Load in the weights from the checkpoint_path UpperCamelCase_: Optional[int] = torch.load(UpperCAmelCase__ , map_location='cpu' )['module'] # Load the entity vocab file UpperCamelCase_: Any = load_original_entity_vocab(UpperCAmelCase__ ) # add an entry for [MASK2] UpperCamelCase_: List[str] = max(entity_vocab.values() ) + 1 config.entity_vocab_size += 1 UpperCamelCase_: Union[str, Any] = XLMRobertaTokenizer.from_pretrained(metadata['model_config']['bert_model_name'] ) # Add special tokens to the token vocabulary for downstream tasks UpperCamelCase_: Any = AddedToken('<ent>' , lstrip=UpperCAmelCase__ , rstrip=UpperCAmelCase__ ) UpperCamelCase_: Optional[Any] = AddedToken('<ent2>' , lstrip=UpperCAmelCase__ , rstrip=UpperCAmelCase__ ) 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(UpperCAmelCase__ ) with open(os.path.join(UpperCAmelCase__ , 'tokenizer_config.json' ) , 'r' ) as f: UpperCamelCase_: Union[str, Any] = json.load(UpperCAmelCase__ ) UpperCamelCase_: str = 'MLukeTokenizer' with open(os.path.join(UpperCAmelCase__ , 'tokenizer_config.json' ) , 'w' ) as f: json.dump(UpperCAmelCase__ , UpperCAmelCase__ ) with open(os.path.join(UpperCAmelCase__ , MLukeTokenizer.vocab_files_names['entity_vocab_file'] ) , 'w' ) as f: json.dump(UpperCAmelCase__ , UpperCAmelCase__ ) UpperCamelCase_: Optional[Any] = MLukeTokenizer.from_pretrained(UpperCAmelCase__ ) # Initialize the embeddings of the special tokens UpperCamelCase_: Any = tokenizer.convert_tokens_to_ids(['@'] )[0] UpperCamelCase_: List[str] = tokenizer.convert_tokens_to_ids(['#'] )[0] UpperCamelCase_: Tuple = state_dict['embeddings.word_embeddings.weight'] UpperCamelCase_: int = word_emb[ent_init_index].unsqueeze(0 ) UpperCamelCase_: Any = word_emb[enta_init_index].unsqueeze(0 ) UpperCamelCase_: str = torch.cat([word_emb, ent_emb, enta_emb] ) # add special tokens for 'entity_predictions.bias' for bias_name in ["lm_head.decoder.bias", "lm_head.bias"]: UpperCamelCase_: Union[str, Any] = state_dict[bias_name] UpperCamelCase_: Tuple = decoder_bias[ent_init_index].unsqueeze(0 ) UpperCamelCase_: Any = decoder_bias[enta_init_index].unsqueeze(0 ) UpperCamelCase_: Optional[Any] = torch.cat([decoder_bias, ent_decoder_bias, enta_decoder_bias] ) # 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_: List[Any] = F'''encoder.layer.{layer_index}.attention.self.''' UpperCamelCase_: str = state_dict[prefix + matrix_name] UpperCamelCase_: Dict = state_dict[prefix + matrix_name] UpperCamelCase_: Dict = state_dict[prefix + matrix_name] # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks UpperCamelCase_: List[str] = state_dict['entity_embeddings.entity_embeddings.weight'] UpperCamelCase_: int = entity_emb[entity_vocab['[MASK]']].unsqueeze(0 ) UpperCamelCase_: Tuple = torch.cat([entity_emb, entity_mask_emb] ) # add [MASK2] for 'entity_predictions.bias' UpperCamelCase_: Optional[Any] = state_dict['entity_predictions.bias'] UpperCamelCase_: List[str] = entity_prediction_bias[entity_vocab['[MASK]']].unsqueeze(0 ) UpperCamelCase_: List[Any] = torch.cat([entity_prediction_bias, entity_mask_bias] ) UpperCamelCase_: List[Any] = LukeForMaskedLM(config=UpperCAmelCase__ ).eval() state_dict.pop('entity_predictions.decoder.weight' ) state_dict.pop('lm_head.decoder.weight' ) state_dict.pop('lm_head.decoder.bias' ) UpperCamelCase_: Optional[Any] = OrderedDict() for key, value in state_dict.items(): if not (key.startswith('lm_head' ) or key.startswith('entity_predictions' )): UpperCamelCase_: Union[str, Any] = state_dict[key] else: UpperCamelCase_: Dict = state_dict[key] UpperCamelCase_ ,UpperCamelCase_: Optional[int] = model.load_state_dict(UpperCAmelCase__ , strict=UpperCAmelCase__ ) if set(UpperCAmelCase__ ) != {"luke.embeddings.position_ids"}: raise ValueError(F'''Unexpected unexpected_keys: {unexpected_keys}''' ) if set(UpperCAmelCase__ ) != { "lm_head.decoder.weight", "lm_head.decoder.bias", "entity_predictions.decoder.weight", }: raise ValueError(F'''Unexpected missing_keys: {missing_keys}''' ) model.tie_weights() assert (model.luke.embeddings.word_embeddings.weight == model.lm_head.decoder.weight).all() assert (model.luke.entity_embeddings.entity_embeddings.weight == model.entity_predictions.decoder.weight).all() # Check outputs UpperCamelCase_: Optional[int] = MLukeTokenizer.from_pretrained(UpperCAmelCase__ , task='entity_classification' ) UpperCamelCase_: Tuple = 'ISO 639-3 uses the code fas for the dialects spoken across Iran and アフガニスタン (Afghanistan).' UpperCamelCase_: Optional[int] = (0, 9) UpperCamelCase_: Union[str, Any] = tokenizer(UpperCAmelCase__ , entity_spans=[span] , return_tensors='pt' ) UpperCamelCase_: str = model(**UpperCAmelCase__ ) # Verify word hidden states if model_size == "large": raise NotImplementedError else: # base UpperCamelCase_: int = torch.Size((1, 3_3, 7_6_8) ) UpperCamelCase_: Tuple = torch.tensor([[0.0892, 0.0596, -0.2819], [0.0134, 0.1199, 0.0573], [-0.0169, 0.0927, 0.0644]] ) 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] , UpperCAmelCase__ , atol=1E-4 ): raise ValueError # Verify entity hidden states if model_size == "large": raise NotImplementedError else: # base UpperCamelCase_: Dict = torch.Size((1, 1, 7_6_8) ) UpperCamelCase_: Tuple = torch.tensor([[-0.1482, 0.0609, 0.0322]] ) 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] , UpperCAmelCase__ , atol=1E-4 ): raise ValueError # Verify masked word/entity prediction UpperCamelCase_: str = MLukeTokenizer.from_pretrained(UpperCAmelCase__ ) UpperCamelCase_: int = 'Tokyo is the capital of <mask>.' UpperCamelCase_: Dict = (2_4, 3_0) UpperCamelCase_: int = tokenizer(UpperCAmelCase__ , entity_spans=[span] , return_tensors='pt' ) UpperCamelCase_: Dict = model(**UpperCAmelCase__ ) UpperCamelCase_: Optional[int] = encoding['input_ids'][0].tolist() UpperCamelCase_: List[Any] = input_ids.index(tokenizer.convert_tokens_to_ids('<mask>' ) ) UpperCamelCase_: Any = outputs.logits[0][mask_position_id].argmax(dim=-1 ) assert "Japan" == tokenizer.decode(UpperCAmelCase__ ) UpperCamelCase_: Union[str, Any] = outputs.entity_logits[0][0].argmax().item() UpperCamelCase_: Optional[Any] = [ entity for entity, entity_id in tokenizer.entity_vocab.items() if entity_id == predicted_entity_id ] assert [e for e in multilingual_predicted_entities if e.startswith('en:' )][0] == "en:Japan" # Finally, save our PyTorch model and tokenizer print('Saving PyTorch model to {}'.format(UpperCAmelCase__ ) ) model.save_pretrained(UpperCAmelCase__ ) def snake_case (UpperCAmelCase__ ) -> int: UpperCamelCase_: Optional[Any] = ['[MASK]', '[PAD]', '[UNK]'] UpperCamelCase_: Any = [json.loads(UpperCAmelCase__ ) for line in open(UpperCAmelCase__ )] UpperCamelCase_: Tuple = {} for entry in data: UpperCamelCase_: Optional[int] = entry['id'] for entity_name, language in entry["entities"]: if entity_name in SPECIAL_TOKENS: UpperCamelCase_: Union[str, Any] = entity_id break UpperCamelCase_: Dict = F'''{language}:{entity_name}''' UpperCamelCase_: Optional[int] = entity_id return new_mapping if __name__ == "__main__": A_ : Tuple = 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_ : List[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, )
57
0
import torch from diffusers import DDIMParallelScheduler from .test_schedulers import SchedulerCommonTest class _UpperCamelCase( __lowerCamelCase ): __SCREAMING_SNAKE_CASE : int = (DDIMParallelScheduler,) __SCREAMING_SNAKE_CASE : Union[str, Any] = (('''eta''', 0.0), ('''num_inference_steps''', 50)) def __lowerCAmelCase ( self : str , **SCREAMING_SNAKE_CASE__ : Optional[int] ): '''simple docstring''' __a : List[Any] = { 'num_train_timesteps': 1_0_0_0, 'beta_start': 0.0_001, 'beta_end': 0.02, 'beta_schedule': 'linear', 'clip_sample': True, } config.update(**SCREAMING_SNAKE_CASE__ ) return config def __lowerCAmelCase ( self : str , **SCREAMING_SNAKE_CASE__ : Optional[int] ): '''simple docstring''' __a : Tuple = self.scheduler_classes[0] __a : Optional[Any] = self.get_scheduler_config(**SCREAMING_SNAKE_CASE__ ) __a : Any = scheduler_class(**SCREAMING_SNAKE_CASE__ ) __a , __a : List[str] = 1_0, 0.0 __a : Dict = self.dummy_model() __a : str = self.dummy_sample_deter scheduler.set_timesteps(SCREAMING_SNAKE_CASE__ ) for t in scheduler.timesteps: __a : str = model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __a : List[str] = scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ).prev_sample return sample def __lowerCAmelCase ( self : Tuple ): '''simple docstring''' for timesteps in [1_0_0, 5_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Dict ): '''simple docstring''' for steps_offset in [0, 1]: self.check_over_configs(steps_offset=SCREAMING_SNAKE_CASE__ ) __a : Optional[Any] = self.scheduler_classes[0] __a : List[str] = self.get_scheduler_config(steps_offset=1 ) __a : Optional[Any] = scheduler_class(**SCREAMING_SNAKE_CASE__ ) scheduler.set_timesteps(5 ) assert torch.equal(scheduler.timesteps , torch.LongTensor([8_0_1, 6_0_1, 4_0_1, 2_0_1, 1] ) ) def __lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' for beta_start, beta_end in zip([0.0_001, 0.001, 0.01, 0.1] , [0.002, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=SCREAMING_SNAKE_CASE__ , beta_end=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : int ): '''simple docstring''' for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Optional[Any] ): '''simple docstring''' for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : List[Any] ): '''simple docstring''' for clip_sample in [True, False]: self.check_over_configs(clip_sample=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Optional[Any] ): '''simple docstring''' for timestep_spacing in ["trailing", "leading"]: self.check_over_configs(timestep_spacing=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : int ): '''simple docstring''' for rescale_betas_zero_snr in [True, False]: self.check_over_configs(rescale_betas_zero_snr=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : str ): '''simple docstring''' self.check_over_configs(thresholding=SCREAMING_SNAKE_CASE__ ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs( thresholding=SCREAMING_SNAKE_CASE__ , prediction_type=SCREAMING_SNAKE_CASE__ , sample_max_value=SCREAMING_SNAKE_CASE__ , ) def __lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' for t in [1, 1_0, 4_9]: self.check_over_forward(time_step=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : List[str] ): '''simple docstring''' for t, num_inference_steps in zip([1, 1_0, 5_0] , [1_0, 5_0, 5_0_0] ): self.check_over_forward(time_step=SCREAMING_SNAKE_CASE__ , num_inference_steps=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : List[Any] ): '''simple docstring''' for t, eta in zip([1, 1_0, 4_9] , [0.0, 0.5, 1.0] ): self.check_over_forward(time_step=SCREAMING_SNAKE_CASE__ , eta=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : List[Any] ): '''simple docstring''' __a : List[str] = self.scheduler_classes[0] __a : Union[str, Any] = self.get_scheduler_config() __a : Any = scheduler_class(**SCREAMING_SNAKE_CASE__ ) assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(4_2_0 , 4_0_0 ) - 0.14_771 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(9_8_0 , 9_6_0 ) - 0.32_460 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(4_8_7 , 4_8_6 ) - 0.00_979 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(9_9_9 , 9_9_8 ) - 0.02 ) ) < 1e-5 def __lowerCAmelCase ( self : Optional[Any] ): '''simple docstring''' __a : List[str] = self.scheduler_classes[0] __a : List[str] = self.get_scheduler_config() __a : Optional[Any] = scheduler_class(**SCREAMING_SNAKE_CASE__ ) __a , __a : Any = 1_0, 0.0 scheduler.set_timesteps(SCREAMING_SNAKE_CASE__ ) __a : List[Any] = self.dummy_model() __a : int = self.dummy_sample_deter __a : List[Any] = self.dummy_sample_deter + 0.1 __a : List[str] = self.dummy_sample_deter - 0.1 __a : Optional[Any] = samplea.shape[0] __a : Optional[Any] = torch.stack([samplea, samplea, samplea] , dim=0 ) __a : Union[str, Any] = torch.arange(SCREAMING_SNAKE_CASE__ )[0:3, None].repeat(1 , SCREAMING_SNAKE_CASE__ ) __a : int = model(samples.flatten(0 , 1 ) , timesteps.flatten(0 , 1 ) ) __a : int = scheduler.batch_step_no_noise(SCREAMING_SNAKE_CASE__ , timesteps.flatten(0 , 1 ) , samples.flatten(0 , 1 ) , SCREAMING_SNAKE_CASE__ ) __a : Dict = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) __a : Optional[Any] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) assert abs(result_sum.item() - 1_147.7_904 ) < 1e-2 assert abs(result_mean.item() - 0.4_982 ) < 1e-3 def __lowerCAmelCase ( self : str ): '''simple docstring''' __a : List[str] = self.full_loop() __a : Tuple = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) __a : int = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) assert abs(result_sum.item() - 172.0_067 ) < 1e-2 assert abs(result_mean.item() - 0.223_967 ) < 1e-3 def __lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' __a : Optional[int] = self.full_loop(prediction_type='v_prediction' ) __a : str = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) __a : Union[str, Any] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) assert abs(result_sum.item() - 52.5_302 ) < 1e-2 assert abs(result_mean.item() - 0.0_684 ) < 1e-3 def __lowerCAmelCase ( self : int ): '''simple docstring''' __a : Union[str, Any] = self.full_loop(set_alpha_to_one=SCREAMING_SNAKE_CASE__ , beta_start=0.01 ) __a : Optional[int] = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) __a : Optional[int] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) assert abs(result_sum.item() - 149.8_295 ) < 1e-2 assert abs(result_mean.item() - 0.1_951 ) < 1e-3 def __lowerCAmelCase ( self : str ): '''simple docstring''' __a : Dict = self.full_loop(set_alpha_to_one=SCREAMING_SNAKE_CASE__ , beta_start=0.01 ) __a : str = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) __a : Tuple = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) assert abs(result_sum.item() - 149.0_784 ) < 1e-2 assert abs(result_mean.item() - 0.1_941 ) < 1e-3
47
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A_ : Optional[Any] = logging.get_logger(__name__) A_ : Optional[Any] = { 'distilbert-base-uncased': 'https://huggingface.co/distilbert-base-uncased/resolve/main/config.json', 'distilbert-base-uncased-distilled-squad': ( 'https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/config.json' ), 'distilbert-base-cased': 'https://huggingface.co/distilbert-base-cased/resolve/main/config.json', 'distilbert-base-cased-distilled-squad': ( 'https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/config.json' ), 'distilbert-base-german-cased': 'https://huggingface.co/distilbert-base-german-cased/resolve/main/config.json', 'distilbert-base-multilingual-cased': ( 'https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/config.json' ), 'distilbert-base-uncased-finetuned-sst-2-english': ( 'https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-english/resolve/main/config.json' ), } class _lowerCAmelCase( UpperCAmelCase_ ): """simple docstring""" a : Dict ='''distilbert''' a : List[str] ={ '''hidden_size''': '''dim''', '''num_attention_heads''': '''n_heads''', '''num_hidden_layers''': '''n_layers''', } def __init__( self , _lowerCamelCase=3_0_5_2_2 , _lowerCamelCase=5_1_2 , _lowerCamelCase=False , _lowerCamelCase=6 , _lowerCamelCase=1_2 , _lowerCamelCase=7_6_8 , _lowerCamelCase=4 * 7_6_8 , _lowerCamelCase=0.1 , _lowerCamelCase=0.1 , _lowerCamelCase="gelu" , _lowerCamelCase=0.0_2 , _lowerCamelCase=0.1 , _lowerCamelCase=0.2 , _lowerCamelCase=0 , **_lowerCamelCase , ): UpperCamelCase_: Tuple = vocab_size UpperCamelCase_: str = max_position_embeddings UpperCamelCase_: Optional[int] = sinusoidal_pos_embds UpperCamelCase_: Union[str, Any] = n_layers UpperCamelCase_: Optional[int] = n_heads UpperCamelCase_: int = dim UpperCamelCase_: Tuple = hidden_dim UpperCamelCase_: Any = dropout UpperCamelCase_: Optional[Any] = attention_dropout UpperCamelCase_: List[str] = activation UpperCamelCase_: Optional[Any] = initializer_range UpperCamelCase_: Optional[Any] = qa_dropout UpperCamelCase_: List[str] = seq_classif_dropout super().__init__(**_lowerCamelCase , pad_token_id=_lowerCamelCase ) class _lowerCAmelCase( UpperCAmelCase_ ): """simple docstring""" @property def _a ( self ): if self.task == "multiple-choice": UpperCamelCase_: Any = {0: 'batch', 1: 'choice', 2: 'sequence'} else: UpperCamelCase_: List[Any] = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
57
0
'''simple docstring''' import argparse from transformers import BigBirdConfig, BigBirdForPreTraining, BigBirdForQuestionAnswering, load_tf_weights_in_big_bird from transformers.utils import logging logging.set_verbosity_info() def A ( UpperCamelCase_ : Optional[int] , UpperCamelCase_ : Dict , UpperCamelCase_ : Dict , UpperCamelCase_ : int ) -> Any: '''simple docstring''' lowerCAmelCase__ = BigBirdConfig.from_json_file(UpperCamelCase_ ) print(F"""Building PyTorch model from configuration: {config}""" ) if is_trivia_qa: lowerCAmelCase__ = BigBirdForQuestionAnswering(UpperCamelCase_ ) else: lowerCAmelCase__ = BigBirdForPreTraining(UpperCamelCase_ ) # Load weights from tf checkpoint load_tf_weights_in_big_bird(UpperCamelCase_ , UpperCamelCase_ , is_trivia_qa=UpperCamelCase_ ) # Save pytorch-model print(F"""Save PyTorch model to {pytorch_dump_path}""" ) model.save_pretrained(UpperCamelCase_ ) if __name__ == "__main__": UpperCAmelCase__ : Union[str, Any] = 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( "--big_bird_config_file", default=None, type=str, required=True, help=( "The config json file corresponding to the pre-trained BERT 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." ) parser.add_argument( "--is_trivia_qa", action="store_true", help="Whether to convert a model with a trivia_qa head." ) UpperCAmelCase__ : int = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.tf_checkpoint_path, args.big_bird_config_file, args.pytorch_dump_path, args.is_trivia_qa )
48
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A_ : int = { 'configuration_lilt': ['LILT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LiltConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : Any = [ 'LILT_PRETRAINED_MODEL_ARCHIVE_LIST', 'LiltForQuestionAnswering', 'LiltForSequenceClassification', 'LiltForTokenClassification', 'LiltModel', 'LiltPreTrainedModel', ] if TYPE_CHECKING: from .configuration_lilt import LILT_PRETRAINED_CONFIG_ARCHIVE_MAP, LiltConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_lilt import ( LILT_PRETRAINED_MODEL_ARCHIVE_LIST, LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, LiltPreTrainedModel, ) else: import sys A_ : Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
57
0
"""simple docstring""" import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, CycleDiffusionPipeline, DDIMScheduler, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class _UpperCAmelCase ( _lowerCAmelCase , _lowerCAmelCase , unittest.TestCase ): a__ : List[str] = CycleDiffusionPipeline a__ : Optional[int] = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - { "negative_prompt", "height", "width", "negative_prompt_embeds", } a__ : Optional[int] = PipelineTesterMixin.required_optional_params - {"latents"} a__ : Optional[Any] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"source_prompt"} ) a__ : List[str] = IMAGE_TO_IMAGE_IMAGE_PARAMS a__ : str = IMAGE_TO_IMAGE_IMAGE_PARAMS def a ( self : Optional[int] ): torch.manual_seed(0 ) __UpperCAmelCase = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') , cross_attention_dim=32 , ) __UpperCAmelCase = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule='''scaled_linear''' , num_train_timesteps=10_00 , clip_sample=_lowercase , set_alpha_to_one=_lowercase , ) torch.manual_seed(0 ) __UpperCAmelCase = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , ) torch.manual_seed(0 ) __UpperCAmelCase = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , ) __UpperCAmelCase = CLIPTextModel(_lowercase ) __UpperCAmelCase = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) __UpperCAmelCase = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''safety_checker''': None, '''feature_extractor''': None, } return components def a ( self : Any , _lowercase : List[Any] , _lowercase : Optional[Any]=0 ): __UpperCAmelCase = floats_tensor((1, 3, 32, 32) , rng=random.Random(_lowercase ) ).to(_lowercase ) __UpperCAmelCase = image / 2 + 0.5 if str(_lowercase ).startswith('''mps''' ): __UpperCAmelCase = torch.manual_seed(_lowercase ) else: __UpperCAmelCase = torch.Generator(device=_lowercase ).manual_seed(_lowercase ) __UpperCAmelCase = { '''prompt''': '''An astronaut riding an elephant''', '''source_prompt''': '''An astronaut riding a horse''', '''image''': image, '''generator''': generator, '''num_inference_steps''': 2, '''eta''': 0.1, '''strength''': 0.8, '''guidance_scale''': 3, '''source_guidance_scale''': 1, '''output_type''': '''numpy''', } return inputs def a ( self : Optional[int] ): __UpperCAmelCase = '''cpu''' # ensure determinism for the device-dependent torch.Generator __UpperCAmelCase = self.get_dummy_components() __UpperCAmelCase = CycleDiffusionPipeline(**_lowercase ) __UpperCAmelCase = pipe.to(_lowercase ) pipe.set_progress_bar_config(disable=_lowercase ) __UpperCAmelCase = self.get_dummy_inputs(_lowercase ) __UpperCAmelCase = pipe(**_lowercase ) __UpperCAmelCase = output.images __UpperCAmelCase = images[0, -3:, -3:, -1] assert images.shape == (1, 32, 32, 3) __UpperCAmelCase = np.array([0.4_459, 0.4_943, 0.4_544, 0.6_643, 0.5_474, 0.4_327, 0.5_701, 0.5_959, 0.5_179] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 @unittest.skipIf(torch_device != '''cuda''' , '''This test requires a GPU''' ) def a ( self : Optional[int] ): __UpperCAmelCase = self.get_dummy_components() for name, module in components.items(): if hasattr(_lowercase , '''half''' ): __UpperCAmelCase = module.half() __UpperCAmelCase = CycleDiffusionPipeline(**_lowercase ) __UpperCAmelCase = pipe.to(_lowercase ) pipe.set_progress_bar_config(disable=_lowercase ) __UpperCAmelCase = self.get_dummy_inputs(_lowercase ) __UpperCAmelCase = pipe(**_lowercase ) __UpperCAmelCase = output.images __UpperCAmelCase = images[0, -3:, -3:, -1] assert images.shape == (1, 32, 32, 3) __UpperCAmelCase = np.array([0.3_506, 0.4_543, 0.446, 0.4_575, 0.5_195, 0.4_155, 0.5_273, 0.518, 0.4_116] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 @skip_mps def a ( self : Tuple ): return super().test_save_load_local() @unittest.skip('''non-deterministic pipeline''' ) def a ( self : List[str] ): return super().test_inference_batch_single_identical() @skip_mps def a ( self : int ): return super().test_dict_tuple_outputs_equivalent() @skip_mps def a ( self : str ): return super().test_save_load_optional_components() @skip_mps def a ( self : int ): return super().test_attention_slicing_forward_pass() @slow @require_torch_gpu class _UpperCAmelCase ( unittest.TestCase ): def a ( self : List[str] ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def a ( self : int ): __UpperCAmelCase = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/cycle-diffusion/black_colored_car.png''' ) __UpperCAmelCase = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car_fp16.npy''' ) __UpperCAmelCase = init_image.resize((5_12, 5_12) ) __UpperCAmelCase = '''CompVis/stable-diffusion-v1-4''' __UpperCAmelCase = DDIMScheduler.from_pretrained(_lowercase , subfolder='''scheduler''' ) __UpperCAmelCase = CycleDiffusionPipeline.from_pretrained( _lowercase , scheduler=_lowercase , safety_checker=_lowercase , torch_dtype=torch.floataa , revision='''fp16''' ) pipe.to(_lowercase ) pipe.set_progress_bar_config(disable=_lowercase ) pipe.enable_attention_slicing() __UpperCAmelCase = '''A black colored car''' __UpperCAmelCase = '''A blue colored car''' __UpperCAmelCase = torch.manual_seed(0 ) __UpperCAmelCase = pipe( prompt=_lowercase , source_prompt=_lowercase , image=_lowercase , num_inference_steps=1_00 , eta=0.1 , strength=0.85 , guidance_scale=3 , source_guidance_scale=1 , generator=_lowercase , output_type='''np''' , ) __UpperCAmelCase = output.images # the values aren't exactly equal, but the images look the same visually assert np.abs(image - expected_image ).max() < 5E-1 def a ( self : Optional[Any] ): __UpperCAmelCase = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/cycle-diffusion/black_colored_car.png''' ) __UpperCAmelCase = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car.npy''' ) __UpperCAmelCase = init_image.resize((5_12, 5_12) ) __UpperCAmelCase = '''CompVis/stable-diffusion-v1-4''' __UpperCAmelCase = DDIMScheduler.from_pretrained(_lowercase , subfolder='''scheduler''' ) __UpperCAmelCase = CycleDiffusionPipeline.from_pretrained(_lowercase , scheduler=_lowercase , safety_checker=_lowercase ) pipe.to(_lowercase ) pipe.set_progress_bar_config(disable=_lowercase ) pipe.enable_attention_slicing() __UpperCAmelCase = '''A black colored car''' __UpperCAmelCase = '''A blue colored car''' __UpperCAmelCase = torch.manual_seed(0 ) __UpperCAmelCase = pipe( prompt=_lowercase , source_prompt=_lowercase , image=_lowercase , num_inference_steps=1_00 , eta=0.1 , strength=0.85 , guidance_scale=3 , source_guidance_scale=1 , generator=_lowercase , output_type='''np''' , ) __UpperCAmelCase = output.images assert np.abs(image - expected_image ).max() < 2E-2
49
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available A_ : List[str] = { 'configuration_roc_bert': ['ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'RoCBertConfig'], 'tokenization_roc_bert': ['RoCBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: pass try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : Union[str, Any] = [ 'ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'RoCBertForCausalLM', 'RoCBertForMaskedLM', 'RoCBertForMultipleChoice', 'RoCBertForPreTraining', 'RoCBertForQuestionAnswering', 'RoCBertForSequenceClassification', 'RoCBertForTokenClassification', 'RoCBertLayer', 'RoCBertModel', 'RoCBertPreTrainedModel', 'load_tf_weights_in_roc_bert', ] if TYPE_CHECKING: from .configuration_roc_bert import ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RoCBertConfig from .tokenization_roc_bert import RoCBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: raise OptionalDependencyNotAvailable() try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roc_bert import ( ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, RoCBertForCausalLM, RoCBertForMaskedLM, RoCBertForMultipleChoice, RoCBertForPreTraining, RoCBertForQuestionAnswering, RoCBertForSequenceClassification, RoCBertForTokenClassification, RoCBertLayer, RoCBertModel, RoCBertPreTrainedModel, load_tf_weights_in_roc_bert, ) else: import sys A_ : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
57
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available UpperCamelCase : Any = { 'configuration_altclip': [ 'ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP', 'AltCLIPConfig', 'AltCLIPTextConfig', 'AltCLIPVisionConfig', ], 'processing_altclip': ['AltCLIPProcessor'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase : List[str] = [ 'ALTCLIP_PRETRAINED_MODEL_ARCHIVE_LIST', 'AltCLIPPreTrainedModel', 'AltCLIPModel', 'AltCLIPTextModel', 'AltCLIPVisionModel', ] if TYPE_CHECKING: from .configuration_altclip import ( ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, AltCLIPConfig, AltCLIPTextConfig, AltCLIPVisionConfig, ) from .processing_altclip import AltCLIPProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_altclip import ( ALTCLIP_PRETRAINED_MODEL_ARCHIVE_LIST, AltCLIPModel, AltCLIPPreTrainedModel, AltCLIPTextModel, AltCLIPVisionModel, ) else: import sys UpperCamelCase : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
50
from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import BaseOutput, is_torch_available, is_transformers_available @dataclass class _lowerCAmelCase( UpperCAmelCase_ ): """simple docstring""" a : Union[List[PIL.Image.Image], np.ndarray] a : Optional[List[bool]] if is_transformers_available() and is_torch_available(): from .pipeline_semantic_stable_diffusion import SemanticStableDiffusionPipeline
57
0
'''simple docstring''' import itertools from dataclasses import dataclass from typing import Any, Callable, Dict, List, Optional, Union import pandas as pd import pyarrow as pa import datasets import datasets.config from datasets.features.features import require_storage_cast from datasets.table import table_cast from datasets.utils.py_utils import Literal a__ : Any = datasets.utils.logging.get_logger(__name__) a__ : str = ['names', 'prefix'] a__ : Any = ['warn_bad_lines', 'error_bad_lines', 'mangle_dupe_cols'] a__ : Dict = ['encoding_errors', 'on_bad_lines'] a__ : Optional[Any] = ['date_format'] @dataclass class lowerCAmelCase__ ( datasets.BuilderConfig ): '''simple docstring''' _lowerCamelCase ="," _lowerCamelCase =None _lowerCamelCase ="infer" _lowerCamelCase =None _lowerCamelCase =None _lowerCamelCase =None _lowerCamelCase =None _lowerCamelCase =None _lowerCamelCase =True _lowerCamelCase =None _lowerCamelCase =None _lowerCamelCase =None _lowerCamelCase =None _lowerCamelCase =False _lowerCamelCase =None _lowerCamelCase =None _lowerCamelCase =None _lowerCamelCase =True _lowerCamelCase =True _lowerCamelCase =False _lowerCamelCase =True _lowerCamelCase =None _lowerCamelCase ="." _lowerCamelCase =None _lowerCamelCase ='"' _lowerCamelCase =0 _lowerCamelCase =None _lowerCamelCase =None _lowerCamelCase =None _lowerCamelCase =None _lowerCamelCase =True _lowerCamelCase =True _lowerCamelCase =0 _lowerCamelCase =True _lowerCamelCase =False _lowerCamelCase =None _lowerCamelCase =1_00_00 _lowerCamelCase =None _lowerCamelCase ="strict" _lowerCamelCase ="error" _lowerCamelCase =None def __snake_case ( self : Any ): if self.delimiter is not None: UpperCAmelCase = self.delimiter if self.column_names is not None: UpperCAmelCase = self.column_names @property def __snake_case ( self : Optional[Any] ): UpperCAmelCase = { '''sep''': self.sep, '''header''': self.header, '''names''': self.names, '''index_col''': self.index_col, '''usecols''': self.usecols, '''prefix''': self.prefix, '''mangle_dupe_cols''': self.mangle_dupe_cols, '''engine''': self.engine, '''converters''': self.converters, '''true_values''': self.true_values, '''false_values''': self.false_values, '''skipinitialspace''': self.skipinitialspace, '''skiprows''': self.skiprows, '''nrows''': self.nrows, '''na_values''': self.na_values, '''keep_default_na''': self.keep_default_na, '''na_filter''': self.na_filter, '''verbose''': self.verbose, '''skip_blank_lines''': self.skip_blank_lines, '''thousands''': self.thousands, '''decimal''': self.decimal, '''lineterminator''': self.lineterminator, '''quotechar''': self.quotechar, '''quoting''': self.quoting, '''escapechar''': self.escapechar, '''comment''': self.comment, '''encoding''': self.encoding, '''dialect''': self.dialect, '''error_bad_lines''': self.error_bad_lines, '''warn_bad_lines''': self.warn_bad_lines, '''skipfooter''': self.skipfooter, '''doublequote''': self.doublequote, '''memory_map''': self.memory_map, '''float_precision''': self.float_precision, '''chunksize''': self.chunksize, '''encoding_errors''': self.encoding_errors, '''on_bad_lines''': self.on_bad_lines, '''date_format''': self.date_format, } # some kwargs must not be passed if they don't have a default value # some others are deprecated and we can also not pass them if they are the default value for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS: if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig() , a__ ): del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 2.0 new arguments if not (datasets.config.PANDAS_VERSION.major >= 2): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 1.3 new arguments if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] return pd_read_csv_kwargs class lowerCAmelCase__ ( datasets.ArrowBasedBuilder ): '''simple docstring''' _lowerCamelCase =CsvConfig def __snake_case ( self : Optional[int] ): return datasets.DatasetInfo(features=self.config.features ) def __snake_case ( self : int , a__ : List[str] ): if not self.config.data_files: raise ValueError(f"At least one data file must be specified, but got data_files={self.config.data_files}" ) UpperCAmelCase = dl_manager.download_and_extract(self.config.data_files ) if isinstance(a__ , (str, list, tuple) ): UpperCAmelCase = data_files if isinstance(a__ , a__ ): UpperCAmelCase = [files] UpperCAmelCase = [dl_manager.iter_files(a__ ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'''files''': files} )] UpperCAmelCase = [] for split_name, files in data_files.items(): if isinstance(a__ , a__ ): UpperCAmelCase = [files] UpperCAmelCase = [dl_manager.iter_files(a__ ) for file in files] splits.append(datasets.SplitGenerator(name=a__ , gen_kwargs={'''files''': files} ) ) return splits def __snake_case ( self : Any , a__ : pa.Table ): if self.config.features is not None: UpperCAmelCase = self.config.features.arrow_schema if all(not require_storage_cast(a__ ) for feature in self.config.features.values() ): # cheaper cast UpperCAmelCase = pa.Table.from_arrays([pa_table[field.name] for field in schema] , schema=a__ ) else: # more expensive cast; allows str <-> int/float or str to Audio for example UpperCAmelCase = table_cast(a__ , a__ ) return pa_table def __snake_case ( self : Any , a__ : Tuple ): UpperCAmelCase = self.config.features.arrow_schema if self.config.features else None # dtype allows reading an int column as str UpperCAmelCase = ( { name: dtype.to_pandas_dtype() if not require_storage_cast(a__ ) else object for name, dtype, feature in zip(schema.names , schema.types , self.config.features.values() ) } if schema is not None else None ) for file_idx, file in enumerate(itertools.chain.from_iterable(a__ ) ): UpperCAmelCase = pd.read_csv(a__ , iterator=a__ , dtype=a__ , **self.config.pd_read_csv_kwargs ) try: for batch_idx, df in enumerate(a__ ): UpperCAmelCase = pa.Table.from_pandas(a__ ) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(a__ ) except ValueError as e: logger.error(f"Failed to read file '{file}' with error {type(a__ )}: {e}" ) raise
51
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConfig, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaForCTC, WavaVecaForPreTraining, WavaVecaProcessor, logging, ) from transformers.models.wavaveca.modeling_wavaveca import WavaVecaForSequenceClassification logging.set_verbosity_info() A_ : Tuple = logging.get_logger(__name__) A_ : Optional[int] = { 'post_extract_proj': 'feature_projection.projection', 'encoder.pos_conv.0': 'encoder.pos_conv_embed.conv', 'self_attn.k_proj': 'encoder.layers.*.attention.k_proj', 'self_attn.v_proj': 'encoder.layers.*.attention.v_proj', 'self_attn.q_proj': 'encoder.layers.*.attention.q_proj', 'self_attn.out_proj': 'encoder.layers.*.attention.out_proj', 'self_attn_layer_norm': 'encoder.layers.*.layer_norm', 'fc1': 'encoder.layers.*.feed_forward.intermediate_dense', 'fc2': 'encoder.layers.*.feed_forward.output_dense', 'final_layer_norm': 'encoder.layers.*.final_layer_norm', 'encoder.layer_norm': 'encoder.layer_norm', 'adapter_layer': 'encoder.layers.*.adapter_layer', 'w2v_model.layer_norm': 'feature_projection.layer_norm', 'quantizer.weight_proj': 'quantizer.weight_proj', 'quantizer.vars': 'quantizer.codevectors', 'project_q': 'project_q', 'final_proj': 'project_hid', 'w2v_encoder.proj': 'lm_head', 'mask_emb': 'masked_spec_embed', 'pooling_layer.linear': 'projector', 'pooling_layer.projection': 'classifier', } A_ : int = [ 'lm_head', 'quantizer.weight_proj', 'quantizer.codevectors', 'project_q', 'project_hid', 'projector', 'classifier', ] def snake_case (UpperCAmelCase__ ) -> str: UpperCamelCase_: Tuple = {} with open(UpperCAmelCase__ , 'r' ) as file: for line_number, line in enumerate(UpperCAmelCase__ ): UpperCamelCase_: List[Any] = line.strip() if line: UpperCamelCase_: List[Any] = line.split() UpperCamelCase_: Optional[Any] = line_number UpperCamelCase_: Any = words[0] UpperCamelCase_: List[Any] = value return result def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) -> List[str]: for attribute in key.split('.' ): UpperCamelCase_: str = getattr(UpperCAmelCase__ , UpperCAmelCase__ ) UpperCamelCase_: str = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(UpperCAmelCase__ ): UpperCamelCase_: Any = PARAM_MAPPING[full_name.split('.' )[-1]] UpperCamelCase_: Dict = 'param' if weight_type is not None and weight_type != "param": UpperCamelCase_: Optional[Any] = getattr(UpperCAmelCase__ , UpperCAmelCase__ ).shape elif weight_type is not None and weight_type == "param": UpperCamelCase_: Optional[Any] = hf_pointer for attribute in hf_param_name.split('.' ): UpperCamelCase_: str = getattr(UpperCAmelCase__ , UpperCAmelCase__ ) UpperCamelCase_: Tuple = shape_pointer.shape # let's reduce dimension UpperCamelCase_: int = value[0] else: UpperCamelCase_: Union[str, Any] = hf_pointer.shape if hf_shape != value.shape: raise ValueError( F'''Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be''' F''' {value.shape} for {full_name}''' ) if weight_type == "weight": UpperCamelCase_: Optional[int] = value elif weight_type == "weight_g": UpperCamelCase_: Any = value elif weight_type == "weight_v": UpperCamelCase_: Union[str, Any] = value elif weight_type == "bias": UpperCamelCase_: Union[str, Any] = value elif weight_type == "param": for attribute in hf_param_name.split('.' ): UpperCamelCase_: Dict = getattr(UpperCAmelCase__ , UpperCAmelCase__ ) UpperCamelCase_: Optional[Any] = value else: UpperCamelCase_: int = value logger.info(F'''{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.''' ) def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) -> Any: UpperCamelCase_: Union[str, Any] = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(UpperCAmelCase__ ): UpperCamelCase_: Dict = PARAM_MAPPING[full_name.split('.' )[-1]] UpperCamelCase_: List[Any] = 'param' if weight_type is not None and weight_type != "param": UpperCamelCase_: List[Any] = '.'.join([key, weight_type] ) elif weight_type is not None and weight_type == "param": UpperCamelCase_: Any = '.'.join([key, hf_param_name] ) else: UpperCamelCase_: Union[str, Any] = key UpperCamelCase_: Any = value if 'lm_head' in full_key else value[0] A_ : str = { 'W_a': 'linear_1.weight', 'W_b': 'linear_2.weight', 'b_a': 'linear_1.bias', 'b_b': 'linear_2.bias', 'ln_W': 'norm.weight', 'ln_b': 'norm.bias', } def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__=None , UpperCAmelCase__=None ) -> Any: UpperCamelCase_: Optional[int] = False for key, mapped_key in MAPPING.items(): UpperCamelCase_: Tuple = 'wav2vec2.' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]: UpperCamelCase_: Optional[Any] = True if "*" in mapped_key: UpperCamelCase_: Optional[int] = name.split(UpperCAmelCase__ )[0].split('.' )[-2] UpperCamelCase_: Any = mapped_key.replace('*' , UpperCAmelCase__ ) if "weight_g" in name: UpperCamelCase_: Union[str, Any] = 'weight_g' elif "weight_v" in name: UpperCamelCase_: Dict = 'weight_v' elif "bias" in name: UpperCamelCase_: int = 'bias' elif "weight" in name: # TODO: don't match quantizer.weight_proj UpperCamelCase_: str = 'weight' else: UpperCamelCase_: Union[str, Any] = None if hf_dict is not None: rename_dict(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) else: set_recursively(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) return is_used return is_used def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) -> List[str]: UpperCamelCase_: List[Any] = [] UpperCamelCase_: Dict = fairseq_model.state_dict() UpperCamelCase_: Optional[Any] = hf_model.wavaveca.feature_extractor for name, value in fairseq_dict.items(): UpperCamelCase_: Union[str, Any] = False if "conv_layers" in name: load_conv_layer( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , hf_model.config.feat_extract_norm == 'group' , ) UpperCamelCase_: List[Any] = True else: UpperCamelCase_: Tuple = load_wavaveca_layer(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) if not is_used: unused_weights.append(UpperCAmelCase__ ) logger.warning(F'''Unused weights: {unused_weights}''' ) def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) -> Any: UpperCamelCase_: Any = full_name.split('conv_layers.' )[-1] UpperCamelCase_: int = name.split('.' ) UpperCamelCase_: int = int(items[0] ) UpperCamelCase_: Union[str, Any] = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.''' ) UpperCamelCase_: Union[str, Any] = value logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.''' ) UpperCamelCase_: int = value logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.''' ) UpperCamelCase_: Union[str, Any] = value logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.''' ) UpperCamelCase_: List[Any] = value logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) else: unused_weights.append(UpperCAmelCase__ ) @torch.no_grad() def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__=None , UpperCAmelCase__=None , UpperCAmelCase__=True , UpperCAmelCase__=False ) -> Dict: if config_path is not None: UpperCamelCase_: Tuple = WavaVecaConfig.from_pretrained(UpperCAmelCase__ ) else: UpperCamelCase_: List[str] = WavaVecaConfig() if is_seq_class: UpperCamelCase_: int = read_txt_into_dict(UpperCAmelCase__ ) UpperCamelCase_: Tuple = idalabel UpperCamelCase_: str = WavaVecaForSequenceClassification(UpperCAmelCase__ ) UpperCamelCase_: Optional[int] = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6_0_0_0 , padding_value=0 , do_normalize=UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , ) feature_extractor.save_pretrained(UpperCAmelCase__ ) elif is_finetuned: if dict_path: UpperCamelCase_: List[Any] = Dictionary.load(UpperCAmelCase__ ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq UpperCamelCase_: Dict = target_dict.pad_index UpperCamelCase_: Tuple = target_dict.bos_index UpperCamelCase_: Optional[Any] = target_dict.eos_index UpperCamelCase_: Union[str, Any] = len(target_dict.symbols ) UpperCamelCase_: int = os.path.join(UpperCAmelCase__ , 'vocab.json' ) if not os.path.isdir(UpperCAmelCase__ ): logger.error('--pytorch_dump_folder_path ({}) should be a directory'.format(UpperCAmelCase__ ) ) return os.makedirs(UpperCAmelCase__ , exist_ok=UpperCAmelCase__ ) UpperCamelCase_: str = target_dict.indices # fairseq has the <pad> and <s> switched UpperCamelCase_: List[str] = 0 UpperCamelCase_: List[Any] = 1 with open(UpperCAmelCase__ , 'w' , encoding='utf-8' ) as vocab_handle: json.dump(UpperCAmelCase__ , UpperCAmelCase__ ) UpperCamelCase_: Union[str, Any] = WavaVecaCTCTokenizer( UpperCAmelCase__ , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token='|' , do_lower_case=UpperCAmelCase__ , ) UpperCamelCase_: Any = True if config.feat_extract_norm == 'layer' else False UpperCamelCase_: Tuple = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6_0_0_0 , padding_value=0 , do_normalize=UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , ) UpperCamelCase_: Dict = WavaVecaProcessor(feature_extractor=UpperCAmelCase__ , tokenizer=UpperCAmelCase__ ) processor.save_pretrained(UpperCAmelCase__ ) UpperCamelCase_: Any = WavaVecaForCTC(UpperCAmelCase__ ) else: UpperCamelCase_: Any = WavaVecaForPreTraining(UpperCAmelCase__ ) if is_finetuned or is_seq_class: UpperCamelCase_ ,UpperCamelCase_ ,UpperCamelCase_: Dict = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] )} ) else: UpperCamelCase_: List[str] = argparse.Namespace(task='audio_pretraining' ) UpperCamelCase_: Any = fairseq.tasks.setup_task(UpperCAmelCase__ ) UpperCamelCase_ ,UpperCamelCase_ ,UpperCamelCase_: Union[str, Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=UpperCAmelCase__ ) UpperCamelCase_: str = model[0].eval() recursively_load_weights(UpperCAmelCase__ , UpperCAmelCase__ , not is_finetuned ) hf_wavavec.save_pretrained(UpperCAmelCase__ ) if __name__ == "__main__": A_ : str = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint') parser.add_argument('--dict_path', default=None, type=str, help='Path to dict of fine-tuned model') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') parser.add_argument( '--not_finetuned', action='store_true', help='Whether the model to convert is a fine-tuned model or not' ) parser.add_argument( '--is_seq_class', action='store_true', help='Whether the model to convert is a fine-tuned sequence classification model or not', ) A_ : int = parser.parse_args() A_ : str = not args.not_finetuned and not args.is_seq_class convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, is_finetuned, args.is_seq_class, )
57
0
"""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 = {'''configuration_opt''': ['''OPT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''OPTConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A = [ '''OPT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''OPTForCausalLM''', '''OPTModel''', '''OPTPreTrainedModel''', '''OPTForSequenceClassification''', '''OPTForQuestionAnswering''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A = ['''TFOPTForCausalLM''', '''TFOPTModel''', '''TFOPTPreTrainedModel'''] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A = [ '''FlaxOPTForCausalLM''', '''FlaxOPTModel''', '''FlaxOPTPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_opt import OPT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPTConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_opt import ( OPT_PRETRAINED_MODEL_ARCHIVE_LIST, OPTForCausalLM, OPTForQuestionAnswering, OPTForSequenceClassification, OPTModel, OPTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_opt import TFOPTForCausalLM, TFOPTModel, TFOPTPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_opt import FlaxOPTForCausalLM, FlaxOPTModel, FlaxOPTPreTrainedModel else: import sys A = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
52
import inspect import os import unittest import torch import accelerate from accelerate import debug_launcher from accelerate.test_utils import ( execute_subprocess_async, require_cpu, require_huggingface_suite, require_multi_gpu, require_single_gpu, ) from accelerate.utils import patch_environment @require_huggingface_suite class _lowerCAmelCase( unittest.TestCase ): """simple docstring""" def _a ( self ): UpperCamelCase_: Optional[int] = inspect.getfile(accelerate.test_utils ) UpperCamelCase_: Dict = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ['scripts', 'external_deps', 'test_metrics.py'] ) from accelerate.test_utils.scripts.external_deps import test_metrics # noqa: F401 UpperCamelCase_: Tuple = test_metrics @require_cpu def _a ( self ): debug_launcher(self.test_metrics.main , num_processes=1 ) @require_cpu def _a ( self ): debug_launcher(self.test_metrics.main ) @require_single_gpu def _a ( self ): self.test_metrics.main() @require_multi_gpu def _a ( self ): print(f'''Found {torch.cuda.device_count()} devices.''' ) UpperCamelCase_: List[Any] = ['torchrun', f'''--nproc_per_node={torch.cuda.device_count()}''', self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(_lowerCamelCase , env=os.environ.copy() )
57
0
from datetime import datetime import requests from bsa import BeautifulSoup if __name__ == "__main__": _snake_case : List[Any] = input('Enter image url: ').strip() print(F"""Downloading image from {url} ...""") _snake_case : Union[str, Any] = BeautifulSoup(requests.get(url).content, 'html.parser') # The image URL is in the content field of the first meta tag with property og:image _snake_case : List[Any] = soup.find('meta', {'property': 'og:image'})['content'] _snake_case : str = requests.get(image_url).content _snake_case : Any = F"""{datetime.now():%Y-%m-%d_%H:%M:%S}.jpg""" with open(file_name, 'wb') as fp: fp.write(image_data) print(F"""Done. Image saved to disk as {file_name}.""")
53
import math class _lowerCAmelCase: """simple docstring""" def _a ( self , _lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: int = 0.0 UpperCamelCase_: Tuple = 0.0 for i in range(len(_lowerCamelCase ) ): da += math.pow((sample[i] - weights[0][i]) , 2 ) da += math.pow((sample[i] - weights[1][i]) , 2 ) return 0 if da > da else 1 return 0 def _a ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): for i in range(len(_lowerCamelCase ) ): weights[j][i] += alpha * (sample[i] - weights[j][i]) return weights def snake_case () -> None: # Training Examples ( m, n ) UpperCamelCase_: List[str] = [[1, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 1, 1]] # weight initialization ( n, C ) UpperCamelCase_: List[Any] = [[0.2, 0.6, 0.5, 0.9], [0.8, 0.4, 0.7, 0.3]] # training UpperCamelCase_: Dict = SelfOrganizingMap() UpperCamelCase_: List[Any] = 3 UpperCamelCase_: List[str] = 0.5 for _ in range(UpperCAmelCase__ ): for j in range(len(UpperCAmelCase__ ) ): # training sample UpperCamelCase_: int = training_samples[j] # Compute the winning vector UpperCamelCase_: Tuple = self_organizing_map.get_winner(UpperCAmelCase__ , UpperCAmelCase__ ) # Update the winning vector UpperCamelCase_: Union[str, Any] = self_organizing_map.update(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) # classify test sample UpperCamelCase_: Dict = [0, 0, 0, 1] UpperCamelCase_: Union[str, Any] = self_organizing_map.get_winner(UpperCAmelCase__ , UpperCAmelCase__ ) # results print(F'''Clusters that the test sample belongs to : {winner}''' ) print(F'''Weights that have been trained : {weights}''' ) # running the main() function if __name__ == "__main__": main()
57
0
import gc import inspect import unittest import torch from parameterized import parameterized from diffusers import PriorTransformer from diffusers.utils import floats_tensor, slow, torch_all_close, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin enable_full_determinism() class A ( __lowercase , unittest.TestCase ): _snake_case =PriorTransformer _snake_case ='''hidden_states''' @property def lowerCAmelCase__ ( self: str ) -> List[Any]: '''simple docstring''' UpperCAmelCase_ =4 UpperCAmelCase_ =8 UpperCAmelCase_ =7 UpperCAmelCase_ =floats_tensor((batch_size, embedding_dim) ).to(_lowerCAmelCase ) UpperCAmelCase_ =floats_tensor((batch_size, embedding_dim) ).to(_lowerCAmelCase ) UpperCAmelCase_ =floats_tensor((batch_size, num_embeddings, embedding_dim) ).to(_lowerCAmelCase ) return { "hidden_states": hidden_states, "timestep": 2, "proj_embedding": proj_embedding, "encoder_hidden_states": encoder_hidden_states, } def lowerCAmelCase__ ( self: Tuple , _lowerCAmelCase: Tuple=0 ) -> Tuple: '''simple docstring''' torch.manual_seed(_lowerCAmelCase ) UpperCAmelCase_ =4 UpperCAmelCase_ =8 UpperCAmelCase_ =7 UpperCAmelCase_ =torch.randn((batch_size, embedding_dim) ).to(_lowerCAmelCase ) UpperCAmelCase_ =torch.randn((batch_size, embedding_dim) ).to(_lowerCAmelCase ) UpperCAmelCase_ =torch.randn((batch_size, num_embeddings, embedding_dim) ).to(_lowerCAmelCase ) return { "hidden_states": hidden_states, "timestep": 2, "proj_embedding": proj_embedding, "encoder_hidden_states": encoder_hidden_states, } @property def lowerCAmelCase__ ( self: List[Any] ) -> str: '''simple docstring''' return (4, 8) @property def lowerCAmelCase__ ( self: Optional[int] ) -> Optional[int]: '''simple docstring''' return (4, 8) def lowerCAmelCase__ ( self: Optional[Any] ) -> Tuple: '''simple docstring''' UpperCAmelCase_ ={ "num_attention_heads": 2, "attention_head_dim": 4, "num_layers": 2, "embedding_dim": 8, "num_embeddings": 7, "additional_embeddings": 4, } UpperCAmelCase_ =self.dummy_input return init_dict, inputs_dict def lowerCAmelCase__ ( self: List[Any] ) -> Optional[int]: '''simple docstring''' UpperCAmelCase_ , UpperCAmelCase_ =PriorTransformer.from_pretrained( "hf-internal-testing/prior-dummy" , output_loading_info=_lowerCAmelCase ) self.assertIsNotNone(_lowerCAmelCase ) self.assertEqual(len(loading_info["missing_keys"] ) , 0 ) model.to(_lowerCAmelCase ) UpperCAmelCase_ =model(**self.dummy_input )[0] assert hidden_states is not None, "Make sure output is not None" def lowerCAmelCase__ ( self: Any ) -> Any: '''simple docstring''' UpperCAmelCase_ , UpperCAmelCase_ =self.prepare_init_args_and_inputs_for_common() UpperCAmelCase_ =self.model_class(**_lowerCAmelCase ) UpperCAmelCase_ =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCAmelCase_ =[*signature.parameters.keys()] UpperCAmelCase_ =["hidden_states", "timestep"] self.assertListEqual(arg_names[:2] , _lowerCAmelCase ) def lowerCAmelCase__ ( self: List[str] ) -> int: '''simple docstring''' UpperCAmelCase_ =PriorTransformer.from_pretrained("hf-internal-testing/prior-dummy" ) UpperCAmelCase_ =model.to(_lowerCAmelCase ) if hasattr(_lowerCAmelCase , "set_default_attn_processor" ): model.set_default_attn_processor() UpperCAmelCase_ =self.get_dummy_seed_input() with torch.no_grad(): UpperCAmelCase_ =model(**_lowerCAmelCase )[0] UpperCAmelCase_ =output[0, :5].flatten().cpu() print(_lowerCAmelCase ) # Since the VAE Gaussian prior's generator is seeded on the appropriate device, # the expected output slices are not the same for CPU and GPU. UpperCAmelCase_ =torch.tensor([-1.34_36, -0.28_70, 0.75_38, 0.43_68, -0.02_39] ) self.assertTrue(torch_all_close(_lowerCAmelCase , _lowerCAmelCase , rtol=1e-2 ) ) @slow class A ( unittest.TestCase ): def lowerCAmelCase__ ( self: Dict , _lowerCAmelCase: str=1 , _lowerCAmelCase: Any=768 , _lowerCAmelCase: Any=77 , _lowerCAmelCase: Optional[int]=0 ) -> str: '''simple docstring''' torch.manual_seed(_lowerCAmelCase ) UpperCAmelCase_ =batch_size UpperCAmelCase_ =embedding_dim UpperCAmelCase_ =num_embeddings UpperCAmelCase_ =torch.randn((batch_size, embedding_dim) ).to(_lowerCAmelCase ) UpperCAmelCase_ =torch.randn((batch_size, embedding_dim) ).to(_lowerCAmelCase ) UpperCAmelCase_ =torch.randn((batch_size, num_embeddings, embedding_dim) ).to(_lowerCAmelCase ) return { "hidden_states": hidden_states, "timestep": 2, "proj_embedding": proj_embedding, "encoder_hidden_states": encoder_hidden_states, } def lowerCAmelCase__ ( self: Optional[int] ) -> str: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() @parameterized.expand( [ # fmt: off [13, [-0.58_61, 0.12_83, -0.09_31, 0.08_82, 0.44_76, 0.13_29, -0.04_98, 0.06_40]], [37, [-0.49_13, 0.01_10, -0.04_83, 0.05_41, 0.49_54, -0.01_70, 0.03_54, 0.16_51]], # fmt: on ] ) def lowerCAmelCase__ ( self: Tuple , _lowerCAmelCase: List[str] , _lowerCAmelCase: List[str] ) -> int: '''simple docstring''' UpperCAmelCase_ =PriorTransformer.from_pretrained("kandinsky-community/kandinsky-2-1-prior" , subfolder="prior" ) model.to(_lowerCAmelCase ) UpperCAmelCase_ =self.get_dummy_seed_input(seed=_lowerCAmelCase ) with torch.no_grad(): UpperCAmelCase_ =model(**_lowerCAmelCase )[0] assert list(sample.shape ) == [1, 768] UpperCAmelCase_ =sample[0, :8].flatten().cpu() print(_lowerCAmelCase ) UpperCAmelCase_ =torch.tensor(_lowerCAmelCase ) assert torch_all_close(_lowerCAmelCase , _lowerCAmelCase , atol=1e-3 )
54
from collections import namedtuple A_ : Tuple = namedtuple('from_to', 'from_ to') A_ : int = { 'cubicmeter': from_to(1, 1), 'litre': from_to(0.001, 1000), 'kilolitre': from_to(1, 1), 'gallon': from_to(0.00454, 264.172), 'cubicyard': from_to(0.76455, 1.30795), 'cubicfoot': from_to(0.028, 35.3147), 'cup': from_to(0.000236588, 4226.75), } def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) -> float: if from_type not in METRIC_CONVERSION: raise ValueError( F'''Invalid \'from_type\' value: {from_type!r} Supported values are:\n''' + ', '.join(UpperCAmelCase__ ) ) if to_type not in METRIC_CONVERSION: raise ValueError( F'''Invalid \'to_type\' value: {to_type!r}. Supported values are:\n''' + ', '.join(UpperCAmelCase__ ) ) return value * METRIC_CONVERSION[from_type].from_ * METRIC_CONVERSION[to_type].to if __name__ == "__main__": import doctest doctest.testmod()
57
0
from transformers import BertTokenizer, EncoderDecoderModel, SeqaSeqTrainer, SeqaSeqTrainingArguments from transformers.testing_utils import TestCasePlus, require_torch, slow from transformers.utils import is_datasets_available if is_datasets_available(): import datasets class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' @slow @require_torch def UpperCamelCase_ ( self : Optional[int] ): __A = EncoderDecoderModel.from_encoder_decoder_pretrained("prajjwal1/bert-tiny" ,"prajjwal1/bert-tiny" ) __A = BertTokenizer.from_pretrained("bert-base-uncased" ) __A = bertabert.config.encoder.vocab_size __A = tokenizer.sep_token_id __A = tokenizer.cls_token_id __A = 1_28 __A = datasets.load_dataset("cnn_dailymail" ,"3.0.0" ,split="train[:1%]" ) __A = datasets.load_dataset("cnn_dailymail" ,"3.0.0" ,split="validation[:1%]" ) __A = train_dataset.select(range(32 ) ) __A = val_dataset.select(range(16 ) ) __A = 4 def _map_to_encoder_decoder_inputs(A : str ): # Tokenizer will automatically set [BOS] <text> [EOS] __A = tokenizer(batch["article"] ,padding="max_length" ,truncation=A ,max_length=5_12 ) __A = tokenizer(batch["highlights"] ,padding="max_length" ,truncation=A ,max_length=1_28 ) __A = inputs.input_ids __A = inputs.attention_mask __A = outputs.input_ids __A = outputs.input_ids.copy() __A = [ [-1_00 if token == tokenizer.pad_token_id else token for token in labels] for labels in batch["labels"] ] __A = outputs.attention_mask assert all(len(A ) == 5_12 for x in inputs.input_ids ) assert all(len(A ) == 1_28 for x in outputs.input_ids ) return batch def _compute_metrics(A : Union[str, Any] ): __A = pred.label_ids __A = pred.predictions # all unnecessary tokens are removed __A = tokenizer.batch_decode(A ,skip_special_tokens=A ) __A = tokenizer.batch_decode(A ,skip_special_tokens=A ) __A = sum([int(pred_str[i] == label_str[i] ) for i in range(len(A ) )] ) / len(A ) return {"accuracy": accuracy} # map train dataset __A = train_dataset.map( _map_to_encoder_decoder_inputs ,batched=A ,batch_size=A ,remove_columns=["article", "highlights"] ,) train_dataset.set_format( type="torch" ,columns=["input_ids", "attention_mask", "decoder_input_ids", "decoder_attention_mask", "labels"] ,) # same for validation dataset __A = val_dataset.map( _map_to_encoder_decoder_inputs ,batched=A ,batch_size=A ,remove_columns=["article", "highlights"] ,) val_dataset.set_format( type="torch" ,columns=["input_ids", "attention_mask", "decoder_input_ids", "decoder_attention_mask", "labels"] ,) __A = self.get_auto_remove_tmp_dir() __A = SeqaSeqTrainingArguments( output_dir=A ,per_device_train_batch_size=A ,per_device_eval_batch_size=A ,predict_with_generate=A ,evaluation_strategy="steps" ,do_train=A ,do_eval=A ,warmup_steps=0 ,eval_steps=2 ,logging_steps=2 ,) # instantiate trainer __A = SeqaSeqTrainer( model=A ,args=A ,compute_metrics=_compute_metrics ,train_dataset=A ,eval_dataset=A ,tokenizer=A ,) # start training trainer.train()
55
import warnings from ...utils import logging from .image_processing_clip import CLIPImageProcessor A_ : int = logging.get_logger(__name__) class _lowerCAmelCase( UpperCAmelCase_ ): """simple docstring""" def __init__( self , *_lowerCamelCase , **_lowerCamelCase ): warnings.warn( 'The class CLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use CLIPImageProcessor instead.' , _lowerCamelCase , ) super().__init__(*_lowerCamelCase , **_lowerCamelCase )
57
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 import os from accelerate.utils import ComputeEnvironment from .cluster import get_cluster_input from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401 from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401 from .sagemaker import get_sagemaker_input _a : str = "Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine" def _a () -> Dict: """simple docstring""" __snake_case = _ask_options( 'In which compute environment are you running?' , ['This machine', 'AWS (Amazon SageMaker)'] , _convert_compute_environment , ) if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: __snake_case = get_sagemaker_input() else: __snake_case = get_cluster_input() return config def _a (lowercase__ : Union[str, Any]=None ) -> int: """simple docstring""" if subparsers is not None: __snake_case = subparsers.add_parser('config' , description=lowercase__ ) else: __snake_case = argparse.ArgumentParser('Accelerate config command' , description=lowercase__ ) parser.add_argument( '--config_file' , default=lowercase__ , help=( 'The path to use to store the config file. Will default to a file named default_config.yaml in the cache ' 'location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have ' 'such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed ' 'with \'huggingface\'.' ) , ) if subparsers is not None: parser.set_defaults(func=lowercase__ ) return parser def _a (lowercase__ : List[str] ) -> Union[str, Any]: """simple docstring""" __snake_case = get_user_input() if args.config_file is not None: __snake_case = args.config_file else: if not os.path.isdir(lowercase__ ): os.makedirs(lowercase__ ) __snake_case = default_yaml_config_file if config_file.endswith('.json' ): config.to_json_file(lowercase__ ) else: config.to_yaml_file(lowercase__ ) print(f'accelerate configuration saved at {config_file}' ) def _a () -> int: """simple docstring""" __snake_case = config_command_parser() __snake_case = parser.parse_args() config_command(lowercase__ ) if __name__ == "__main__": main()
56
import math from typing import Any, Callable, List, Optional, Tuple, Union import numpy as np import torch from ...models import TaFilmDecoder from ...schedulers import DDPMScheduler from ...utils import is_onnx_available, logging, randn_tensor if is_onnx_available(): from ..onnx_utils import OnnxRuntimeModel from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline from .continous_encoder import SpectrogramContEncoder from .notes_encoder import SpectrogramNotesEncoder A_ : List[Any] = logging.get_logger(__name__) # pylint: disable=invalid-name A_ : Optional[int] = 256 class _lowerCAmelCase( UpperCAmelCase_ ): """simple docstring""" a : Union[str, Any] =['''melgan'''] def __init__( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , ): super().__init__() # From MELGAN UpperCamelCase_: Any = math.log(1e-5 ) # Matches MelGAN training. UpperCamelCase_: List[Any] = 4.0 # Largest value for most examples UpperCamelCase_: Tuple = 1_2_8 self.register_modules( notes_encoder=_lowerCamelCase , continuous_encoder=_lowerCamelCase , decoder=_lowerCamelCase , scheduler=_lowerCamelCase , melgan=_lowerCamelCase , ) def _a ( self , _lowerCamelCase , _lowerCamelCase=(-1.0, 1.0) , _lowerCamelCase=False ): UpperCamelCase_ ,UpperCamelCase_: Union[str, Any] = output_range if clip: UpperCamelCase_: int = torch.clip(_lowerCamelCase , self.min_value , self.max_value ) # Scale to [0, 1]. UpperCamelCase_: List[Any] = (features - self.min_value) / (self.max_value - self.min_value) # Scale to [min_out, max_out]. return zero_one * (max_out - min_out) + min_out def _a ( self , _lowerCamelCase , _lowerCamelCase=(-1.0, 1.0) , _lowerCamelCase=False ): UpperCamelCase_ ,UpperCamelCase_: Dict = input_range UpperCamelCase_: List[str] = torch.clip(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) if clip else outputs # Scale to [0, 1]. UpperCamelCase_: Optional[Any] = (outputs - min_out) / (max_out - min_out) # Scale to [self.min_value, self.max_value]. return zero_one * (self.max_value - self.min_value) + self.min_value def _a ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: str = input_tokens > 0 UpperCamelCase_ ,UpperCamelCase_: Tuple = self.notes_encoder( encoder_input_tokens=_lowerCamelCase , encoder_inputs_mask=_lowerCamelCase ) UpperCamelCase_ ,UpperCamelCase_: Any = self.continuous_encoder( encoder_inputs=_lowerCamelCase , encoder_inputs_mask=_lowerCamelCase ) return [(tokens_encoded, tokens_mask), (continuous_encoded, continuous_mask)] def _a ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: Dict = noise_time if not torch.is_tensor(_lowerCamelCase ): UpperCamelCase_: List[str] = torch.tensor([timesteps] , dtype=torch.long , device=input_tokens.device ) elif torch.is_tensor(_lowerCamelCase ) and len(timesteps.shape ) == 0: UpperCamelCase_: Dict = timesteps[None].to(input_tokens.device ) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML UpperCamelCase_: Union[str, Any] = timesteps * torch.ones(input_tokens.shape[0] , dtype=timesteps.dtype , device=timesteps.device ) UpperCamelCase_: Any = self.decoder( encodings_and_masks=_lowerCamelCase , decoder_input_tokens=_lowerCamelCase , decoder_noise_time=_lowerCamelCase ) return logits @torch.no_grad() def __call__( self , _lowerCamelCase , _lowerCamelCase = None , _lowerCamelCase = 1_0_0 , _lowerCamelCase = True , _lowerCamelCase = "numpy" , _lowerCamelCase = None , _lowerCamelCase = 1 , ): if (callback_steps is None) or ( callback_steps is not None and (not isinstance(_lowerCamelCase , _lowerCamelCase ) or callback_steps <= 0) ): raise ValueError( f'''`callback_steps` has to be a positive integer but is {callback_steps} of type''' f''' {type(_lowerCamelCase )}.''' ) UpperCamelCase_: List[str] = np.zeros([1, TARGET_FEATURE_LENGTH, self.n_dims] , dtype=np.floataa ) UpperCamelCase_: str = np.zeros([1, 0, self.n_dims] , np.floataa ) UpperCamelCase_: Dict = torch.ones((1, TARGET_FEATURE_LENGTH) , dtype=_lowerCamelCase , device=self.device ) for i, encoder_input_tokens in enumerate(_lowerCamelCase ): if i == 0: UpperCamelCase_: str = torch.from_numpy(pred_mel[:1].copy() ).to( device=self.device , dtype=self.decoder.dtype ) # The first chunk has no previous context. UpperCamelCase_: Tuple = torch.zeros((1, TARGET_FEATURE_LENGTH) , dtype=_lowerCamelCase , device=self.device ) else: # The full song pipeline does not feed in a context feature, so the mask # will be all 0s after the feature converter. Because we know we're # feeding in a full context chunk from the previous prediction, set it # to all 1s. UpperCamelCase_: Any = ones UpperCamelCase_: str = self.scale_features( _lowerCamelCase , output_range=[-1.0, 1.0] , clip=_lowerCamelCase ) UpperCamelCase_: Union[str, Any] = self.encode( input_tokens=torch.IntTensor([encoder_input_tokens] ).to(device=self.device ) , continuous_inputs=_lowerCamelCase , continuous_mask=_lowerCamelCase , ) # Sample encoder_continuous_inputs shaped gaussian noise to begin loop UpperCamelCase_: List[str] = randn_tensor( shape=encoder_continuous_inputs.shape , generator=_lowerCamelCase , device=self.device , dtype=self.decoder.dtype , ) # set step values self.scheduler.set_timesteps(_lowerCamelCase ) # Denoising diffusion loop for j, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): UpperCamelCase_: int = self.decode( encodings_and_masks=_lowerCamelCase , input_tokens=_lowerCamelCase , noise_time=t / self.scheduler.config.num_train_timesteps , ) # Compute previous output: x_t -> x_t-1 UpperCamelCase_: Tuple = self.scheduler.step(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , generator=_lowerCamelCase ).prev_sample UpperCamelCase_: List[Any] = self.scale_to_features(_lowerCamelCase , input_range=[-1.0, 1.0] ) UpperCamelCase_: Any = mel[:1] UpperCamelCase_: List[str] = mel.cpu().float().numpy() UpperCamelCase_: Tuple = np.concatenate([full_pred_mel, pred_mel[:1]] , axis=1 ) # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(_lowerCamelCase , _lowerCamelCase ) logger.info('Generated segment' , _lowerCamelCase ) if output_type == "numpy" and not is_onnx_available(): raise ValueError( 'Cannot return output in \'np\' format if ONNX is not available. Make sure to have ONNX installed or set \'output_type\' to \'mel\'.' ) elif output_type == "numpy" and self.melgan is None: raise ValueError( 'Cannot return output in \'np\' format if melgan component is not defined. Make sure to define `self.melgan` or set \'output_type\' to \'mel\'.' ) if output_type == "numpy": UpperCamelCase_: int = self.melgan(input_features=full_pred_mel.astype(np.floataa ) ) else: UpperCamelCase_: int = full_pred_mel if not return_dict: return (output,) return AudioPipelineOutput(audios=_lowerCamelCase )
57
0
"""simple docstring""" from collections import defaultdict from math import ceil, sqrt def __lowerCAmelCase ( __UpperCamelCase : int = 1_0_0_0_0_0_0 , __UpperCamelCase : int = 1_0 ): '''simple docstring''' snake_case_ : defaultdict = defaultdict(__UpperCamelCase ) for outer_width in range(3 , (t_limit // 4) + 2 ): if outer_width * outer_width > t_limit: snake_case_ : Optional[Any] = max( ceil(sqrt(outer_width * outer_width - t_limit ) ) , 1 ) else: snake_case_ : List[Any] = 1 hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2 for hole_width in range(__UpperCamelCase , 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 <= 1_0 ) if __name__ == "__main__": print(F'''{solution() = }''')
58
import itertools from dataclasses import dataclass from typing import Any, Callable, Dict, List, Optional, Union import pandas as pd import pyarrow as pa import datasets import datasets.config from datasets.features.features import require_storage_cast from datasets.table import table_cast from datasets.utils.py_utils import Literal A_ : Union[str, Any] = datasets.utils.logging.get_logger(__name__) A_ : Optional[Any] = ['names', 'prefix'] A_ : List[str] = ['warn_bad_lines', 'error_bad_lines', 'mangle_dupe_cols'] A_ : List[Any] = ['encoding_errors', 'on_bad_lines'] A_ : Optional[Any] = ['date_format'] @dataclass class _lowerCAmelCase( datasets.BuilderConfig ): """simple docstring""" a : str ="," a : Optional[str] =None a : Optional[Union[int, List[int], str]] ="infer" a : Optional[List[str]] =None a : Optional[List[str]] =None a : Optional[Union[int, str, List[int], List[str]]] =None a : Optional[Union[List[int], List[str]]] =None a : Optional[str] =None a : bool =True a : Optional[Literal["c", "python", "pyarrow"]] =None a : Dict[Union[int, str], Callable[[Any], Any]] =None a : Optional[list] =None a : Optional[list] =None a : bool =False a : Optional[Union[int, List[int]]] =None a : Optional[int] =None a : Optional[Union[str, List[str]]] =None a : bool =True a : bool =True a : bool =False a : bool =True a : Optional[str] =None a : str ="." a : Optional[str] =None a : str ='"' a : int =0 a : Optional[str] =None a : Optional[str] =None a : Optional[str] =None a : Optional[str] =None a : bool =True a : bool =True a : int =0 a : bool =True a : bool =False a : Optional[str] =None a : int =10000 a : Optional[datasets.Features] =None a : Optional[str] ="strict" a : Literal["error", "warn", "skip"] ="error" a : Optional[str] =None def _a ( self ): if self.delimiter is not None: UpperCamelCase_: Optional[Any] = self.delimiter if self.column_names is not None: UpperCamelCase_: int = self.column_names @property def _a ( self ): UpperCamelCase_: Any = { 'sep': self.sep, 'header': self.header, 'names': self.names, 'index_col': self.index_col, 'usecols': self.usecols, 'prefix': self.prefix, 'mangle_dupe_cols': self.mangle_dupe_cols, 'engine': self.engine, 'converters': self.converters, 'true_values': self.true_values, 'false_values': self.false_values, 'skipinitialspace': self.skipinitialspace, 'skiprows': self.skiprows, 'nrows': self.nrows, 'na_values': self.na_values, 'keep_default_na': self.keep_default_na, 'na_filter': self.na_filter, 'verbose': self.verbose, 'skip_blank_lines': self.skip_blank_lines, 'thousands': self.thousands, 'decimal': self.decimal, 'lineterminator': self.lineterminator, 'quotechar': self.quotechar, 'quoting': self.quoting, 'escapechar': self.escapechar, 'comment': self.comment, 'encoding': self.encoding, 'dialect': self.dialect, 'error_bad_lines': self.error_bad_lines, 'warn_bad_lines': self.warn_bad_lines, 'skipfooter': self.skipfooter, 'doublequote': self.doublequote, 'memory_map': self.memory_map, 'float_precision': self.float_precision, 'chunksize': self.chunksize, 'encoding_errors': self.encoding_errors, 'on_bad_lines': self.on_bad_lines, 'date_format': self.date_format, } # some kwargs must not be passed if they don't have a default value # some others are deprecated and we can also not pass them if they are the default value for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS: if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig() , _lowerCamelCase ): del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 2.0 new arguments if not (datasets.config.PANDAS_VERSION.major >= 2): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 1.3 new arguments if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] return pd_read_csv_kwargs class _lowerCAmelCase( datasets.ArrowBasedBuilder ): """simple docstring""" a : Dict =CsvConfig def _a ( self ): return datasets.DatasetInfo(features=self.config.features ) def _a ( self , _lowerCamelCase ): if not self.config.data_files: raise ValueError(f'''At least one data file must be specified, but got data_files={self.config.data_files}''' ) UpperCamelCase_: Tuple = dl_manager.download_and_extract(self.config.data_files ) if isinstance(_lowerCamelCase , (str, list, tuple) ): UpperCamelCase_: List[Any] = data_files if isinstance(_lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: str = [files] UpperCamelCase_: Tuple = [dl_manager.iter_files(_lowerCamelCase ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'files': files} )] UpperCamelCase_: Tuple = [] for split_name, files in data_files.items(): if isinstance(_lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: Dict = [files] UpperCamelCase_: int = [dl_manager.iter_files(_lowerCamelCase ) for file in files] splits.append(datasets.SplitGenerator(name=_lowerCamelCase , gen_kwargs={'files': files} ) ) return splits def _a ( self , _lowerCamelCase ): if self.config.features is not None: UpperCamelCase_: List[Any] = self.config.features.arrow_schema if all(not require_storage_cast(_lowerCamelCase ) for feature in self.config.features.values() ): # cheaper cast UpperCamelCase_: Optional[int] = pa.Table.from_arrays([pa_table[field.name] for field in schema] , schema=_lowerCamelCase ) else: # more expensive cast; allows str <-> int/float or str to Audio for example UpperCamelCase_: int = table_cast(_lowerCamelCase , _lowerCamelCase ) return pa_table def _a ( self , _lowerCamelCase ): UpperCamelCase_: List[str] = self.config.features.arrow_schema if self.config.features else None # dtype allows reading an int column as str UpperCamelCase_: Dict = ( { name: dtype.to_pandas_dtype() if not require_storage_cast(_lowerCamelCase ) else object for name, dtype, feature in zip(schema.names , schema.types , self.config.features.values() ) } if schema is not None else None ) for file_idx, file in enumerate(itertools.chain.from_iterable(_lowerCamelCase ) ): UpperCamelCase_: Optional[Any] = pd.read_csv(_lowerCamelCase , iterator=_lowerCamelCase , dtype=_lowerCamelCase , **self.config.pd_read_csv_kwargs ) try: for batch_idx, df in enumerate(_lowerCamelCase ): UpperCamelCase_: Union[str, Any] = pa.Table.from_pandas(_lowerCamelCase ) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(_lowerCamelCase ) except ValueError as e: logger.error(f'''Failed to read file \'{file}\' with error {type(_lowerCamelCase )}: {e}''' ) raise
57
0
import json import os from dataclasses import dataclass from functools import partial from typing import Callable import flax.linen as nn import jax import jax.numpy as jnp import joblib import optax import wandb from flax import jax_utils, struct, traverse_util from flax.serialization import from_bytes, to_bytes from flax.training import train_state from flax.training.common_utils import shard from tqdm.auto import tqdm from transformers import BigBirdConfig, FlaxBigBirdForQuestionAnswering from transformers.models.big_bird.modeling_flax_big_bird import FlaxBigBirdForQuestionAnsweringModule class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = 42 lowercase_ = jnp.floataa lowercase_ = True def SCREAMING_SNAKE_CASE_ (self : Any) ->List[str]: '''simple docstring''' super().setup() lowerCamelCase__: int =nn.Dense(5 , dtype=self.dtype) def __call__(self : Dict , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : Any) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Optional[Any] =super().__call__(*UpperCAmelCase_ , **UpperCAmelCase_) lowerCamelCase__: int =self.cls(outputs[2]) return outputs[:2] + (cls_out,) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = FlaxBigBirdForNaturalQuestionsModule def lowerCAmelCase_ ( __a , __a , __a , __a , __a , __a ) -> Tuple: """simple docstring""" def cross_entropy(__a , __a , __a=None ): lowerCamelCase__: Tuple =logits.shape[-1] lowerCamelCase__: Tuple =(labels[..., None] == jnp.arange(__a )[None]).astype("f4" ) lowerCamelCase__: str =jax.nn.log_softmax(__a , axis=-1 ) lowerCamelCase__: Optional[Any] =-jnp.sum(labels * logits , axis=-1 ) if reduction is not None: lowerCamelCase__: Optional[Any] =reduction(__a ) return loss lowerCamelCase__: str =partial(__a , reduction=jnp.mean ) lowerCamelCase__: str =cross_entropy(__a , __a ) lowerCamelCase__: Optional[int] =cross_entropy(__a , __a ) lowerCamelCase__: Optional[Any] =cross_entropy(__a , __a ) return (start_loss + end_loss + pooled_loss) / 3 @dataclass class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowercase_ = "google/bigbird-roberta-base" lowercase_ = 3000 lowercase_ = 1_0500 lowercase_ = 128 lowercase_ = 3 lowercase_ = 1 lowercase_ = 5 # tx_args lowercase_ = 3E-5 lowercase_ = 0.0 lowercase_ = 2_0000 lowercase_ = 0.0095 lowercase_ = "bigbird-roberta-natural-questions" lowercase_ = "training-expt" lowercase_ = "data/nq-training.jsonl" lowercase_ = "data/nq-validation.jsonl" def SCREAMING_SNAKE_CASE_ (self : Tuple) ->List[str]: '''simple docstring''' os.makedirs(self.base_dir , exist_ok=UpperCAmelCase_) lowerCamelCase__: Optional[Any] =os.path.join(self.base_dir , self.save_dir) lowerCamelCase__: List[str] =self.batch_size_per_device * jax.device_count() @dataclass class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowercase_ = 42 lowercase_ = 4096 # no dynamic padding on TPUs def __call__(self : List[Any] , UpperCAmelCase_ : Optional[Any]) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Optional[Any] =self.collate_fn(UpperCAmelCase_) lowerCamelCase__: List[Any] =jax.tree_util.tree_map(UpperCAmelCase_ , UpperCAmelCase_) return batch def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : List[str]) ->List[Any]: '''simple docstring''' lowerCamelCase__ , lowerCamelCase__: List[Any] =self.fetch_inputs(features["input_ids"]) lowerCamelCase__: Union[str, Any] ={ "input_ids": jnp.array(UpperCAmelCase_ , dtype=jnp.intaa), "attention_mask": jnp.array(UpperCAmelCase_ , dtype=jnp.intaa), "start_labels": jnp.array(features["start_token"] , dtype=jnp.intaa), "end_labels": jnp.array(features["end_token"] , dtype=jnp.intaa), "pooled_labels": jnp.array(features["category"] , dtype=jnp.intaa), } return batch def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : list) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: Tuple =[self._fetch_inputs(UpperCAmelCase_) for ids in input_ids] return zip(*UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : list) ->Any: '''simple docstring''' lowerCamelCase__: Optional[Any] =[1 for _ in range(len(UpperCAmelCase_))] while len(UpperCAmelCase_) < self.max_length: input_ids.append(self.pad_id) attention_mask.append(0) return input_ids, attention_mask def lowerCAmelCase_ ( __a , __a , __a=None ) -> str: """simple docstring""" if seed is not None: lowerCamelCase__: Any =dataset.shuffle(seed=__a ) for i in range(len(__a ) // batch_size ): lowerCamelCase__: Any =dataset[i * batch_size : (i + 1) * batch_size] yield dict(__a ) @partial(jax.pmap , axis_name="batch" ) def lowerCAmelCase_ ( __a , __a , **__a ) -> List[str]: """simple docstring""" def loss_fn(__a ): lowerCamelCase__: Optional[int] =model_inputs.pop("start_labels" ) lowerCamelCase__: int =model_inputs.pop("end_labels" ) lowerCamelCase__: List[str] =model_inputs.pop("pooled_labels" ) lowerCamelCase__: Optional[int] =state.apply_fn(**__a , params=__a , dropout_rng=__a , train=__a ) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: List[Any] =outputs return state.loss_fn( __a , __a , __a , __a , __a , __a , ) lowerCamelCase__ , lowerCamelCase__: int =jax.random.split(__a ) lowerCamelCase__: Optional[Any] =jax.value_and_grad(__a ) lowerCamelCase__ , lowerCamelCase__: List[str] =grad_fn(state.params ) lowerCamelCase__: Optional[Any] =jax.lax.pmean({"loss": loss} , axis_name="batch" ) lowerCamelCase__: List[str] =jax.lax.pmean(__a , "batch" ) lowerCamelCase__: List[str] =state.apply_gradients(grads=__a ) return state, metrics, new_drp_rng @partial(jax.pmap , axis_name="batch" ) def lowerCAmelCase_ ( __a , **__a ) -> List[Any]: """simple docstring""" lowerCamelCase__: int =model_inputs.pop("start_labels" ) lowerCamelCase__: List[str] =model_inputs.pop("end_labels" ) lowerCamelCase__: int =model_inputs.pop("pooled_labels" ) lowerCamelCase__: Optional[Any] =state.apply_fn(**__a , params=state.params , train=__a ) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: List[str] =outputs lowerCamelCase__: Optional[int] =state.loss_fn(__a , __a , __a , __a , __a , __a ) lowerCamelCase__: Optional[Any] =jax.lax.pmean({"loss": loss} , axis_name="batch" ) return metrics class _SCREAMING_SNAKE_CASE ( train_state.TrainState ): '''simple docstring''' lowercase_ = struct.field(pytree_node=__SCREAMING_SNAKE_CASE ) @dataclass class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = None def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int=None) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Dict =model.params lowerCamelCase__: Tuple =TrainState.create( apply_fn=model.__call__ , params=UpperCAmelCase_ , tx=UpperCAmelCase_ , loss_fn=UpperCAmelCase_ , ) if ckpt_dir is not None: lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Any =restore_checkpoint(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: Tuple ={ "lr": args.lr, "init_lr": args.init_lr, "warmup_steps": args.warmup_steps, "num_train_steps": num_train_steps, "weight_decay": args.weight_decay, } lowerCamelCase__ , lowerCamelCase__: List[Any] =build_tx(**UpperCAmelCase_) lowerCamelCase__: str =train_state.TrainState( step=UpperCAmelCase_ , apply_fn=model.__call__ , params=UpperCAmelCase_ , tx=UpperCAmelCase_ , opt_state=UpperCAmelCase_ , ) lowerCamelCase__: Tuple =args lowerCamelCase__: Tuple =data_collator lowerCamelCase__: str =lr lowerCamelCase__: Dict =params lowerCamelCase__: List[str] =jax_utils.replicate(UpperCAmelCase_) return state def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Tuple) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: Tuple =self.args lowerCamelCase__: Any =len(UpperCAmelCase_) // args.batch_size lowerCamelCase__: List[str] =jax.random.PRNGKey(0) lowerCamelCase__: Optional[Any] =jax.random.split(UpperCAmelCase_ , jax.device_count()) for epoch in range(args.max_epochs): lowerCamelCase__: Union[str, Any] =jnp.array(0 , dtype=jnp.floataa) lowerCamelCase__: str =get_batched_dataset(UpperCAmelCase_ , args.batch_size , seed=UpperCAmelCase_) lowerCamelCase__: Dict =0 for batch in tqdm(UpperCAmelCase_ , total=UpperCAmelCase_ , desc=F"""Running EPOCH-{epoch}"""): lowerCamelCase__: List[str] =self.data_collator(UpperCAmelCase_) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Optional[int] =self.train_step_fn(UpperCAmelCase_ , UpperCAmelCase_ , **UpperCAmelCase_) running_loss += jax_utils.unreplicate(metrics["loss"]) i += 1 if i % args.logging_steps == 0: lowerCamelCase__: Optional[int] =jax_utils.unreplicate(state.step) lowerCamelCase__: List[Any] =running_loss.item() / i lowerCamelCase__: Tuple =self.scheduler_fn(state_step - 1) lowerCamelCase__: Union[str, Any] =self.evaluate(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: Dict ={ "step": state_step.item(), "eval_loss": eval_loss.item(), "tr_loss": tr_loss, "lr": lr.item(), } tqdm.write(str(UpperCAmelCase_)) self.logger.log(UpperCAmelCase_ , commit=UpperCAmelCase_) if i % args.save_steps == 0: self.save_checkpoint(args.save_dir + F"""-e{epoch}-s{i}""" , state=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : str , UpperCAmelCase_ : str) ->Any: '''simple docstring''' lowerCamelCase__: List[Any] =get_batched_dataset(UpperCAmelCase_ , self.args.batch_size) lowerCamelCase__: List[str] =len(UpperCAmelCase_) // self.args.batch_size lowerCamelCase__: str =jnp.array(0 , dtype=jnp.floataa) lowerCamelCase__: Optional[Any] =0 for batch in tqdm(UpperCAmelCase_ , total=UpperCAmelCase_ , desc="Evaluating ... "): lowerCamelCase__: int =self.data_collator(UpperCAmelCase_) lowerCamelCase__: str =self.val_step_fn(UpperCAmelCase_ , **UpperCAmelCase_) running_loss += jax_utils.unreplicate(metrics["loss"]) i += 1 return running_loss / i def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[int]) ->int: '''simple docstring''' lowerCamelCase__: Any =jax_utils.unreplicate(UpperCAmelCase_) print(F"""SAVING CHECKPOINT IN {save_dir}""" , end=" ... ") self.model_save_fn(UpperCAmelCase_ , params=state.params) with open(os.path.join(UpperCAmelCase_ , "opt_state.msgpack") , "wb") as f: f.write(to_bytes(state.opt_state)) joblib.dump(self.args , os.path.join(UpperCAmelCase_ , "args.joblib")) joblib.dump(self.data_collator , os.path.join(UpperCAmelCase_ , "data_collator.joblib")) with open(os.path.join(UpperCAmelCase_ , "training_state.json") , "w") as f: json.dump({"step": state.step.item()} , UpperCAmelCase_) print("DONE") def lowerCAmelCase_ ( __a , __a ) -> str: """simple docstring""" print(F"""RESTORING CHECKPOINT FROM {save_dir}""" , end=" ... " ) with open(os.path.join(__a , "flax_model.msgpack" ) , "rb" ) as f: lowerCamelCase__: Tuple =from_bytes(state.params , f.read() ) with open(os.path.join(__a , "opt_state.msgpack" ) , "rb" ) as f: lowerCamelCase__: Optional[int] =from_bytes(state.opt_state , f.read() ) lowerCamelCase__: Any =joblib.load(os.path.join(__a , "args.joblib" ) ) lowerCamelCase__: Union[str, Any] =joblib.load(os.path.join(__a , "data_collator.joblib" ) ) with open(os.path.join(__a , "training_state.json" ) , "r" ) as f: lowerCamelCase__: Optional[Any] =json.load(__a ) lowerCamelCase__: Any =training_state["step"] print("DONE" ) return params, opt_state, step, args, data_collator def lowerCAmelCase_ ( __a , __a , __a , __a ) -> Optional[int]: """simple docstring""" lowerCamelCase__: int =num_train_steps - warmup_steps lowerCamelCase__: str =optax.linear_schedule(init_value=__a , end_value=__a , transition_steps=__a ) lowerCamelCase__: Optional[Any] =optax.linear_schedule(init_value=__a , end_value=1e-7 , transition_steps=__a ) lowerCamelCase__: List[Any] =optax.join_schedules(schedules=[warmup_fn, decay_fn] , boundaries=[warmup_steps] ) return lr def lowerCAmelCase_ ( __a , __a , __a , __a , __a ) -> str: """simple docstring""" def weight_decay_mask(__a ): lowerCamelCase__: List[str] =traverse_util.flatten_dict(__a ) lowerCamelCase__: List[str] ={k: (v[-1] != "bias" and v[-2:] != ("LayerNorm", "scale")) for k, v in params.items()} return traverse_util.unflatten_dict(__a ) lowerCamelCase__: Optional[Any] =scheduler_fn(__a , __a , __a , __a ) lowerCamelCase__: Tuple =optax.adamw(learning_rate=__a , weight_decay=__a , mask=__a ) return tx, lr
59
from ...configuration_utils import PretrainedConfig from ...utils import logging A_ : str = logging.get_logger(__name__) A_ : Union[str, Any] = { 's-JoL/Open-Llama-V1': 'https://huggingface.co/s-JoL/Open-Llama-V1/blob/main/config.json', } class _lowerCAmelCase( UpperCAmelCase_ ): """simple docstring""" a : Tuple ='''open-llama''' def __init__( self , _lowerCamelCase=1_0_0_0_0_0 , _lowerCamelCase=4_0_9_6 , _lowerCamelCase=1_1_0_0_8 , _lowerCamelCase=3_2 , _lowerCamelCase=3_2 , _lowerCamelCase="silu" , _lowerCamelCase=2_0_4_8 , _lowerCamelCase=0.0_2 , _lowerCamelCase=1e-6 , _lowerCamelCase=True , _lowerCamelCase=0 , _lowerCamelCase=1 , _lowerCamelCase=2 , _lowerCamelCase=False , _lowerCamelCase=True , _lowerCamelCase=0.1 , _lowerCamelCase=0.1 , _lowerCamelCase=True , _lowerCamelCase=True , _lowerCamelCase=None , **_lowerCamelCase , ): UpperCamelCase_: int = vocab_size UpperCamelCase_: List[Any] = max_position_embeddings UpperCamelCase_: Dict = hidden_size UpperCamelCase_: Dict = intermediate_size UpperCamelCase_: Union[str, Any] = num_hidden_layers UpperCamelCase_: Dict = num_attention_heads UpperCamelCase_: Union[str, Any] = hidden_act UpperCamelCase_: Union[str, Any] = initializer_range UpperCamelCase_: List[Any] = rms_norm_eps UpperCamelCase_: Union[str, Any] = use_cache UpperCamelCase_: Dict = kwargs.pop( 'use_memorry_efficient_attention' , _lowerCamelCase ) UpperCamelCase_: Union[str, Any] = hidden_dropout_prob UpperCamelCase_: Any = attention_dropout_prob UpperCamelCase_: int = use_stable_embedding UpperCamelCase_: Tuple = shared_input_output_embedding UpperCamelCase_: str = rope_scaling self._rope_scaling_validation() super().__init__( pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , tie_word_embeddings=_lowerCamelCase , **_lowerCamelCase , ) def _a ( self ): if self.rope_scaling is None: return if not isinstance(self.rope_scaling , _lowerCamelCase ) or len(self.rope_scaling ) != 2: raise ValueError( '`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, ' f'''got {self.rope_scaling}''' ) UpperCamelCase_: str = self.rope_scaling.get('type' , _lowerCamelCase ) UpperCamelCase_: int = self.rope_scaling.get('factor' , _lowerCamelCase ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( f'''`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}''' ) if rope_scaling_factor is None or not isinstance(_lowerCamelCase , _lowerCamelCase ) or rope_scaling_factor <= 1.0: raise ValueError(f'''`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}''' )
57
0
from __future__ import annotations from collections.abc import Callable lowerCAmelCase_ = list[list[float | int]] def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> Matrix: """simple docstring""" snake_case_ : int = len(_UpperCamelCase ) snake_case_ : Matrix = [[0 for _ in range(size + 1 )] for _ in range(_UpperCamelCase )] snake_case_ : int snake_case_ : int snake_case_ : int snake_case_ : int snake_case_ : int snake_case_ : float for row in range(_UpperCamelCase ): for col in range(_UpperCamelCase ): snake_case_ : int = matrix[row][col] snake_case_ : int = vector[row][0] snake_case_ : str = 0 snake_case_ : List[str] = 0 while row < size and col < size: # pivoting snake_case_ : Any = max((abs(augmented[rowa][col] ), rowa) for rowa in range(_UpperCamelCase , _UpperCamelCase ) )[ 1 ] if augmented[pivot_row][col] == 0: col += 1 continue else: snake_case_ , snake_case_ : int = augmented[pivot_row], augmented[row] for rowa in range(row + 1 , _UpperCamelCase ): snake_case_ : Tuple = augmented[rowa][col] / augmented[row][col] snake_case_ : str = 0 for cola in range(col + 1 , size + 1 ): augmented[rowa][cola] -= augmented[row][cola] * ratio row += 1 col += 1 # back substitution for col in range(1 , _UpperCamelCase ): for row in range(_UpperCamelCase ): snake_case_ : Tuple = augmented[row][col] / augmented[col][col] for cola in range(_UpperCamelCase , size + 1 ): augmented[row][cola] -= augmented[col][cola] * ratio # round to get rid of numbers like 2.000000000000004 return [ [round(augmented[row][size] / augmented[row][row] , 10 )] for row in range(_UpperCamelCase ) ] def lowerCamelCase_ ( _UpperCamelCase ) -> Callable[[int], int]: """simple docstring""" snake_case_ : int = len(_UpperCamelCase ) snake_case_ : Matrix = [[0 for _ in range(_UpperCamelCase )] for _ in range(_UpperCamelCase )] snake_case_ : Matrix = [[0] for _ in range(_UpperCamelCase )] snake_case_ : Matrix snake_case_ : int snake_case_ : int snake_case_ : int for x_val, y_val in enumerate(_UpperCamelCase ): for col in range(_UpperCamelCase ): snake_case_ : str = (x_val + 1) ** (size - col - 1) snake_case_ : Optional[int] = y_val snake_case_ : Any = solve(_UpperCamelCase , _UpperCamelCase ) def interpolated_func(_UpperCamelCase ) -> int: return sum( round(coeffs[x_val][0] ) * (var ** (size - x_val - 1)) for x_val in range(_UpperCamelCase ) ) return interpolated_func def lowerCamelCase_ ( _UpperCamelCase ) -> int: """simple docstring""" return ( 1 - variable + variable**2 - variable**3 + variable**4 - variable**5 + variable**6 - variable**7 + variable**8 - variable**9 + variable**10 ) def lowerCamelCase_ ( _UpperCamelCase = question_function , _UpperCamelCase = 10 ) -> int: """simple docstring""" snake_case_ : list[int] = [func(_UpperCamelCase ) for x_val in range(1 , order + 1 )] snake_case_ : list[Callable[[int], int]] = [ interpolate(data_points[:max_coeff] ) for max_coeff in range(1 , order + 1 ) ] snake_case_ : int = 0 snake_case_ : Callable[[int], int] snake_case_ : int for poly in polynomials: snake_case_ : List[Any] = 1 while func(_UpperCamelCase ) == poly(_UpperCamelCase ): x_val += 1 ret += poly(_UpperCamelCase ) return ret if __name__ == "__main__": print(F'''{solution() = }''')
60
import collections import inspect import unittest from transformers import FocalNetConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( FocalNetBackbone, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetModel, ) from transformers.models.focalnet.modeling_focalnet import FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class _lowerCAmelCase: """simple docstring""" def __init__( self , _lowerCamelCase , _lowerCamelCase=1_3 , _lowerCamelCase=3_2 , _lowerCamelCase=2 , _lowerCamelCase=3 , _lowerCamelCase=1_6 , _lowerCamelCase=[3_2, 6_4, 1_2_8] , _lowerCamelCase=[1, 2, 1] , _lowerCamelCase=[2, 2, 4] , _lowerCamelCase=2 , _lowerCamelCase=2.0 , _lowerCamelCase=True , _lowerCamelCase=0.0 , _lowerCamelCase=0.0 , _lowerCamelCase=0.1 , _lowerCamelCase="gelu" , _lowerCamelCase=False , _lowerCamelCase=True , _lowerCamelCase=0.0_2 , _lowerCamelCase=1e-5 , _lowerCamelCase=True , _lowerCamelCase=None , _lowerCamelCase=True , _lowerCamelCase=1_0 , _lowerCamelCase=8 , _lowerCamelCase=["stage1", "stage2"] , _lowerCamelCase=[1, 2] , ): UpperCamelCase_: Tuple = parent UpperCamelCase_: Dict = batch_size UpperCamelCase_: List[str] = image_size UpperCamelCase_: Tuple = patch_size UpperCamelCase_: Tuple = num_channels UpperCamelCase_: Dict = embed_dim UpperCamelCase_: List[Any] = hidden_sizes UpperCamelCase_: List[str] = depths UpperCamelCase_: List[str] = num_heads UpperCamelCase_: Optional[int] = window_size UpperCamelCase_: Tuple = mlp_ratio UpperCamelCase_: Dict = qkv_bias UpperCamelCase_: str = hidden_dropout_prob UpperCamelCase_: Optional[Any] = attention_probs_dropout_prob UpperCamelCase_: int = drop_path_rate UpperCamelCase_: Dict = hidden_act UpperCamelCase_: List[str] = use_absolute_embeddings UpperCamelCase_: Dict = patch_norm UpperCamelCase_: Optional[Any] = layer_norm_eps UpperCamelCase_: List[str] = initializer_range UpperCamelCase_: List[Any] = is_training UpperCamelCase_: Optional[int] = scope UpperCamelCase_: str = use_labels UpperCamelCase_: List[str] = type_sequence_label_size UpperCamelCase_: Union[str, Any] = encoder_stride UpperCamelCase_: Dict = out_features UpperCamelCase_: str = out_indices def _a ( self ): UpperCamelCase_: int = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase_: List[Any] = None if self.use_labels: UpperCamelCase_: Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase_: Optional[Any] = self.get_config() return config, pixel_values, labels def _a ( self ): return FocalNetConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , hidden_sizes=self.hidden_sizes , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , out_features=self.out_features , out_indices=self.out_indices , ) def _a ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: Optional[int] = FocalNetModel(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() UpperCamelCase_: int = model(_lowerCamelCase ) UpperCamelCase_: int = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) UpperCamelCase_: int = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) ) def _a ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: List[str] = FocalNetBackbone(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() UpperCamelCase_: Optional[int] = model(_lowerCamelCase ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.image_size, 8, 8] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[:-1] ) # verify backbone works with out_features=None UpperCamelCase_: int = None UpperCamelCase_: List[Any] = FocalNetBackbone(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() UpperCamelCase_: Any = model(_lowerCamelCase ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.image_size * 2, 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def _a ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: Tuple = FocalNetForMaskedImageModeling(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() UpperCamelCase_: Any = model(_lowerCamelCase ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images UpperCamelCase_: List[Any] = 1 UpperCamelCase_: Dict = FocalNetForMaskedImageModeling(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() UpperCamelCase_: Optional[int] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) UpperCamelCase_: Union[str, Any] = model(_lowerCamelCase ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def _a ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: Tuple = self.type_sequence_label_size UpperCamelCase_: List[Any] = FocalNetForImageClassification(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() UpperCamelCase_: str = model(_lowerCamelCase , labels=_lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images UpperCamelCase_: Union[str, Any] = 1 UpperCamelCase_: Dict = FocalNetForImageClassification(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() UpperCamelCase_: Dict = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) UpperCamelCase_: Union[str, Any] = model(_lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def _a ( self ): UpperCamelCase_: Dict = self.prepare_config_and_inputs() UpperCamelCase_ ,UpperCamelCase_ ,UpperCamelCase_: List[str] = config_and_inputs UpperCamelCase_: int = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class _lowerCAmelCase( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase ): """simple docstring""" a : Optional[int] =( ( FocalNetModel, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetBackbone, ) if is_torch_available() else () ) a : Any =( {'''feature-extraction''': FocalNetModel, '''image-classification''': FocalNetForImageClassification} if is_torch_available() else {} ) a : Dict =False a : Union[str, Any] =False a : Tuple =False a : Optional[int] =False a : Union[str, Any] =False def _a ( self ): UpperCamelCase_: str = FocalNetModelTester(self ) UpperCamelCase_: Tuple = ConfigTester(self , config_class=_lowerCamelCase , embed_dim=3_7 , has_text_modality=_lowerCamelCase ) def _a ( self ): self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _a ( self ): return def _a ( self ): UpperCamelCase_: Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowerCamelCase ) def _a ( self ): UpperCamelCase_: List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*_lowerCamelCase ) def _a ( self ): UpperCamelCase_: Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*_lowerCamelCase ) def _a ( self ): UpperCamelCase_: Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_lowerCamelCase ) @unittest.skip(reason='FocalNet does not use inputs_embeds' ) def _a ( self ): pass @unittest.skip(reason='FocalNet does not use feedforward chunking' ) def _a ( self ): pass def _a ( self ): UpperCamelCase_ ,UpperCamelCase_: List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes[:-1]: UpperCamelCase_: Union[str, Any] = model_class(_lowerCamelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) UpperCamelCase_: List[str] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_lowerCamelCase , nn.Linear ) ) def _a ( self ): UpperCamelCase_ ,UpperCamelCase_: Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes[:-1]: UpperCamelCase_: List[Any] = model_class(_lowerCamelCase ) UpperCamelCase_: Optional[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase_: Any = [*signature.parameters.keys()] UpperCamelCase_: List[Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] , _lowerCamelCase ) def _a ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: Tuple = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() with torch.no_grad(): UpperCamelCase_: Tuple = model(**self._prepare_for_class(_lowerCamelCase , _lowerCamelCase ) ) UpperCamelCase_: Union[str, Any] = outputs.hidden_states UpperCamelCase_: Tuple = getattr( self.model_tester , 'expected_num_hidden_layers' , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(_lowerCamelCase ) , _lowerCamelCase ) # FocalNet has a different seq_length UpperCamelCase_: Optional[Any] = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) UpperCamelCase_: int = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) UpperCamelCase_: Dict = outputs.reshaped_hidden_states self.assertEqual(len(_lowerCamelCase ) , _lowerCamelCase ) UpperCamelCase_ ,UpperCamelCase_ ,UpperCamelCase_ ,UpperCamelCase_: int = reshaped_hidden_states[0].shape UpperCamelCase_: List[str] = ( reshaped_hidden_states[0].view(_lowerCamelCase , _lowerCamelCase , height * width ).permute(0 , 2 , 1 ) ) self.assertListEqual( list(reshaped_hidden_states.shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def _a ( self ): UpperCamelCase_ ,UpperCamelCase_: Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase_: int = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes[:-1]: UpperCamelCase_: int = True self.check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCamelCase_: Optional[Any] = True self.check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def _a ( self ): UpperCamelCase_ ,UpperCamelCase_: Dict = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase_: str = 3 UpperCamelCase_: Any = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) UpperCamelCase_: int = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) UpperCamelCase_: List[Any] = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) UpperCamelCase_: str = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes[:-1]: UpperCamelCase_: Dict = True self.check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCamelCase_: Optional[Any] = True self.check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , (padded_height, padded_width) ) @slow def _a ( self ): for model_name in FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase_: List[Any] = FocalNetModel.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) def _a ( self ): UpperCamelCase_ ,UpperCamelCase_: Dict = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase_: Dict = _config_zero_init(_lowerCamelCase ) for model_class in self.all_model_classes: UpperCamelCase_: List[str] = model_class(config=_lowerCamelCase ) for name, param in model.named_parameters(): if "embeddings" not in name and param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=f'''Parameter {name} of model {model_class} seems not properly initialized''' , ) @require_vision @require_torch class _lowerCAmelCase( unittest.TestCase ): """simple docstring""" @cached_property def _a ( self ): # TODO update organization return AutoImageProcessor.from_pretrained('microsoft/focalnet-tiny' ) if is_vision_available() else None @slow def _a ( self ): UpperCamelCase_: Optional[int] = FocalNetForImageClassification.from_pretrained('microsoft/focalnet-tiny' ).to(_lowerCamelCase ) UpperCamelCase_: Optional[Any] = self.default_image_processor UpperCamelCase_: str = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) UpperCamelCase_: str = image_processor(images=_lowerCamelCase , return_tensors='pt' ).to(_lowerCamelCase ) # forward pass with torch.no_grad(): UpperCamelCase_: List[str] = model(**_lowerCamelCase ) # verify the logits UpperCamelCase_: Optional[int] = torch.Size((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , _lowerCamelCase ) UpperCamelCase_: Optional[int] = torch.tensor([0.2_1_6_6, -0.4_3_6_8, 0.2_1_9_1] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _lowerCamelCase , atol=1e-4 ) ) self.assertTrue(outputs.logits.argmax(dim=-1 ).item() , 2_8_1 ) @require_torch class _lowerCAmelCase( UpperCAmelCase_ , unittest.TestCase ): """simple docstring""" a : Optional[Any] =(FocalNetBackbone,) if is_torch_available() else () a : List[str] =FocalNetConfig a : List[str] =False def _a ( self ): UpperCamelCase_: Any = FocalNetModelTester(self )
57
0
import unittest from transformers import load_tool from transformers.utils import is_torch_available if is_torch_available(): import torch from transformers.testing_utils import require_torch from .test_tools_common import ToolTesterMixin @require_torch class __lowerCamelCase ( unittest.TestCase , UpperCamelCase__ ): """simple docstring""" def a ( self : Tuple ) -> List[Any]: lowerCAmelCase__ = load_tool("text-to-speech" ) self.tool.setup() def a ( self : Dict ) -> Optional[int]: # SpeechT5 isn't deterministic torch.manual_seed(0 ) lowerCAmelCase__ = self.tool("hey" ) lowerCAmelCase__ = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.0_005_966_668_832_115_829, -0.0_003_657_640_190_795_064, -0.00_013_439_502_799_883_485] ) , ) ) def a ( self : List[Any] ) -> Union[str, Any]: # SpeechT5 isn't deterministic torch.manual_seed(0 ) lowerCAmelCase__ = self.tool("hey" ) lowerCAmelCase__ = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.0_005_966_668_832_115_829, -0.0_003_657_640_190_795_064, -0.00_013_439_502_799_883_485] ) , ) )
61
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) A_ : Tuple = { 'configuration_distilbert': [ 'DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'DistilBertConfig', 'DistilBertOnnxConfig', ], 'tokenization_distilbert': ['DistilBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : Optional[Any] = ['DistilBertTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : int = [ 'DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'DistilBertForMaskedLM', 'DistilBertForMultipleChoice', 'DistilBertForQuestionAnswering', 'DistilBertForSequenceClassification', 'DistilBertForTokenClassification', 'DistilBertModel', 'DistilBertPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : List[Any] = [ 'TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFDistilBertForMaskedLM', 'TFDistilBertForMultipleChoice', 'TFDistilBertForQuestionAnswering', 'TFDistilBertForSequenceClassification', 'TFDistilBertForTokenClassification', 'TFDistilBertMainLayer', 'TFDistilBertModel', 'TFDistilBertPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : int = [ 'FlaxDistilBertForMaskedLM', 'FlaxDistilBertForMultipleChoice', 'FlaxDistilBertForQuestionAnswering', 'FlaxDistilBertForSequenceClassification', 'FlaxDistilBertForTokenClassification', 'FlaxDistilBertModel', 'FlaxDistilBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_distilbert import ( DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DistilBertConfig, DistilBertOnnxConfig, ) from .tokenization_distilbert import DistilBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_distilbert_fast import DistilBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_distilbert import ( DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, DistilBertModel, DistilBertPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_distilbert import ( TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDistilBertForMaskedLM, TFDistilBertForMultipleChoice, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertMainLayer, TFDistilBertModel, TFDistilBertPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, FlaxDistilBertPreTrainedModel, ) else: import sys A_ : Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
57
0
import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device if is_torch_available(): from transformers import AutoModelForSeqaSeqLM, AutoTokenizer @require_torch @require_sentencepiece @require_tokenizers class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @slow def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : Any = AutoModelForSeqaSeqLM.from_pretrained("google/mt5-small" , return_dict=UpperCAmelCase_ ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = AutoTokenizer.from_pretrained("google/mt5-small" ) SCREAMING_SNAKE_CASE : str = tokenizer("Hello there" , return_tensors="pt" ).input_ids SCREAMING_SNAKE_CASE : Any = tokenizer("Hi I am" , return_tensors="pt" ).input_ids SCREAMING_SNAKE_CASE : str = model(input_ids.to(UpperCAmelCase_ ) , labels=labels.to(UpperCAmelCase_ ) ).loss SCREAMING_SNAKE_CASE : List[str] = -(labels.shape[-1] * loss.item()) SCREAMING_SNAKE_CASE : Any = -84.9_127 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1E-4 )
62
import os import socket from contextlib import contextmanager import torch from ..commands.config.default import write_basic_config # noqa: F401 from ..state import PartialState from .dataclasses import DistributedType from .imports import is_deepspeed_available, is_tpu_available from .transformer_engine import convert_model from .versions import is_torch_version if is_deepspeed_available(): from deepspeed import DeepSpeedEngine if is_tpu_available(check_device=False): import torch_xla.core.xla_model as xm def snake_case (UpperCAmelCase__ ) -> Union[str, Any]: if is_torch_version('<' , '2.0.0' ) or not hasattr(UpperCAmelCase__ , '_dynamo' ): return False return isinstance(UpperCAmelCase__ , torch._dynamo.eval_frame.OptimizedModule ) def snake_case (UpperCAmelCase__ , UpperCAmelCase__ = True ) -> Any: UpperCamelCase_: Optional[Any] = (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel) UpperCamelCase_: int = is_compiled_module(UpperCAmelCase__ ) if is_compiled: UpperCamelCase_: List[str] = model UpperCamelCase_: Dict = model._orig_mod if is_deepspeed_available(): options += (DeepSpeedEngine,) while isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): UpperCamelCase_: Dict = model.module if not keep_fpaa_wrapper: UpperCamelCase_: int = getattr(UpperCAmelCase__ , 'forward' ) UpperCamelCase_: List[str] = model.__dict__.pop('_original_forward' , UpperCAmelCase__ ) if original_forward is not None: while hasattr(UpperCAmelCase__ , '__wrapped__' ): UpperCamelCase_: Any = forward.__wrapped__ if forward == original_forward: break UpperCamelCase_: Optional[int] = forward if getattr(UpperCAmelCase__ , '_converted_to_transformer_engine' , UpperCAmelCase__ ): convert_model(UpperCAmelCase__ , to_transformer_engine=UpperCAmelCase__ ) if is_compiled: UpperCamelCase_: Union[str, Any] = model UpperCamelCase_: Tuple = compiled_model return model def snake_case () -> List[str]: PartialState().wait_for_everyone() def snake_case (UpperCAmelCase__ , UpperCAmelCase__ ) -> Dict: if PartialState().distributed_type == DistributedType.TPU: xm.save(UpperCAmelCase__ , UpperCAmelCase__ ) elif PartialState().local_process_index == 0: torch.save(UpperCAmelCase__ , UpperCAmelCase__ ) @contextmanager def snake_case (**UpperCAmelCase__ ) -> Any: for key, value in kwargs.items(): UpperCamelCase_: int = str(UpperCAmelCase__ ) yield for key in kwargs: if key.upper() in os.environ: del os.environ[key.upper()] def snake_case (UpperCAmelCase__ ) -> str: if not hasattr(UpperCAmelCase__ , '__qualname__' ) and not hasattr(UpperCAmelCase__ , '__name__' ): UpperCamelCase_: List[Any] = getattr(UpperCAmelCase__ , '__class__' , UpperCAmelCase__ ) if hasattr(UpperCAmelCase__ , '__qualname__' ): return obj.__qualname__ if hasattr(UpperCAmelCase__ , '__name__' ): return obj.__name__ return str(UpperCAmelCase__ ) def snake_case (UpperCAmelCase__ , UpperCAmelCase__ ) -> Any: for key, value in source.items(): if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): UpperCamelCase_: Any = destination.setdefault(UpperCAmelCase__ , {} ) merge_dicts(UpperCAmelCase__ , UpperCAmelCase__ ) else: UpperCamelCase_: str = value return destination def snake_case (UpperCAmelCase__ = None ) -> bool: if port is None: UpperCamelCase_: List[str] = 2_9_5_0_0 with socket.socket(socket.AF_INET , socket.SOCK_STREAM ) as s: return s.connect_ex(('localhost', port) ) == 0
57
0
import inspect import tempfile import unittest from huggingface_hub import hf_hub_download from transformers import is_torch_available from transformers.testing_utils import is_flaky, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin a : Union[str, Any] = 1e-4 if is_torch_available(): import torch from transformers import AutoformerConfig, AutoformerForPrediction, AutoformerModel from transformers.models.autoformer.modeling_autoformer import AutoformerDecoder, AutoformerEncoder @require_torch class a : """simple docstring""" def __init__( self : str , __lowercase : Any , __lowercase : Optional[int]=16 , __lowercase : Union[str, Any]=13 , __lowercase : int=7 , __lowercase : List[Any]=14 , __lowercase : List[Any]=10 , __lowercase : List[str]=19 , __lowercase : List[str]=5 , __lowercase : Optional[int]=4 , __lowercase : int=True , __lowercase : Dict=16 , __lowercase : Any=2 , __lowercase : Union[str, Any]=4 , __lowercase : Optional[Any]=4 , __lowercase : Union[str, Any]="gelu" , __lowercase : Optional[Any]=0.1 , __lowercase : Dict=0.1 , __lowercase : List[str]=[1, 2, 3, 4, 5] , __lowercase : Optional[Any]=25 , __lowercase : List[str]=5 , ) -> Dict: __UpperCAmelCase : Any = d_model __UpperCAmelCase : Dict = parent __UpperCAmelCase : List[Any] = batch_size __UpperCAmelCase : List[str] = prediction_length __UpperCAmelCase : Dict = context_length __UpperCAmelCase : Any = cardinality __UpperCAmelCase : Any = num_time_features __UpperCAmelCase : Optional[Any] = lags_sequence __UpperCAmelCase : Union[str, Any] = embedding_dimension __UpperCAmelCase : List[str] = is_training __UpperCAmelCase : Optional[int] = hidden_size __UpperCAmelCase : List[Any] = num_hidden_layers __UpperCAmelCase : List[str] = num_attention_heads __UpperCAmelCase : Optional[Any] = intermediate_size __UpperCAmelCase : List[str] = hidden_act __UpperCAmelCase : Any = hidden_dropout_prob __UpperCAmelCase : List[str] = attention_probs_dropout_prob __UpperCAmelCase : Any = context_length __UpperCAmelCase : int = prediction_length + label_length __UpperCAmelCase : List[str] = label_length __UpperCAmelCase : Union[str, Any] = moving_average __UpperCAmelCase : Optional[int] = autocorrelation_factor def UpperCAmelCase ( self : Tuple ) -> List[Any]: return AutoformerConfig( d_model=self.d_model , 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 , prediction_length=self.prediction_length , context_length=self.context_length , label_length=self.label_length , lags_sequence=self.lags_sequence , num_time_features=self.num_time_features , num_static_categorical_features=1 , cardinality=[self.cardinality] , embedding_dimension=[self.embedding_dimension] , moving_average=self.moving_average , ) def UpperCAmelCase ( self : Optional[int] , __lowercase : str ) -> Optional[Any]: __UpperCAmelCase : Tuple = config.context_length + max(config.lags_sequence ) __UpperCAmelCase : str = ids_tensor([self.batch_size, 1] , config.cardinality[0] ) __UpperCAmelCase : str = floats_tensor([self.batch_size, _past_length, config.num_time_features] ) __UpperCAmelCase : Dict = floats_tensor([self.batch_size, _past_length] ) __UpperCAmelCase : Dict = floats_tensor([self.batch_size, _past_length] ) > 0.5 # decoder inputs __UpperCAmelCase : Optional[int] = floats_tensor([self.batch_size, config.prediction_length, config.num_time_features] ) __UpperCAmelCase : Any = floats_tensor([self.batch_size, config.prediction_length] ) __UpperCAmelCase : Union[str, Any] = { """past_values""": past_values, """static_categorical_features""": static_categorical_features, """past_time_features""": past_time_features, """past_observed_mask""": past_observed_mask, """future_time_features""": future_time_features, """future_values""": future_values, } return inputs_dict def UpperCAmelCase ( self : Dict ) -> List[Any]: __UpperCAmelCase : Any = self.get_config() __UpperCAmelCase : int = self.prepare_autoformer_inputs_dict(__lowercase ) return config, inputs_dict def UpperCAmelCase ( self : Any ) -> Optional[int]: __UpperCAmelCase , __UpperCAmelCase : List[str] = self.prepare_config_and_inputs() return config, inputs_dict def UpperCAmelCase ( self : Optional[Any] , __lowercase : Optional[Any] , __lowercase : Union[str, Any] ) -> int: __UpperCAmelCase : int = AutoformerModel(config=__lowercase ).to(__lowercase ).eval() __UpperCAmelCase : int = model(**__lowercase ) __UpperCAmelCase : Optional[Any] = outputs.encoder_last_hidden_state __UpperCAmelCase : Tuple = outputs.last_hidden_state with tempfile.TemporaryDirectory() as tmpdirname: __UpperCAmelCase : int = model.get_encoder() encoder.save_pretrained(__lowercase ) __UpperCAmelCase : List[str] = AutoformerEncoder.from_pretrained(__lowercase ).to(__lowercase ) __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase : List[Any] = model.create_network_inputs(**__lowercase ) __UpperCAmelCase , __UpperCAmelCase : Tuple = model.decomposition_layer(transformer_inputs[:, : config.context_length, ...] ) __UpperCAmelCase : Tuple = torch.cat( (transformer_inputs[:, : config.context_length, ...], feature[:, : config.context_length, ...]) , dim=-1 , ) __UpperCAmelCase : str = encoder(inputs_embeds=__lowercase )[0] self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1e-3 ) __UpperCAmelCase : int = ( torch.mean(transformer_inputs[:, : config.context_length, ...] , dim=1 ) .unsqueeze(1 ) .repeat(1 , config.prediction_length , 1 ) ) __UpperCAmelCase : int = torch.zeros( [transformer_inputs.shape[0], config.prediction_length, transformer_inputs.shape[2]] , device=enc_input.device , ) __UpperCAmelCase : int = torch.cat( ( torch.cat((seasonal_input[:, -config.label_length :, ...], zeros) , dim=1 ), feature[:, config.context_length - config.label_length :, ...], ) , dim=-1 , ) __UpperCAmelCase : Dict = torch.cat( ( torch.cat((trend_input[:, -config.label_length :, ...], mean) , dim=1 ), feature[:, config.context_length - config.label_length :, ...], ) , dim=-1 , ) with tempfile.TemporaryDirectory() as tmpdirname: __UpperCAmelCase : Optional[Any] = model.get_decoder() decoder.save_pretrained(__lowercase ) __UpperCAmelCase : List[Any] = AutoformerDecoder.from_pretrained(__lowercase ).to(__lowercase ) __UpperCAmelCase : Optional[int] = decoder( trend=__lowercase , inputs_embeds=__lowercase , encoder_hidden_states=__lowercase , )[0] self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1e-3 ) @require_torch class a ( lowercase__ , lowercase__ , unittest.TestCase ): """simple docstring""" a : Dict = (AutoformerModel, AutoformerForPrediction) if is_torch_available() else () a : Any = (AutoformerForPrediction,) if is_torch_available() else () a : Dict = {'feature-extraction': AutoformerModel} if is_torch_available() else {} a : Optional[int] = False a : List[str] = False a : str = False a : Optional[int] = False a : Union[str, Any] = False a : Tuple = False def UpperCAmelCase ( self : Union[str, Any] ) -> List[str]: __UpperCAmelCase : Tuple = AutoformerModelTester(self ) __UpperCAmelCase : Dict = ConfigTester(self , config_class=__lowercase , has_text_modality=__lowercase ) def UpperCAmelCase ( self : Any ) -> Tuple: self.config_tester.run_common_tests() def UpperCAmelCase ( self : Dict ) -> str: __UpperCAmelCase , __UpperCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: __UpperCAmelCase : Any = model_class(__lowercase ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(__lowercase ) __UpperCAmelCase , __UpperCAmelCase : Union[str, Any] = model_class.from_pretrained(__lowercase , output_loading_info=__lowercase ) self.assertEqual(info["""missing_keys"""] , [] ) def UpperCAmelCase ( self : Optional[Any] ) -> int: __UpperCAmelCase : str = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_encoder_decoder_model_standalone(*__lowercase ) @unittest.skip(reason="""Model has no tokens embeddings""" ) def UpperCAmelCase ( self : Any ) -> List[Any]: pass def UpperCAmelCase ( self : Any ) -> Optional[Any]: __UpperCAmelCase : Any = inspect.signature(getattr(__lowercase , """forward""" ) ) # The main input is the name of the argument after `self` __UpperCAmelCase : Optional[int] = list(model_signature.parameters.keys() )[1] self.assertEqual(AutoformerModel.main_input_name , __lowercase ) def UpperCAmelCase ( self : Optional[int] ) -> Union[str, Any]: __UpperCAmelCase , __UpperCAmelCase : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __UpperCAmelCase : Tuple = model_class(__lowercase ) __UpperCAmelCase : Any = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __UpperCAmelCase : Tuple = [*signature.parameters.keys()] __UpperCAmelCase : Tuple = [ """past_values""", """past_time_features""", """past_observed_mask""", """static_categorical_features""", """static_real_features""", """future_values""", """future_time_features""", ] if model.__class__.__name__ in ["AutoformerForPrediction"]: expected_arg_names.append("""future_observed_mask""" ) expected_arg_names.extend( [ """decoder_attention_mask""", """head_mask""", """decoder_head_mask""", """cross_attn_head_mask""", """encoder_outputs""", """past_key_values""", """output_hidden_states""", """output_attentions""", """use_cache""", """return_dict""", ] ) self.assertListEqual(arg_names[: len(__lowercase )] , __lowercase ) def UpperCAmelCase ( self : int ) -> Optional[int]: __UpperCAmelCase , __UpperCAmelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() __UpperCAmelCase : Any = True __UpperCAmelCase : List[str] = getattr(self.model_tester , """seq_length""" , __lowercase ) __UpperCAmelCase : Optional[int] = getattr(self.model_tester , """decoder_seq_length""" , __lowercase ) __UpperCAmelCase : Dict = getattr(self.model_tester , """encoder_seq_length""" , __lowercase ) __UpperCAmelCase : Union[str, Any] = getattr(self.model_tester , """d_model""" , __lowercase ) __UpperCAmelCase : List[Any] = getattr(self.model_tester , """num_attention_heads""" , __lowercase ) __UpperCAmelCase : List[Any] = d_model // num_attention_heads for model_class in self.all_model_classes: __UpperCAmelCase : Dict = True __UpperCAmelCase : str = False __UpperCAmelCase : Optional[Any] = True __UpperCAmelCase : Union[str, Any] = model_class(__lowercase ) model.to(__lowercase ) model.eval() with torch.no_grad(): __UpperCAmelCase : int = model(**self._prepare_for_class(__lowercase , __lowercase ) ) __UpperCAmelCase : List[Any] = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(__lowercase ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] __UpperCAmelCase : int = True __UpperCAmelCase : int = model_class(__lowercase ) model.to(__lowercase ) model.eval() with torch.no_grad(): __UpperCAmelCase : List[str] = model(**self._prepare_for_class(__lowercase , __lowercase ) ) __UpperCAmelCase : Optional[int] = outputs.encoder_attentions self.assertEqual(len(__lowercase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, dim] , ) __UpperCAmelCase : List[str] = len(__lowercase ) __UpperCAmelCase : Union[str, Any] = 7 if "last_hidden_state" in outputs: correct_outlen += 1 if "trend" in outputs: correct_outlen += 1 if "past_key_values" in outputs: correct_outlen += 1 # past_key_values have been returned if "loss" in outputs: correct_outlen += 1 if "params" in outputs: correct_outlen += 1 self.assertEqual(__lowercase , __lowercase ) # decoder attentions __UpperCAmelCase : List[Any] = outputs.decoder_attentions self.assertIsInstance(__lowercase , (list, tuple) ) self.assertEqual(len(__lowercase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, decoder_seq_length, dim] , ) # cross attentions __UpperCAmelCase : Tuple = outputs.cross_attentions self.assertIsInstance(__lowercase , (list, tuple) ) self.assertEqual(len(__lowercase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(cross_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, decoder_seq_length, dim] , ) # Check attention is always last and order is fine __UpperCAmelCase : List[Any] = True __UpperCAmelCase : int = True __UpperCAmelCase : List[str] = model_class(__lowercase ) model.to(__lowercase ) model.eval() with torch.no_grad(): __UpperCAmelCase : int = model(**self._prepare_for_class(__lowercase , __lowercase ) ) self.assertEqual(out_len + 2 , len(__lowercase ) ) __UpperCAmelCase : Dict = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(__lowercase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, dim] , ) @is_flaky() def UpperCAmelCase ( self : Union[str, Any] ) -> Optional[int]: super().test_retain_grad_hidden_states_attentions() def lowerCamelCase__ ( __lowerCamelCase : Tuple="train-batch.pt" ): __UpperCAmelCase : str = hf_hub_download(repo_id="""hf-internal-testing/tourism-monthly-batch""" , filename=__lowerCamelCase , repo_type="""dataset""" ) __UpperCAmelCase : Optional[Any] = torch.load(__lowerCamelCase , map_location=__lowerCamelCase ) return batch @require_torch @slow class a ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase ( self : List[Any] ) -> List[Any]: __UpperCAmelCase : Dict = AutoformerModel.from_pretrained("""huggingface/autoformer-tourism-monthly""" ).to(__lowercase ) __UpperCAmelCase : Dict = prepare_batch() with torch.no_grad(): __UpperCAmelCase : int = model( past_values=batch["""past_values"""] , past_time_features=batch["""past_time_features"""] , past_observed_mask=batch["""past_observed_mask"""] , static_categorical_features=batch["""static_categorical_features"""] , future_values=batch["""future_values"""] , future_time_features=batch["""future_time_features"""] , )[0] __UpperCAmelCase : Dict = torch.Size( (64, model.config.prediction_length + model.config.label_length, model.config.feature_size) ) self.assertEqual(output.shape , __lowercase ) __UpperCAmelCase : Optional[int] = torch.tensor( [[0.3_593, -1.3_398, 0.6_330], [0.2_279, 1.5_396, -0.1_792], [0.0_450, 1.3_225, -0.2_335]] , device=__lowercase ) self.assertTrue(torch.allclose(output[0, :3, :3] , __lowercase , atol=__lowercase ) ) def UpperCAmelCase ( self : str ) -> Union[str, Any]: __UpperCAmelCase : Union[str, Any] = AutoformerForPrediction.from_pretrained("""huggingface/autoformer-tourism-monthly""" ).to(__lowercase ) __UpperCAmelCase : List[str] = prepare_batch("""val-batch.pt""" ) with torch.no_grad(): __UpperCAmelCase : Any = model( past_values=batch["""past_values"""] , past_time_features=batch["""past_time_features"""] , past_observed_mask=batch["""past_observed_mask"""] , static_categorical_features=batch["""static_categorical_features"""] , ).encoder_last_hidden_state __UpperCAmelCase : Optional[int] = torch.Size((64, model.config.context_length, model.config.d_model) ) self.assertEqual(output.shape , __lowercase ) __UpperCAmelCase : Dict = torch.tensor( [[-0.0_734, -0.9_036, 0.8_358], [4.7_186, 2.4_113, 1.9_581], [1.7_953, 2.3_558, 1.2_970]] , device=__lowercase ) self.assertTrue(torch.allclose(output[0, :3, :3] , __lowercase , atol=__lowercase ) ) def UpperCAmelCase ( self : Optional[Any] ) -> Optional[int]: __UpperCAmelCase : Union[str, Any] = AutoformerForPrediction.from_pretrained("""huggingface/autoformer-tourism-monthly""" ).to(__lowercase ) __UpperCAmelCase : Optional[int] = prepare_batch("""val-batch.pt""" ) with torch.no_grad(): __UpperCAmelCase : int = model.generate( static_categorical_features=batch["""static_categorical_features"""] , past_time_features=batch["""past_time_features"""] , past_values=batch["""past_values"""] , future_time_features=batch["""future_time_features"""] , past_observed_mask=batch["""past_observed_mask"""] , ) __UpperCAmelCase : Optional[Any] = torch.Size((64, model.config.num_parallel_samples, model.config.prediction_length) ) self.assertEqual(outputs.sequences.shape , __lowercase ) __UpperCAmelCase : Optional[Any] = torch.tensor([3_130.6_763, 4_056.5_293, 7_053.0_786] , device=__lowercase ) __UpperCAmelCase : List[str] = outputs.sequences.mean(dim=1 ) self.assertTrue(torch.allclose(mean_prediction[0, -3:] , __lowercase , rtol=1e-1 ) )
63
import argparse import os import pickle import sys import torch from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() # We do this to be able to load python 2 datasets pickles # See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918 A_ : Optional[Any] = data_utils.TransfoXLTokenizer A_ : Union[str, Any] = data_utils.TransfoXLCorpus A_ : Any = data_utils A_ : Optional[Any] = data_utils def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) -> List[str]: if transfo_xl_dataset_file: # Convert a pre-processed corpus (see original TensorFlow repo) with open(UpperCAmelCase__ , 'rb' ) as fp: UpperCamelCase_: Union[str, Any] = pickle.load(UpperCAmelCase__ , encoding='latin1' ) # Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term) UpperCamelCase_: Any = pytorch_dump_folder_path + '/' + VOCAB_FILES_NAMES['pretrained_vocab_file'] print(F'''Save vocabulary to {pytorch_vocab_dump_path}''' ) UpperCamelCase_: Union[str, Any] = corpus.vocab.__dict__ torch.save(UpperCAmelCase__ , UpperCAmelCase__ ) UpperCamelCase_: str = corpus.__dict__ corpus_dict_no_vocab.pop('vocab' , UpperCAmelCase__ ) UpperCamelCase_: str = pytorch_dump_folder_path + '/' + CORPUS_NAME print(F'''Save dataset to {pytorch_dataset_dump_path}''' ) torch.save(UpperCAmelCase__ , UpperCAmelCase__ ) if tf_checkpoint_path: # Convert a pre-trained TensorFlow model UpperCamelCase_: Any = os.path.abspath(UpperCAmelCase__ ) UpperCamelCase_: Dict = os.path.abspath(UpperCAmelCase__ ) print(F'''Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.''' ) # Initialise PyTorch model if transfo_xl_config_file == "": UpperCamelCase_: List[str] = TransfoXLConfig() else: UpperCamelCase_: Optional[int] = TransfoXLConfig.from_json_file(UpperCAmelCase__ ) print(F'''Building PyTorch model from configuration: {config}''' ) UpperCamelCase_: Union[str, Any] = TransfoXLLMHeadModel(UpperCAmelCase__ ) UpperCamelCase_: Tuple = load_tf_weights_in_transfo_xl(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) # Save pytorch-model UpperCamelCase_: str = os.path.join(UpperCAmelCase__ , UpperCAmelCase__ ) UpperCamelCase_: Union[str, Any] = os.path.join(UpperCAmelCase__ , UpperCAmelCase__ ) print(F'''Save PyTorch model to {os.path.abspath(UpperCAmelCase__ )}''' ) torch.save(model.state_dict() , UpperCAmelCase__ ) print(F'''Save configuration file to {os.path.abspath(UpperCAmelCase__ )}''' ) with open(UpperCAmelCase__ , 'w' , encoding='utf-8' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": A_ : int = argparse.ArgumentParser() parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the folder to store the PyTorch model or dataset/vocab.', ) parser.add_argument( '--tf_checkpoint_path', default='', type=str, help='An optional path to a TensorFlow checkpoint path to be converted.', ) parser.add_argument( '--transfo_xl_config_file', default='', type=str, help=( 'An optional config json file corresponding to the pre-trained BERT model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--transfo_xl_dataset_file', default='', type=str, help='An optional dataset file to be converted in a vocabulary.', ) A_ : Tuple = parser.parse_args() convert_transfo_xl_checkpoint_to_pytorch( args.tf_checkpoint_path, args.transfo_xl_config_file, args.pytorch_dump_folder_path, args.transfo_xl_dataset_file, )
57
0
import os import re import unicodedata from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import is_torch_available, logging if is_torch_available(): import torch if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation lowercase_ : Any = logging.get_logger(__name__) lowercase_ : List[str] = {'vocab_file': 'spiece.model'} lowercase_ : Dict = { 'vocab_file': { 'AI-Sweden/gpt-sw3-126m': 'https://huggingface.co/AI-Sweden/gpt-sw3-126m/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-350m': 'https://huggingface.co/AI-Sweden/gpt-sw3-350m/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-1.6b': 'https://huggingface.co/AI-Sweden/gpt-sw3-1.6b/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-6.7b': 'https://huggingface.co/AI-Sweden/gpt-sw3-6.7b/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-20b': 'https://huggingface.co/AI-Sweden/gpt-sw3-20b/resolve/main/spiece.model', } } lowercase_ : Tuple = { 'AI-Sweden/gpt-sw3-126m': 2_0_4_8, 'AI-Sweden/gpt-sw3-350m': 2_0_4_8, 'AI-Sweden/gpt-sw3-1.6b': 2_0_4_8, 'AI-Sweden/gpt-sw3-6.7b': 2_0_4_8, 'AI-Sweden/gpt-sw3-20b': 2_0_4_8, } class _lowerCamelCase ( UpperCamelCase_ ): __a = VOCAB_FILES_NAMES __a = PRETRAINED_VOCAB_FILES_MAP __a = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __a = ["input_ids", "attention_mask"] def __init__( self , lowerCAmelCase , lowerCAmelCase=False , lowerCAmelCase=False , lowerCAmelCase=False , lowerCAmelCase=None , lowerCAmelCase=None , lowerCAmelCase=None , lowerCAmelCase=None , lowerCAmelCase = None , **lowerCAmelCase , ) -> None: SCREAMING_SNAKE_CASE__: Optional[Any]= {} if sp_model_kwargs is None else sp_model_kwargs SCREAMING_SNAKE_CASE__: Union[str, Any]= kwargs.get('''name_or_path''' ) if name_or_path is None: logger.warning( '''name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b,''' ''' you are testing the model, this can safely be ignored''' ) SCREAMING_SNAKE_CASE__: Dict= '''None''' # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing SCREAMING_SNAKE_CASE__: List[Any]= '''<|endoftext|>''' if eos_token is None else eos_token SCREAMING_SNAKE_CASE__: List[Any]= '''<unk>''' if unk_token is None else unk_token if "gpt-sw3-7b" in name_or_path: SCREAMING_SNAKE_CASE__: List[str]= unk_token if pad_token is None else pad_token SCREAMING_SNAKE_CASE__: Dict= eos_token if bos_token is None else bos_token else: SCREAMING_SNAKE_CASE__: Optional[Any]= '''<pad>''' if pad_token is None else pad_token SCREAMING_SNAKE_CASE__: List[Any]= '''<s>''' if bos_token is None else bos_token super().__init__( do_lower_case=lowerCAmelCase , remove_space=lowerCAmelCase , keep_accents=lowerCAmelCase , bos_token=lowerCAmelCase , eos_token=lowerCAmelCase , unk_token=lowerCAmelCase , pad_token=lowerCAmelCase , sp_model_kwargs=self.sp_model_kwargs , **lowerCAmelCase , ) SCREAMING_SNAKE_CASE__: Union[str, Any]= do_lower_case SCREAMING_SNAKE_CASE__: int= remove_space SCREAMING_SNAKE_CASE__: List[str]= keep_accents SCREAMING_SNAKE_CASE__: int= vocab_file SCREAMING_SNAKE_CASE__: int= spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(lowerCAmelCase ) # Used for whitespace normalization in input texts # fmt : off SCREAMING_SNAKE_CASE__: Optional[int]= {''' ''', ''' ''', ''' ''', ''' ''', ''' ''', ''' ''', ''' ''', ''' ''', ''' ''', ''' ''', '''''', '''„'''} # fmt : on # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing SCREAMING_SNAKE_CASE__: str= re.compile( f'[{"".join(map(lowerCAmelCase , list(range(0 , 9 ) ) + list(range(11 , 32 ) ) + list(range(127 , 160 ) ) + [160, 173, 8203] ) )}]' ) def __getstate__( self ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__: Any= self.__dict__.copy() SCREAMING_SNAKE_CASE__: Dict= None return state def __setstate__( self , lowerCAmelCase ) -> List[Any]: SCREAMING_SNAKE_CASE__: List[Any]= d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): SCREAMING_SNAKE_CASE__: Union[str, Any]= {} SCREAMING_SNAKE_CASE__: Tuple= spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) @property # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.vocab_size def UpperCamelCase_ ( self ) -> int: return len(self.sp_model ) def UpperCamelCase_ ( self , lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__: Any= self.non_printing_characters_re.sub('''''' , lowerCAmelCase ) # Normalize whitespaces SCREAMING_SNAKE_CASE__: Any= ''''''.join([char if char not in self.whitespaces else ''' ''' for char in text] ) # NFC Unicode normalization SCREAMING_SNAKE_CASE__: Optional[Any]= unicodedata.normalize('''NFC''' , lowerCAmelCase ) return text def UpperCamelCase_ ( self , lowerCAmelCase , **lowerCAmelCase ) -> List[str]: SCREAMING_SNAKE_CASE__: Union[str, Any]= self.preprocess_text(lowerCAmelCase ) return self.sp_model.encode(lowerCAmelCase , out_type=lowerCAmelCase ) def UpperCamelCase_ ( self , lowerCAmelCase ) -> int: return self.sp_model.PieceToId(lowerCAmelCase ) def UpperCamelCase_ ( self , lowerCAmelCase ) -> str: return self.sp_model.IdToPiece(lowerCAmelCase ) @staticmethod def UpperCamelCase_ ( lowerCAmelCase ) -> str: return out_string def UpperCamelCase_ ( self , lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__: Union[str, Any]= [] SCREAMING_SNAKE_CASE__: Optional[int]= '''''' SCREAMING_SNAKE_CASE__: Any= False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: # TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document if not prev_is_special: out_string += " " out_string += self.sp_model.decode(lowerCAmelCase ) + token SCREAMING_SNAKE_CASE__: Union[str, Any]= True SCREAMING_SNAKE_CASE__: Tuple= [] else: current_sub_tokens.append(lowerCAmelCase ) SCREAMING_SNAKE_CASE__: int= False out_string += self.sp_model.decode(lowerCAmelCase ) return out_string def UpperCamelCase_ ( self ) -> Dict[str, int]: SCREAMING_SNAKE_CASE__: List[Any]= {self.convert_ids_to_tokens(lowerCAmelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def UpperCamelCase_ ( self , lowerCAmelCase , lowerCAmelCase = None ) -> Tuple[str]: if not os.path.isdir(lowerCAmelCase ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return SCREAMING_SNAKE_CASE__: Optional[int]= os.path.join( lowerCAmelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowerCAmelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , lowerCAmelCase ) elif not os.path.isfile(self.vocab_file ): with open(lowerCAmelCase , '''wb''' ) as fi: SCREAMING_SNAKE_CASE__: Optional[Any]= self.sp_model.serialized_model_proto() fi.write(lowerCAmelCase ) return (out_vocab_file,) def UpperCamelCase_ ( self , lowerCAmelCase , lowerCAmelCase = False ) -> Union[List[int], List[List[int]], "torch.Tensor"]: if isinstance(lowerCAmelCase , lowerCAmelCase ): SCREAMING_SNAKE_CASE__: List[Any]= self.preprocess_text(lowerCAmelCase ) SCREAMING_SNAKE_CASE__: Optional[int]= self.sp_model.encode(lowerCAmelCase ) else: SCREAMING_SNAKE_CASE__: Dict= [self.preprocess_text(lowerCAmelCase ) for t in text] SCREAMING_SNAKE_CASE__: Optional[Any]= self.sp_model.encode(lowerCAmelCase ) if return_tensors is True or return_tensors == "pt": SCREAMING_SNAKE_CASE__: Dict= torch.tensor(lowerCAmelCase ) return token_ids def UpperCamelCase_ ( self , lowerCAmelCase ) -> str: return self.sp_model.decode(lowerCAmelCase ) def UpperCamelCase_ ( self , lowerCAmelCase ) -> List[int]: SCREAMING_SNAKE_CASE__: Tuple= [f'User: {text}' if is_user else f'Bot: {text}' for is_user, text in conversation.iter_texts()] SCREAMING_SNAKE_CASE__: int= ( f'{self.eos_token}{self.bos_token}' + f'{self.bos_token}'.join(lowerCAmelCase ) + f'{self.bos_token}Bot:' ) return self.encode(text=lowerCAmelCase )
64
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL A_ : List[str] = logging.get_logger(__name__) def snake_case (UpperCAmelCase__ , UpperCAmelCase__ ) -> Union[str, Any]: UpperCamelCase_: Tuple = b.T UpperCamelCase_: Tuple = np.sum(np.square(UpperCAmelCase__ ) , axis=1 ) UpperCamelCase_: Optional[Any] = np.sum(np.square(UpperCAmelCase__ ) , axis=0 ) UpperCamelCase_: Optional[int] = np.matmul(UpperCAmelCase__ , UpperCAmelCase__ ) UpperCamelCase_: List[Any] = aa[:, None] - 2 * ab + ba[None, :] return d def snake_case (UpperCAmelCase__ , UpperCAmelCase__ ) -> Optional[Any]: UpperCamelCase_: List[str] = x.reshape(-1 , 3 ) UpperCamelCase_: Union[str, Any] = squared_euclidean_distance(UpperCAmelCase__ , UpperCAmelCase__ ) return np.argmin(UpperCAmelCase__ , axis=1 ) class _lowerCAmelCase( UpperCAmelCase_ ): """simple docstring""" a : Any =['''pixel_values'''] def __init__( self , _lowerCamelCase = None , _lowerCamelCase = True , _lowerCamelCase = None , _lowerCamelCase = PILImageResampling.BILINEAR , _lowerCamelCase = True , _lowerCamelCase = True , **_lowerCamelCase , ): super().__init__(**_lowerCamelCase ) UpperCamelCase_: List[str] = size if size is not None else {'height': 2_5_6, 'width': 2_5_6} UpperCamelCase_: str = get_size_dict(_lowerCamelCase ) UpperCamelCase_: Any = np.array(_lowerCamelCase ) if clusters is not None else None UpperCamelCase_: Optional[int] = do_resize UpperCamelCase_: List[Any] = size UpperCamelCase_: Optional[int] = resample UpperCamelCase_: str = do_normalize UpperCamelCase_: str = do_color_quantize def _a ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = PILImageResampling.BILINEAR , _lowerCamelCase = None , **_lowerCamelCase , ): UpperCamelCase_: Any = get_size_dict(_lowerCamelCase ) if "height" not in size or "width" not in size: raise ValueError(f'''Size dictionary must contain both height and width keys. Got {size.keys()}''' ) return resize( _lowerCamelCase , size=(size['height'], size['width']) , resample=_lowerCamelCase , data_format=_lowerCamelCase , **_lowerCamelCase ) def _a ( self , _lowerCamelCase , _lowerCamelCase = None , ): UpperCamelCase_: Optional[Any] = rescale(image=_lowerCamelCase , scale=1 / 1_2_7.5 , data_format=_lowerCamelCase ) UpperCamelCase_: Optional[Any] = image - 1 return image def _a ( self , _lowerCamelCase , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = ChannelDimension.FIRST , **_lowerCamelCase , ): UpperCamelCase_: Optional[Any] = do_resize if do_resize is not None else self.do_resize UpperCamelCase_: Tuple = size if size is not None else self.size UpperCamelCase_: Union[str, Any] = get_size_dict(_lowerCamelCase ) UpperCamelCase_: Union[str, Any] = resample if resample is not None else self.resample UpperCamelCase_: Any = do_normalize if do_normalize is not None else self.do_normalize UpperCamelCase_: str = do_color_quantize if do_color_quantize is not None else self.do_color_quantize UpperCamelCase_: Dict = clusters if clusters is not None else self.clusters UpperCamelCase_: Dict = np.array(_lowerCamelCase ) UpperCamelCase_: Optional[int] = make_list_of_images(_lowerCamelCase ) if not valid_images(_lowerCamelCase ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None or resample is None: raise ValueError('Size and resample must be specified if do_resize is True.' ) if do_color_quantize and clusters is None: raise ValueError('Clusters must be specified if do_color_quantize is True.' ) # All transformations expect numpy arrays. UpperCamelCase_: Union[str, Any] = [to_numpy_array(_lowerCamelCase ) for image in images] if do_resize: UpperCamelCase_: Union[str, Any] = [self.resize(image=_lowerCamelCase , size=_lowerCamelCase , resample=_lowerCamelCase ) for image in images] if do_normalize: UpperCamelCase_: Optional[Any] = [self.normalize(image=_lowerCamelCase ) for image in images] if do_color_quantize: UpperCamelCase_: Any = [to_channel_dimension_format(_lowerCamelCase , ChannelDimension.LAST ) for image in images] # color quantize from (batch_size, height, width, 3) to (batch_size, height, width) UpperCamelCase_: Optional[Any] = np.array(_lowerCamelCase ) UpperCamelCase_: Optional[Any] = color_quantize(_lowerCamelCase , _lowerCamelCase ).reshape(images.shape[:-1] ) # flatten to (batch_size, height*width) UpperCamelCase_: Dict = images.shape[0] UpperCamelCase_: Any = images.reshape(_lowerCamelCase , -1 ) # We need to convert back to a list of images to keep consistent behaviour across processors. UpperCamelCase_: List[Any] = list(_lowerCamelCase ) else: UpperCamelCase_: int = [to_channel_dimension_format(_lowerCamelCase , _lowerCamelCase ) for image in images] UpperCamelCase_: str = {'input_ids': images} return BatchFeature(data=_lowerCamelCase , tensor_type=_lowerCamelCase )
57
0
"""simple docstring""" import argparse import requests import torch from PIL import Image from transformers import ViTMAEConfig, ViTMAEForPreTraining, ViTMAEImageProcessor def lowerCAmelCase ( __UpperCamelCase ): '''simple docstring''' if "cls_token" in name: UpperCAmelCase__ : Any = name.replace("""cls_token""" , """vit.embeddings.cls_token""" ) if "mask_token" in name: UpperCAmelCase__ : Optional[Any] = name.replace("""mask_token""" , """decoder.mask_token""" ) if "decoder_pos_embed" in name: UpperCAmelCase__ : int = name.replace("""decoder_pos_embed""" , """decoder.decoder_pos_embed""" ) if "pos_embed" in name and "decoder" not in name: UpperCAmelCase__ : List[str] = name.replace("""pos_embed""" , """vit.embeddings.position_embeddings""" ) if "patch_embed.proj" in name: UpperCAmelCase__ : List[str] = name.replace("""patch_embed.proj""" , """vit.embeddings.patch_embeddings.projection""" ) if "patch_embed.norm" in name: UpperCAmelCase__ : List[str] = name.replace("""patch_embed.norm""" , """vit.embeddings.norm""" ) if "decoder_blocks" in name: UpperCAmelCase__ : Tuple = name.replace("""decoder_blocks""" , """decoder.decoder_layers""" ) if "blocks" in name: UpperCAmelCase__ : Union[str, Any] = name.replace("""blocks""" , """vit.encoder.layer""" ) if "attn.proj" in name: UpperCAmelCase__ : Dict = name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name: UpperCAmelCase__ : List[Any] = name.replace("""attn""" , """attention.self""" ) if "norm1" in name: UpperCAmelCase__ : List[Any] = name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: UpperCAmelCase__ : Optional[Any] = name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: UpperCAmelCase__ : Optional[int] = name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: UpperCAmelCase__ : List[str] = name.replace("""mlp.fc2""" , """output.dense""" ) if "decoder_embed" in name: UpperCAmelCase__ : Optional[Any] = name.replace("""decoder_embed""" , """decoder.decoder_embed""" ) if "decoder_norm" in name: UpperCAmelCase__ : List[str] = name.replace("""decoder_norm""" , """decoder.decoder_norm""" ) if "decoder_pred" in name: UpperCAmelCase__ : List[Any] = name.replace("""decoder_pred""" , """decoder.decoder_pred""" ) if "norm.weight" in name and "decoder" not in name: UpperCAmelCase__ : Any = name.replace("""norm.weight""" , """vit.layernorm.weight""" ) if "norm.bias" in name and "decoder" not in name: UpperCAmelCase__ : List[str] = name.replace("""norm.bias""" , """vit.layernorm.bias""" ) return name def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase ): '''simple docstring''' for key in orig_state_dict.copy().keys(): UpperCAmelCase__ : Tuple = orig_state_dict.pop(__UpperCamelCase ) if "qkv" in key: UpperCAmelCase__ : Optional[int] = key.split(""".""" ) UpperCAmelCase__ : Union[str, Any] = int(key_split[1] ) if "decoder_blocks" in key: UpperCAmelCase__ : Optional[int] = config.decoder_hidden_size UpperCAmelCase__ : Optional[int] = """decoder.decoder_layers.""" if "weight" in key: UpperCAmelCase__ : Union[str, Any] = val[:dim, :] UpperCAmelCase__ : Any = val[dim : dim * 2, :] UpperCAmelCase__ : Optional[Any] = val[-dim:, :] elif "bias" in key: UpperCAmelCase__ : Optional[int] = val[:dim] UpperCAmelCase__ : Any = val[dim : dim * 2] UpperCAmelCase__ : List[Any] = val[-dim:] else: UpperCAmelCase__ : Union[str, Any] = config.hidden_size UpperCAmelCase__ : List[str] = """vit.encoder.layer.""" if "weight" in key: UpperCAmelCase__ : int = val[:dim, :] UpperCAmelCase__ : Dict = val[dim : dim * 2, :] UpperCAmelCase__ : Any = val[-dim:, :] elif "bias" in key: UpperCAmelCase__ : str = val[:dim] UpperCAmelCase__ : Tuple = val[dim : dim * 2] UpperCAmelCase__ : Dict = val[-dim:] else: UpperCAmelCase__ : Tuple = val return orig_state_dict def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase ): '''simple docstring''' UpperCAmelCase__ : List[str] = ViTMAEConfig() if "large" in checkpoint_url: UpperCAmelCase__ : int = 1024 UpperCAmelCase__ : List[str] = 4096 UpperCAmelCase__ : List[Any] = 24 UpperCAmelCase__ : Any = 16 elif "huge" in checkpoint_url: UpperCAmelCase__ : List[str] = 14 UpperCAmelCase__ : int = 1280 UpperCAmelCase__ : int = 5120 UpperCAmelCase__ : int = 32 UpperCAmelCase__ : List[Any] = 16 UpperCAmelCase__ : str = ViTMAEForPreTraining(__UpperCamelCase ) UpperCAmelCase__ : Any = torch.hub.load_state_dict_from_url(__UpperCamelCase , map_location="""cpu""" )["""model"""] UpperCAmelCase__ : Dict = ViTMAEImageProcessor(size=config.image_size ) UpperCAmelCase__ : Optional[Any] = convert_state_dict(__UpperCamelCase , __UpperCamelCase ) model.load_state_dict(__UpperCamelCase ) model.eval() UpperCAmelCase__ : List[Any] = """https://user-images.githubusercontent.com/11435359/147738734-196fd92f-9260-48d5-ba7e-bf103d29364d.jpg""" UpperCAmelCase__ : int = Image.open(requests.get(__UpperCamelCase , stream=__UpperCamelCase ).raw ) UpperCAmelCase__ : Tuple = ViTMAEImageProcessor(size=config.image_size ) UpperCAmelCase__ : List[Any] = image_processor(images=__UpperCamelCase , return_tensors="""pt""" ) # forward pass torch.manual_seed(2 ) UpperCAmelCase__ : Any = model(**__UpperCamelCase ) UpperCAmelCase__ : int = outputs.logits if "large" in checkpoint_url: UpperCAmelCase__ : Optional[int] = torch.tensor( [[-0.7309, -0.7128, -1.0169], [-1.0161, -0.9058, -1.1878], [-1.0478, -0.9411, -1.1911]] ) elif "huge" in checkpoint_url: UpperCAmelCase__ : List[str] = torch.tensor( [[-1.1599, -0.9199, -1.2221], [-1.1952, -0.9269, -1.2307], [-1.2143, -0.9337, -1.2262]] ) else: UpperCAmelCase__ : List[Any] = torch.tensor( [[-0.9192, -0.8481, -1.1259], [-1.1349, -1.0034, -1.2599], [-1.1757, -1.0429, -1.2726]] ) # verify logits assert torch.allclose(logits[0, :3, :3] , __UpperCamelCase , atol=1e-4 ) print(F"Saving model to {pytorch_dump_folder_path}" ) model.save_pretrained(__UpperCamelCase ) print(F"Saving image processor to {pytorch_dump_folder_path}" ) image_processor.save_pretrained(__UpperCamelCase ) if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '--checkpoint_url', default='https://dl.fbaipublicfiles.com/mae/visualize/mae_visualize_vit_base.pth', type=str, help='URL of the checkpoint you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) __UpperCAmelCase = parser.parse_args() convert_vit_mae_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
65
import numpy # List of input, output pairs A_ : Any = ( ((5, 2, 3), 15), ((6, 5, 9), 25), ((11, 12, 13), 41), ((1, 1, 1), 8), ((11, 12, 13), 41), ) A_ : List[Any] = (((515, 22, 13), 555), ((61, 35, 49), 150)) A_ : Any = [2, 4, 1, 5] A_ : List[Any] = len(train_data) A_ : List[Any] = 0.009 def snake_case (UpperCAmelCase__ , UpperCAmelCase__="train" ) -> Optional[int]: return calculate_hypothesis_value(UpperCAmelCase__ , UpperCAmelCase__ ) - output( UpperCAmelCase__ , UpperCAmelCase__ ) def snake_case (UpperCAmelCase__ ) -> Optional[Any]: UpperCamelCase_: Optional[Any] = 0 for i in range(len(UpperCAmelCase__ ) - 1 ): hyp_val += data_input_tuple[i] * parameter_vector[i + 1] hyp_val += parameter_vector[0] return hyp_val def snake_case (UpperCAmelCase__ , UpperCAmelCase__ ) -> List[Any]: if data_set == "train": return train_data[example_no][1] elif data_set == "test": return test_data[example_no][1] return None def snake_case (UpperCAmelCase__ , UpperCAmelCase__ ) -> Optional[Any]: if data_set == "train": return _hypothesis_value(train_data[example_no][0] ) elif data_set == "test": return _hypothesis_value(test_data[example_no][0] ) return None def snake_case (UpperCAmelCase__ , UpperCAmelCase__=m ) -> Optional[Any]: UpperCamelCase_: Any = 0 for i in range(UpperCAmelCase__ ): if index == -1: summation_value += _error(UpperCAmelCase__ ) else: summation_value += _error(UpperCAmelCase__ ) * train_data[i][0][index] return summation_value def snake_case (UpperCAmelCase__ ) -> Optional[Any]: UpperCamelCase_: Optional[int] = summation_of_cost_derivative(UpperCAmelCase__ , UpperCAmelCase__ ) / m return cost_derivative_value def snake_case () -> Union[str, Any]: global parameter_vector # Tune these values to set a tolerance value for predicted output UpperCamelCase_: str = 0.00_0002 UpperCamelCase_: Any = 0 UpperCamelCase_: int = 0 while True: j += 1 UpperCamelCase_: int = [0, 0, 0, 0] for i in range(0 , len(UpperCAmelCase__ ) ): UpperCamelCase_: Any = get_cost_derivative(i - 1 ) UpperCamelCase_: Optional[int] = ( parameter_vector[i] - LEARNING_RATE * cost_derivative ) if numpy.allclose( UpperCAmelCase__ , UpperCAmelCase__ , atol=UpperCAmelCase__ , rtol=UpperCAmelCase__ , ): break UpperCamelCase_: Optional[int] = temp_parameter_vector print(('Number of iterations:', j) ) def snake_case () -> int: for i in range(len(UpperCAmelCase__ ) ): print(('Actual output value:', output(UpperCAmelCase__ , 'test' )) ) print(('Hypothesis output:', calculate_hypothesis_value(UpperCAmelCase__ , 'test' )) ) if __name__ == "__main__": run_gradient_descent() print('\nTesting gradient descent for a linear hypothesis function.\n') test_gradient_descent()
57
0
import dataclasses import json import warnings from dataclasses import dataclass, field from time import time from typing import List from ..utils import logging UpperCamelCase = logging.get_logger(__name__) def __magic_name__ ( SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=None ) -> str: return field(default_factory=lambda: default , metadata=SCREAMING_SNAKE_CASE ) @dataclass class lowerCAmelCase_ : _UpperCamelCase : List[str] = list_field( default=[] , metadata={ "help": ( "Model checkpoints to be provided to the AutoModel classes. Leave blank to benchmark the base version" " of all available models" ) } , ) _UpperCamelCase : List[int] = list_field( default=[8] , metadata={"help": "List of batch sizes for which memory and time performance will be evaluated"} ) _UpperCamelCase : List[int] = list_field( default=[8, 32, 128, 512] , metadata={"help": "List of sequence lengths for which memory and time performance will be evaluated"} , ) _UpperCamelCase : bool = field( default=__snake_case , metadata={"help": "Whether to benchmark inference of model. Inference can be disabled via --no-inference."} , ) _UpperCamelCase : bool = field( default=__snake_case , metadata={"help": "Whether to run on available cuda devices. Cuda can be disabled via --no-cuda."} , ) _UpperCamelCase : bool = field( default=__snake_case , metadata={"help": "Whether to run on available tpu devices. TPU can be disabled via --no-tpu."} ) _UpperCamelCase : bool = field(default=__snake_case , metadata={"help": "Use FP16 to accelerate inference."} ) _UpperCamelCase : bool = field(default=__snake_case , metadata={"help": "Benchmark training of model"} ) _UpperCamelCase : bool = field(default=__snake_case , metadata={"help": "Verbose memory tracing"} ) _UpperCamelCase : bool = field( default=__snake_case , metadata={"help": "Whether to perform speed measurements. Speed measurements can be disabled via --no-speed."} , ) _UpperCamelCase : bool = field( default=__snake_case , metadata={ "help": "Whether to perform memory measurements. Memory measurements can be disabled via --no-memory" } , ) _UpperCamelCase : bool = field(default=__snake_case , metadata={"help": "Trace memory line by line"} ) _UpperCamelCase : bool = field(default=__snake_case , metadata={"help": "Save result to a CSV file"} ) _UpperCamelCase : bool = field(default=__snake_case , metadata={"help": "Save all print statements in a log file"} ) _UpperCamelCase : bool = field(default=__snake_case , metadata={"help": "Whether to print environment information"} ) _UpperCamelCase : bool = field( default=__snake_case , metadata={ "help": ( "Whether to use multiprocessing for memory and speed measurement. It is highly recommended to use" " multiprocessing for accurate CPU and GPU memory measurements. This option should only be disabled" " for debugging / testing and on TPU." ) } , ) _UpperCamelCase : str = field( default=F"""inference_time_{round(time() )}.csv""" , metadata={"help": "CSV filename used if saving time results to csv."} , ) _UpperCamelCase : str = field( default=F"""inference_memory_{round(time() )}.csv""" , metadata={"help": "CSV filename used if saving memory results to csv."} , ) _UpperCamelCase : str = field( default=F"""train_time_{round(time() )}.csv""" , metadata={"help": "CSV filename used if saving time results to csv for training."} , ) _UpperCamelCase : str = field( default=F"""train_memory_{round(time() )}.csv""" , metadata={"help": "CSV filename used if saving memory results to csv for training."} , ) _UpperCamelCase : str = field( default=F"""env_info_{round(time() )}.csv""" , metadata={"help": "CSV filename used if saving environment information."} , ) _UpperCamelCase : str = field( default=F"""log_{round(time() )}.csv""" , metadata={"help": "Log filename used if print statements are saved in log."} , ) _UpperCamelCase : int = field(default=3 , metadata={"help": "Times an experiment will be run."} ) _UpperCamelCase : bool = field( default=__snake_case , metadata={ "help": ( "Instead of loading the model as defined in `config.architectures` if exists, just load the pretrain" " model weights." ) } , ) def __a ( self ): warnings.warn( F"""The class {self.__class__} is deprecated. Hugging Face Benchmarking utils""" ' are deprecated in general and it is advised to use external Benchmarking libraries ' ' to benchmark Transformer models.' , _lowerCAmelCase , ) def __a ( self ): return json.dumps(dataclasses.asdict(self ) , indent=2 ) @property def __a ( self ): if len(self.models ) <= 0: raise ValueError( 'Please make sure you provide at least one model name / model identifier, *e.g.* `--models' ' bert-base-cased` or `args.models = [\'bert-base-cased\'].' ) return self.models @property def __a ( self ): if not self.multi_process: return False elif self.is_tpu: logger.info('Multiprocessing is currently not possible on TPU.' ) return False else: return True
66
from ...utils import ( OptionalDependencyNotAvailable, is_flax_available, is_torch_available, is_transformers_available, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .multicontrolnet import MultiControlNetModel from .pipeline_controlnet import StableDiffusionControlNetPipeline from .pipeline_controlnet_imgaimg import StableDiffusionControlNetImgaImgPipeline from .pipeline_controlnet_inpaint import StableDiffusionControlNetInpaintPipeline if is_transformers_available() and is_flax_available(): from .pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline
57
0
def SCREAMING_SNAKE_CASE__ ( snake_case__ :list ) -> bool: if not isinstance(snake_case__ , snake_case__ ): raise ValueError('Input series is not valid, valid series - [2, 4, 6]' ) if len(snake_case__ ) == 0: raise ValueError('Input list must be a non empty list' ) if len(snake_case__ ) == 1: return True _lowercase = series[1] - series[0] for index in range(len(snake_case__ ) - 1 ): if series[index + 1] - series[index] != common_diff: return False return True def SCREAMING_SNAKE_CASE__ ( snake_case__ :list ) -> float: if not isinstance(snake_case__ , snake_case__ ): raise ValueError('Input series is not valid, valid series - [2, 4, 6]' ) if len(snake_case__ ) == 0: raise ValueError('Input list must be a non empty list' ) _lowercase = 0 for val in series: answer += val return answer / len(snake_case__ ) if __name__ == "__main__": import doctest doctest.testmod()
67
from __future__ import annotations import unittest from transformers import AutoTokenizer, PegasusConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFPegasusForConditionalGeneration, TFPegasusModel @require_tf class _lowerCAmelCase: """simple docstring""" a : int =PegasusConfig a : List[str] ={} a : Optional[int] ='''gelu''' def __init__( self , _lowerCamelCase , _lowerCamelCase=1_3 , _lowerCamelCase=7 , _lowerCamelCase=True , _lowerCamelCase=False , _lowerCamelCase=9_9 , _lowerCamelCase=3_2 , _lowerCamelCase=2 , _lowerCamelCase=4 , _lowerCamelCase=3_7 , _lowerCamelCase=0.1 , _lowerCamelCase=0.1 , _lowerCamelCase=4_0 , _lowerCamelCase=2 , _lowerCamelCase=1 , _lowerCamelCase=0 , ): UpperCamelCase_: List[Any] = parent UpperCamelCase_: Dict = batch_size UpperCamelCase_: List[str] = seq_length UpperCamelCase_: List[str] = is_training UpperCamelCase_: Any = use_labels UpperCamelCase_: Optional[Any] = vocab_size UpperCamelCase_: Tuple = hidden_size UpperCamelCase_: List[Any] = num_hidden_layers UpperCamelCase_: Any = num_attention_heads UpperCamelCase_: Optional[Any] = intermediate_size UpperCamelCase_: Optional[int] = hidden_dropout_prob UpperCamelCase_: int = attention_probs_dropout_prob UpperCamelCase_: Union[str, Any] = max_position_embeddings UpperCamelCase_: Dict = eos_token_id UpperCamelCase_: Union[str, Any] = pad_token_id UpperCamelCase_: List[Any] = bos_token_id def _a ( self ): UpperCamelCase_: Union[str, Any] = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) UpperCamelCase_: int = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) UpperCamelCase_: List[str] = tf.concat([input_ids, eos_tensor] , axis=1 ) UpperCamelCase_: Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase_: Tuple = 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 , ) UpperCamelCase_: Optional[Any] = prepare_pegasus_inputs_dict(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) return config, inputs_dict def _a ( self , _lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: Optional[Any] = TFPegasusModel(config=_lowerCamelCase ).get_decoder() UpperCamelCase_: Optional[int] = inputs_dict['input_ids'] UpperCamelCase_: Optional[int] = input_ids[:1, :] UpperCamelCase_: int = inputs_dict['attention_mask'][:1, :] UpperCamelCase_: Optional[int] = inputs_dict['head_mask'] UpperCamelCase_: Optional[int] = 1 # first forward pass UpperCamelCase_: Union[str, Any] = model(_lowerCamelCase , attention_mask=_lowerCamelCase , head_mask=_lowerCamelCase , use_cache=_lowerCamelCase ) UpperCamelCase_ ,UpperCamelCase_: int = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids UpperCamelCase_: int = ids_tensor((self.batch_size, 3) , config.vocab_size ) UpperCamelCase_: List[Any] = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and UpperCamelCase_: Union[str, Any] = tf.concat([input_ids, next_tokens] , axis=-1 ) UpperCamelCase_: int = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) UpperCamelCase_: Any = model(_lowerCamelCase , attention_mask=_lowerCamelCase )[0] UpperCamelCase_: int = model(_lowerCamelCase , attention_mask=_lowerCamelCase , past_key_values=_lowerCamelCase )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice UpperCamelCase_: Optional[int] = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) UpperCamelCase_: Any = output_from_no_past[:, -3:, random_slice_idx] UpperCamelCase_: Union[str, Any] = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(_lowerCamelCase , _lowerCamelCase , rtol=1e-3 ) def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__=None , UpperCAmelCase__=None , UpperCAmelCase__=None , UpperCAmelCase__=None , UpperCAmelCase__=None , ) -> str: if attention_mask is None: UpperCamelCase_: Optional[Any] = tf.cast(tf.math.not_equal(UpperCAmelCase__ , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: UpperCamelCase_: int = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: UpperCamelCase_: str = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: UpperCamelCase_: Any = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: UpperCamelCase_: int = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class _lowerCAmelCase( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase ): """simple docstring""" a : Tuple =(TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else () a : int =(TFPegasusForConditionalGeneration,) if is_tf_available() else () a : Tuple =( { '''conversational''': TFPegasusForConditionalGeneration, '''feature-extraction''': TFPegasusModel, '''summarization''': TFPegasusForConditionalGeneration, '''text2text-generation''': TFPegasusForConditionalGeneration, '''translation''': TFPegasusForConditionalGeneration, } if is_tf_available() else {} ) a : List[str] =True a : List[str] =False a : Tuple =False def _a ( self ): UpperCamelCase_: Dict = TFPegasusModelTester(self ) UpperCamelCase_: Any = ConfigTester(self , config_class=_lowerCamelCase ) def _a ( self ): self.config_tester.run_common_tests() def _a ( self ): UpperCamelCase_: Any = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*_lowerCamelCase ) @require_sentencepiece @require_tokenizers @require_tf class _lowerCAmelCase( unittest.TestCase ): """simple docstring""" a : Dict =[ ''' 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!" ''', ] a : int =[ '''California\'s largest electricity provider has cut power to hundreds of thousands of customers in an effort to''' ''' reduce the risk of wildfires.''', '''N-Dubz have revealed they\'re "grateful" to have been nominated for four Mobo Awards.''', ] # differs slightly from pytorch, likely due to numerical differences in linear layers a : Union[str, Any] ='''google/pegasus-xsum''' @cached_property def _a ( self ): return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def _a ( self ): UpperCamelCase_: Optional[Any] = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def _a ( self , **_lowerCamelCase ): UpperCamelCase_: Dict = self.translate_src_text(**_lowerCamelCase ) assert self.expected_text == generated_words def _a ( self , **_lowerCamelCase ): UpperCamelCase_: Union[str, Any] = self.tokenizer(self.src_text , **_lowerCamelCase , padding=_lowerCamelCase , return_tensors='tf' ) UpperCamelCase_: Any = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=_lowerCamelCase , ) UpperCamelCase_: str = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=_lowerCamelCase ) return generated_words @slow def _a ( self ): self._assert_generated_batch_equal_expected()
57
0
import numpy as np from cva import COLOR_BGR2GRAY, CV_8UC3, cvtColor, filteraD, imread, imshow, waitKey def lowercase__ ( A_: int , A_: int , A_: int , A_: int , A_: int , A_: int ) -> np.ndarray: """simple docstring""" if (ksize % 2) == 0: __UpperCAmelCase =ksize + 1 __UpperCAmelCase =np.zeros((ksize, ksize) , dtype=np.floataa ) # each value for y in range(A_ ): for x in range(A_ ): # distance from center __UpperCAmelCase =x - ksize // 2 __UpperCAmelCase =y - ksize // 2 # degree to radiant __UpperCAmelCase =theta / 180 * np.pi __UpperCAmelCase =np.cos(_theta ) __UpperCAmelCase =np.sin(_theta ) # get kernel x __UpperCAmelCase =cos_theta * px + sin_theta * py # get kernel y __UpperCAmelCase =-sin_theta * px + cos_theta * py # fill kernel __UpperCAmelCase =np.exp( -(_x**2 + gamma**2 * _y**2) / (2 * sigma**2) ) * np.cos(2 * np.pi * _x / lambd + psi ) return gabor if __name__ == "__main__": import doctest doctest.testmod() # read original image __A = imread("../image_data/lena.jpg") # turn image in gray scale value __A = cvtColor(img, COLOR_BGR2GRAY) # Apply multiple Kernel to detect edges __A = np.zeros(gray.shape[:2]) for theta in [0, 30, 60, 90, 1_20, 1_50]: __A = gabor_filter_kernel(10, 8, theta, 10, 0, 0) out += filteraD(gray, CV_8UC3, kernel_aa) __A = out / out.max() * 2_55 __A = out.astype(np.uinta) imshow("Original", gray) imshow("Gabor filter with 20x20 mask and 6 directions", out) waitKey(0)
68
import unittest import numpy as np def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ = None , ) -> np.ndarray: UpperCamelCase_: str = np.shape(UpperCAmelCase__ ) UpperCamelCase_: str = np.shape(UpperCAmelCase__ ) UpperCamelCase_: List[Any] = np.shape(UpperCAmelCase__ ) if shape_a[0] != shape_b[0]: UpperCamelCase_: Any = ( 'Expected the same number of rows for A and B. ' F'''Instead found A of size {shape_a} and B of size {shape_b}''' ) raise ValueError(UpperCAmelCase__ ) if shape_b[1] != shape_c[1]: UpperCamelCase_: int = ( 'Expected the same number of columns for B and C. ' F'''Instead found B of size {shape_b} and C of size {shape_c}''' ) raise ValueError(UpperCAmelCase__ ) UpperCamelCase_: Dict = pseudo_inv if a_inv is None: try: UpperCamelCase_: Optional[Any] = np.linalg.inv(UpperCAmelCase__ ) except np.linalg.LinAlgError: raise ValueError( 'Input matrix A is not invertible. Cannot compute Schur complement.' ) return mat_c - mat_b.T @ a_inv @ mat_b class _lowerCAmelCase( unittest.TestCase ): """simple docstring""" def _a ( self ): UpperCamelCase_: Any = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) UpperCamelCase_: Dict = np.array([[0, 3], [3, 0], [2, 3]] ) UpperCamelCase_: Tuple = np.array([[2, 1], [6, 3]] ) UpperCamelCase_: Tuple = schur_complement(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) UpperCamelCase_: Optional[Any] = np.block([[a, b], [b.T, c]] ) UpperCamelCase_: List[str] = np.linalg.det(_lowerCamelCase ) UpperCamelCase_: List[str] = np.linalg.det(_lowerCamelCase ) UpperCamelCase_: Dict = np.linalg.det(_lowerCamelCase ) self.assertAlmostEqual(_lowerCamelCase , det_a * det_s ) def _a ( self ): UpperCamelCase_: int = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) UpperCamelCase_: List[str] = np.array([[0, 3], [3, 0], [2, 3]] ) UpperCamelCase_: List[str] = np.array([[2, 1], [6, 3]] ) with self.assertRaises(_lowerCamelCase ): schur_complement(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def _a ( self ): UpperCamelCase_: List[Any] = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) UpperCamelCase_: str = np.array([[0, 3], [3, 0], [2, 3]] ) UpperCamelCase_: List[Any] = np.array([[2, 1, 3], [6, 3, 5]] ) with self.assertRaises(_lowerCamelCase ): schur_complement(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) if __name__ == "__main__": import doctest doctest.testmod() unittest.main()
57
0
'''simple docstring''' import math import torch from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from .attention_processor import Attention from .embeddings import get_timestep_embedding from .modeling_utils import ModelMixin class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase , _UpperCamelCase ): @register_to_config def __init__( self : Dict , a_ : int = 128 , a_ : int = 256 , a_ : float = 2000.0 , a_ : int = 768 , a_ : int = 12 , a_ : int = 12 , a_ : int = 64 , a_ : int = 2_048 , a_ : float = 0.1 , ): """simple docstring""" super().__init__() __snake_case = nn.Sequential( nn.Linear(a_ , d_model * 4 , bias=a_ ) , nn.SiLU() , nn.Linear(d_model * 4 , d_model * 4 , bias=a_ ) , nn.SiLU() , ) __snake_case = nn.Embedding(a_ , a_ ) __snake_case = False __snake_case = nn.Linear(a_ , a_ , bias=a_ ) __snake_case = nn.Dropout(p=a_ ) __snake_case = nn.ModuleList() for lyr_num in range(a_ ): # FiLM conditional T5 decoder __snake_case = DecoderLayer(d_model=a_ , d_kv=a_ , num_heads=a_ , d_ff=a_ , dropout_rate=a_ ) self.decoders.append(a_ ) __snake_case = TaLayerNorm(a_ ) __snake_case = nn.Dropout(p=a_ ) __snake_case = nn.Linear(a_ , a_ , bias=a_ ) def A ( self : Any , a_ : Tuple , a_ : Optional[Any] ): """simple docstring""" __snake_case = torch.mul(query_input.unsqueeze(-1 ) , key_input.unsqueeze(-2 ) ) return mask.unsqueeze(-3 ) def A ( self : int , a_ : Any , a_ : Optional[int] , a_ : Any ): """simple docstring""" __snake_case , __snake_case , __snake_case = decoder_input_tokens.shape assert decoder_noise_time.shape == (batch,) # decoder_noise_time is in [0, 1), so rescale to expected timing range. __snake_case = get_timestep_embedding( decoder_noise_time * self.config.max_decoder_noise_time , embedding_dim=self.config.d_model , max_period=self.config.max_decoder_noise_time , ).to(dtype=self.dtype ) __snake_case = self.conditioning_emb(a_ ).unsqueeze(1 ) assert conditioning_emb.shape == (batch, 1, self.config.d_model * 4) __snake_case = decoder_input_tokens.shape[1] # If we want to use relative positions for audio context, we can just offset # this sequence by the length of encodings_and_masks. __snake_case = torch.broadcast_to( torch.arange(a_ , device=decoder_input_tokens.device ) , (batch, seq_length) , ) __snake_case = self.position_encoding(a_ ) __snake_case = self.continuous_inputs_projection(a_ ) inputs += position_encodings __snake_case = self.dropout(a_ ) # decoder: No padding present. __snake_case = torch.ones( decoder_input_tokens.shape[:2] , device=decoder_input_tokens.device , dtype=inputs.dtype ) # Translate encoding masks to encoder-decoder masks. __snake_case = [(x, self.encoder_decoder_mask(a_ , a_ )) for x, y in encodings_and_masks] # cross attend style: concat encodings __snake_case = torch.cat([x[0] for x in encodings_and_encdec_masks] , dim=1 ) __snake_case = torch.cat([x[1] for x in encodings_and_encdec_masks] , dim=-1 ) for lyr in self.decoders: __snake_case = lyr( a_ , conditioning_emb=a_ , encoder_hidden_states=a_ , encoder_attention_mask=a_ , )[0] __snake_case = self.decoder_norm(a_ ) __snake_case = self.post_dropout(a_ ) __snake_case = self.spec_out(a_ ) return spec_out class SCREAMING_SNAKE_CASE__ ( nn.Module ): def __init__( self : Dict , a_ : Optional[int] , a_ : Dict , a_ : List[str] , a_ : Any , a_ : Tuple , a_ : Optional[int]=1e-6 ): """simple docstring""" super().__init__() __snake_case = nn.ModuleList() # cond self attention: layer 0 self.layer.append( TaLayerSelfAttentionCond(d_model=a_ , d_kv=a_ , num_heads=a_ , dropout_rate=a_ ) ) # cross attention: layer 1 self.layer.append( TaLayerCrossAttention( d_model=a_ , d_kv=a_ , num_heads=a_ , dropout_rate=a_ , layer_norm_epsilon=a_ , ) ) # Film Cond MLP + dropout: last layer self.layer.append( TaLayerFFCond(d_model=a_ , d_ff=a_ , dropout_rate=a_ , layer_norm_epsilon=a_ ) ) def A ( self : Any , a_ : List[str] , a_ : Tuple=None , a_ : Any=None , a_ : Union[str, Any]=None , a_ : List[str]=None , a_ : Dict=None , ): """simple docstring""" __snake_case = self.layer[0]( a_ , conditioning_emb=a_ , attention_mask=a_ , ) if encoder_hidden_states is not None: __snake_case = torch.where(encoder_attention_mask > 0 , 0 , -1e10 ).to( encoder_hidden_states.dtype ) __snake_case = self.layer[1]( a_ , key_value_states=a_ , attention_mask=a_ , ) # Apply Film Conditional Feed Forward layer __snake_case = self.layer[-1](a_ , a_ ) return (hidden_states,) class SCREAMING_SNAKE_CASE__ ( nn.Module ): def __init__( self : Union[str, Any] , a_ : Optional[Any] , a_ : Optional[Any] , a_ : List[Any] , a_ : Tuple ): """simple docstring""" super().__init__() __snake_case = TaLayerNorm(a_ ) __snake_case = TaFiLMLayer(in_features=d_model * 4 , out_features=a_ ) __snake_case = Attention(query_dim=a_ , heads=a_ , dim_head=a_ , out_bias=a_ , scale_qk=a_ ) __snake_case = nn.Dropout(a_ ) def A ( self : Optional[Any] , a_ : str , a_ : Union[str, Any]=None , a_ : Tuple=None , ): """simple docstring""" __snake_case = self.layer_norm(a_ ) if conditioning_emb is not None: __snake_case = self.FiLMLayer(a_ , a_ ) # Self-attention block __snake_case = self.attention(a_ ) __snake_case = hidden_states + self.dropout(a_ ) return hidden_states class SCREAMING_SNAKE_CASE__ ( nn.Module ): def __init__( self : Any , a_ : List[str] , a_ : List[str] , a_ : List[str] , a_ : Optional[Any] , a_ : int ): """simple docstring""" super().__init__() __snake_case = Attention(query_dim=a_ , heads=a_ , dim_head=a_ , out_bias=a_ , scale_qk=a_ ) __snake_case = TaLayerNorm(a_ , eps=a_ ) __snake_case = nn.Dropout(a_ ) def A ( self : int , a_ : Any , a_ : Dict=None , a_ : Optional[Any]=None , ): """simple docstring""" __snake_case = self.layer_norm(a_ ) __snake_case = self.attention( a_ , encoder_hidden_states=a_ , attention_mask=attention_mask.squeeze(1 ) , ) __snake_case = hidden_states + self.dropout(a_ ) return layer_output class SCREAMING_SNAKE_CASE__ ( nn.Module ): def __init__( self : Union[str, Any] , a_ : Optional[int] , a_ : Tuple , a_ : Optional[int] , a_ : List[str] ): """simple docstring""" super().__init__() __snake_case = TaDenseGatedActDense(d_model=a_ , d_ff=a_ , dropout_rate=a_ ) __snake_case = TaFiLMLayer(in_features=d_model * 4 , out_features=a_ ) __snake_case = TaLayerNorm(a_ , eps=a_ ) __snake_case = nn.Dropout(a_ ) def A ( self : Optional[int] , a_ : Union[str, Any] , a_ : Union[str, Any]=None ): """simple docstring""" __snake_case = self.layer_norm(a_ ) if conditioning_emb is not None: __snake_case = self.film(a_ , a_ ) __snake_case = self.DenseReluDense(a_ ) __snake_case = hidden_states + self.dropout(a_ ) return hidden_states class SCREAMING_SNAKE_CASE__ ( nn.Module ): def __init__( self : Optional[int] , a_ : str , a_ : Any , a_ : Dict ): """simple docstring""" super().__init__() __snake_case = nn.Linear(a_ , a_ , bias=a_ ) __snake_case = nn.Linear(a_ , a_ , bias=a_ ) __snake_case = nn.Linear(a_ , a_ , bias=a_ ) __snake_case = nn.Dropout(a_ ) __snake_case = NewGELUActivation() def A ( self : Any , a_ : str ): """simple docstring""" __snake_case = self.act(self.wi_a(a_ ) ) __snake_case = self.wi_a(a_ ) __snake_case = hidden_gelu * hidden_linear __snake_case = self.dropout(a_ ) __snake_case = self.wo(a_ ) return hidden_states class SCREAMING_SNAKE_CASE__ ( nn.Module ): def __init__( self : List[str] , a_ : Optional[Any] , a_ : Optional[Any]=1e-6 ): """simple docstring""" super().__init__() __snake_case = nn.Parameter(torch.ones(a_ ) ) __snake_case = eps def A ( self : List[str] , a_ : Any ): """simple docstring""" __snake_case = hidden_states.to(torch.floataa ).pow(2 ).mean(-1 , keepdim=a_ ) __snake_case = hidden_states * torch.rsqrt(variance + self.variance_epsilon ) # convert into half-precision if necessary if self.weight.dtype in [torch.floataa, torch.bfloataa]: __snake_case = hidden_states.to(self.weight.dtype ) return self.weight * hidden_states class SCREAMING_SNAKE_CASE__ ( nn.Module ): def A ( self : List[str] , a_ : torch.Tensor ): """simple docstring""" return 0.5 * input * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi ) * (input + 0.044715 * torch.pow(a_ , 3.0 )) )) class SCREAMING_SNAKE_CASE__ ( nn.Module ): def __init__( self : int , a_ : Union[str, Any] , a_ : List[str] ): """simple docstring""" super().__init__() __snake_case = nn.Linear(a_ , out_features * 2 , bias=a_ ) def A ( self : Optional[int] , a_ : Union[str, Any] , a_ : Optional[int] ): """simple docstring""" __snake_case = self.scale_bias(a_ ) __snake_case , __snake_case = torch.chunk(a_ , 2 , -1 ) __snake_case = x * (1 + scale) + shift return x
69
import argparse import json import os from collections import OrderedDict import torch from transformers import LukeConfig, LukeForMaskedLM, MLukeTokenizer, XLMRobertaTokenizer from transformers.tokenization_utils_base import AddedToken @torch.no_grad() def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) -> int: # Load configuration defined in the metadata file with open(UpperCAmelCase__ ) as metadata_file: UpperCamelCase_: Tuple = json.load(UpperCAmelCase__ ) UpperCamelCase_: List[str] = LukeConfig(use_entity_aware_attention=UpperCAmelCase__ , **metadata['model_config'] ) # Load in the weights from the checkpoint_path UpperCamelCase_: Optional[int] = torch.load(UpperCAmelCase__ , map_location='cpu' )['module'] # Load the entity vocab file UpperCamelCase_: Any = load_original_entity_vocab(UpperCAmelCase__ ) # add an entry for [MASK2] UpperCamelCase_: List[str] = max(entity_vocab.values() ) + 1 config.entity_vocab_size += 1 UpperCamelCase_: Union[str, Any] = XLMRobertaTokenizer.from_pretrained(metadata['model_config']['bert_model_name'] ) # Add special tokens to the token vocabulary for downstream tasks UpperCamelCase_: Any = AddedToken('<ent>' , lstrip=UpperCAmelCase__ , rstrip=UpperCAmelCase__ ) UpperCamelCase_: Optional[Any] = AddedToken('<ent2>' , lstrip=UpperCAmelCase__ , rstrip=UpperCAmelCase__ ) 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(UpperCAmelCase__ ) with open(os.path.join(UpperCAmelCase__ , 'tokenizer_config.json' ) , 'r' ) as f: UpperCamelCase_: Union[str, Any] = json.load(UpperCAmelCase__ ) UpperCamelCase_: str = 'MLukeTokenizer' with open(os.path.join(UpperCAmelCase__ , 'tokenizer_config.json' ) , 'w' ) as f: json.dump(UpperCAmelCase__ , UpperCAmelCase__ ) with open(os.path.join(UpperCAmelCase__ , MLukeTokenizer.vocab_files_names['entity_vocab_file'] ) , 'w' ) as f: json.dump(UpperCAmelCase__ , UpperCAmelCase__ ) UpperCamelCase_: Optional[Any] = MLukeTokenizer.from_pretrained(UpperCAmelCase__ ) # Initialize the embeddings of the special tokens UpperCamelCase_: Any = tokenizer.convert_tokens_to_ids(['@'] )[0] UpperCamelCase_: List[str] = tokenizer.convert_tokens_to_ids(['#'] )[0] UpperCamelCase_: Tuple = state_dict['embeddings.word_embeddings.weight'] UpperCamelCase_: int = word_emb[ent_init_index].unsqueeze(0 ) UpperCamelCase_: Any = word_emb[enta_init_index].unsqueeze(0 ) UpperCamelCase_: str = torch.cat([word_emb, ent_emb, enta_emb] ) # add special tokens for 'entity_predictions.bias' for bias_name in ["lm_head.decoder.bias", "lm_head.bias"]: UpperCamelCase_: Union[str, Any] = state_dict[bias_name] UpperCamelCase_: Tuple = decoder_bias[ent_init_index].unsqueeze(0 ) UpperCamelCase_: Any = decoder_bias[enta_init_index].unsqueeze(0 ) UpperCamelCase_: Optional[Any] = torch.cat([decoder_bias, ent_decoder_bias, enta_decoder_bias] ) # 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_: List[Any] = F'''encoder.layer.{layer_index}.attention.self.''' UpperCamelCase_: str = state_dict[prefix + matrix_name] UpperCamelCase_: Dict = state_dict[prefix + matrix_name] UpperCamelCase_: Dict = state_dict[prefix + matrix_name] # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks UpperCamelCase_: List[str] = state_dict['entity_embeddings.entity_embeddings.weight'] UpperCamelCase_: int = entity_emb[entity_vocab['[MASK]']].unsqueeze(0 ) UpperCamelCase_: Tuple = torch.cat([entity_emb, entity_mask_emb] ) # add [MASK2] for 'entity_predictions.bias' UpperCamelCase_: Optional[Any] = state_dict['entity_predictions.bias'] UpperCamelCase_: List[str] = entity_prediction_bias[entity_vocab['[MASK]']].unsqueeze(0 ) UpperCamelCase_: List[Any] = torch.cat([entity_prediction_bias, entity_mask_bias] ) UpperCamelCase_: List[Any] = LukeForMaskedLM(config=UpperCAmelCase__ ).eval() state_dict.pop('entity_predictions.decoder.weight' ) state_dict.pop('lm_head.decoder.weight' ) state_dict.pop('lm_head.decoder.bias' ) UpperCamelCase_: Optional[Any] = OrderedDict() for key, value in state_dict.items(): if not (key.startswith('lm_head' ) or key.startswith('entity_predictions' )): UpperCamelCase_: Union[str, Any] = state_dict[key] else: UpperCamelCase_: Dict = state_dict[key] UpperCamelCase_ ,UpperCamelCase_: Optional[int] = model.load_state_dict(UpperCAmelCase__ , strict=UpperCAmelCase__ ) if set(UpperCAmelCase__ ) != {"luke.embeddings.position_ids"}: raise ValueError(F'''Unexpected unexpected_keys: {unexpected_keys}''' ) if set(UpperCAmelCase__ ) != { "lm_head.decoder.weight", "lm_head.decoder.bias", "entity_predictions.decoder.weight", }: raise ValueError(F'''Unexpected missing_keys: {missing_keys}''' ) model.tie_weights() assert (model.luke.embeddings.word_embeddings.weight == model.lm_head.decoder.weight).all() assert (model.luke.entity_embeddings.entity_embeddings.weight == model.entity_predictions.decoder.weight).all() # Check outputs UpperCamelCase_: Optional[int] = MLukeTokenizer.from_pretrained(UpperCAmelCase__ , task='entity_classification' ) UpperCamelCase_: Tuple = 'ISO 639-3 uses the code fas for the dialects spoken across Iran and アフガニスタン (Afghanistan).' UpperCamelCase_: Optional[int] = (0, 9) UpperCamelCase_: Union[str, Any] = tokenizer(UpperCAmelCase__ , entity_spans=[span] , return_tensors='pt' ) UpperCamelCase_: str = model(**UpperCAmelCase__ ) # Verify word hidden states if model_size == "large": raise NotImplementedError else: # base UpperCamelCase_: int = torch.Size((1, 3_3, 7_6_8) ) UpperCamelCase_: Tuple = torch.tensor([[0.0892, 0.0596, -0.2819], [0.0134, 0.1199, 0.0573], [-0.0169, 0.0927, 0.0644]] ) 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] , UpperCAmelCase__ , atol=1E-4 ): raise ValueError # Verify entity hidden states if model_size == "large": raise NotImplementedError else: # base UpperCamelCase_: Dict = torch.Size((1, 1, 7_6_8) ) UpperCamelCase_: Tuple = torch.tensor([[-0.1482, 0.0609, 0.0322]] ) 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] , UpperCAmelCase__ , atol=1E-4 ): raise ValueError # Verify masked word/entity prediction UpperCamelCase_: str = MLukeTokenizer.from_pretrained(UpperCAmelCase__ ) UpperCamelCase_: int = 'Tokyo is the capital of <mask>.' UpperCamelCase_: Dict = (2_4, 3_0) UpperCamelCase_: int = tokenizer(UpperCAmelCase__ , entity_spans=[span] , return_tensors='pt' ) UpperCamelCase_: Dict = model(**UpperCAmelCase__ ) UpperCamelCase_: Optional[int] = encoding['input_ids'][0].tolist() UpperCamelCase_: List[Any] = input_ids.index(tokenizer.convert_tokens_to_ids('<mask>' ) ) UpperCamelCase_: Any = outputs.logits[0][mask_position_id].argmax(dim=-1 ) assert "Japan" == tokenizer.decode(UpperCAmelCase__ ) UpperCamelCase_: Union[str, Any] = outputs.entity_logits[0][0].argmax().item() UpperCamelCase_: Optional[Any] = [ entity for entity, entity_id in tokenizer.entity_vocab.items() if entity_id == predicted_entity_id ] assert [e for e in multilingual_predicted_entities if e.startswith('en:' )][0] == "en:Japan" # Finally, save our PyTorch model and tokenizer print('Saving PyTorch model to {}'.format(UpperCAmelCase__ ) ) model.save_pretrained(UpperCAmelCase__ ) def snake_case (UpperCAmelCase__ ) -> int: UpperCamelCase_: Optional[Any] = ['[MASK]', '[PAD]', '[UNK]'] UpperCamelCase_: Any = [json.loads(UpperCAmelCase__ ) for line in open(UpperCAmelCase__ )] UpperCamelCase_: Tuple = {} for entry in data: UpperCamelCase_: Optional[int] = entry['id'] for entity_name, language in entry["entities"]: if entity_name in SPECIAL_TOKENS: UpperCamelCase_: Union[str, Any] = entity_id break UpperCamelCase_: Dict = F'''{language}:{entity_name}''' UpperCamelCase_: Optional[int] = entity_id return new_mapping if __name__ == "__main__": A_ : Tuple = 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_ : List[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, )
57
0
import argparse import json import gdown import numpy as np import torch from huggingface_hub import hf_hub_download from transformers import ( VideoMAEConfig, VideoMAEForPreTraining, VideoMAEForVideoClassification, VideoMAEImageProcessor, ) def _SCREAMING_SNAKE_CASE ( lowercase : int ): '''simple docstring''' lowerCamelCase_ = VideoMAEConfig() set_architecture_configs(lowercase , lowercase ) if "finetuned" not in model_name: lowerCamelCase_ = False if "finetuned" in model_name: lowerCamelCase_ = 'huggingface/label-files' if "kinetics" in model_name: lowerCamelCase_ = 4_00 lowerCamelCase_ = 'kinetics400-id2label.json' elif "ssv2" in model_name: lowerCamelCase_ = 1_74 lowerCamelCase_ = 'something-something-v2-id2label.json' else: raise ValueError('Model name should either contain \'kinetics\' or \'ssv2\' in case it\'s fine-tuned.' ) lowerCamelCase_ = json.load(open(hf_hub_download(lowercase , lowercase , repo_type='dataset' ) , 'r' ) ) lowerCamelCase_ = {int(lowercase ): v for k, v in idalabel.items()} lowerCamelCase_ = idalabel lowerCamelCase_ = {v: k for k, v in idalabel.items()} return config def _SCREAMING_SNAKE_CASE ( lowercase : List[Any] , lowercase : Optional[Any] ): '''simple docstring''' if "small" in model_name: lowerCamelCase_ = 3_84 lowerCamelCase_ = 15_36 lowerCamelCase_ = 12 lowerCamelCase_ = 16 lowerCamelCase_ = 12 lowerCamelCase_ = 3 lowerCamelCase_ = 1_92 lowerCamelCase_ = 7_68 elif "large" in model_name: lowerCamelCase_ = 10_24 lowerCamelCase_ = 40_96 lowerCamelCase_ = 24 lowerCamelCase_ = 16 lowerCamelCase_ = 12 lowerCamelCase_ = 8 lowerCamelCase_ = 5_12 lowerCamelCase_ = 20_48 elif "huge" in model_name: lowerCamelCase_ = 12_80 lowerCamelCase_ = 51_20 lowerCamelCase_ = 32 lowerCamelCase_ = 16 lowerCamelCase_ = 12 lowerCamelCase_ = 8 lowerCamelCase_ = 6_40 lowerCamelCase_ = 25_60 elif "base" not in model_name: raise ValueError('Model name should include either "small", "base", "large", or "huge"' ) def _SCREAMING_SNAKE_CASE ( lowercase : int ): '''simple docstring''' if "encoder." in name: lowerCamelCase_ = name.replace('encoder.' , '' ) if "cls_token" in name: lowerCamelCase_ = name.replace('cls_token' , 'videomae.embeddings.cls_token' ) if "decoder_pos_embed" in name: lowerCamelCase_ = name.replace('decoder_pos_embed' , 'decoder.decoder_pos_embed' ) if "pos_embed" in name and "decoder" not in name: lowerCamelCase_ = name.replace('pos_embed' , 'videomae.embeddings.position_embeddings' ) if "patch_embed.proj" in name: lowerCamelCase_ = name.replace('patch_embed.proj' , 'videomae.embeddings.patch_embeddings.projection' ) if "patch_embed.norm" in name: lowerCamelCase_ = name.replace('patch_embed.norm' , 'videomae.embeddings.norm' ) if "decoder.blocks" in name: lowerCamelCase_ = name.replace('decoder.blocks' , 'decoder.decoder_layers' ) if "blocks" in name: lowerCamelCase_ = name.replace('blocks' , 'videomae.encoder.layer' ) if "attn.proj" in name: lowerCamelCase_ = name.replace('attn.proj' , 'attention.output.dense' ) if "attn" in name and "bias" not in name: lowerCamelCase_ = name.replace('attn' , 'attention.self' ) if "attn" in name: lowerCamelCase_ = name.replace('attn' , 'attention.attention' ) if "norm1" in name: lowerCamelCase_ = name.replace('norm1' , 'layernorm_before' ) if "norm2" in name: lowerCamelCase_ = name.replace('norm2' , 'layernorm_after' ) if "mlp.fc1" in name: lowerCamelCase_ = name.replace('mlp.fc1' , 'intermediate.dense' ) if "mlp.fc2" in name: lowerCamelCase_ = name.replace('mlp.fc2' , 'output.dense' ) if "decoder_embed" in name: lowerCamelCase_ = name.replace('decoder_embed' , 'decoder.decoder_embed' ) if "decoder_norm" in name: lowerCamelCase_ = name.replace('decoder_norm' , 'decoder.decoder_norm' ) if "decoder_pred" in name: lowerCamelCase_ = name.replace('decoder_pred' , 'decoder.decoder_pred' ) if "norm.weight" in name and "decoder" not in name and "fc" not in name: lowerCamelCase_ = name.replace('norm.weight' , 'videomae.layernorm.weight' ) if "norm.bias" in name and "decoder" not in name and "fc" not in name: lowerCamelCase_ = name.replace('norm.bias' , 'videomae.layernorm.bias' ) if "head" in name and "decoder" not in name: lowerCamelCase_ = name.replace('head' , 'classifier' ) return name def _SCREAMING_SNAKE_CASE ( lowercase : Tuple , lowercase : str ): '''simple docstring''' for key in orig_state_dict.copy().keys(): lowerCamelCase_ = orig_state_dict.pop(lowercase ) if key.startswith('encoder.' ): lowerCamelCase_ = key.replace('encoder.' , '' ) if "qkv" in key: lowerCamelCase_ = key.split('.' ) if key.startswith('decoder.blocks' ): lowerCamelCase_ = config.decoder_hidden_size lowerCamelCase_ = int(key_split[2] ) lowerCamelCase_ = 'decoder.decoder_layers.' if "weight" in key: lowerCamelCase_ = val[:dim, :] lowerCamelCase_ = val[dim : dim * 2, :] lowerCamelCase_ = val[-dim:, :] else: lowerCamelCase_ = config.hidden_size lowerCamelCase_ = int(key_split[1] ) lowerCamelCase_ = 'videomae.encoder.layer.' if "weight" in key: lowerCamelCase_ = val[:dim, :] lowerCamelCase_ = val[dim : dim * 2, :] lowerCamelCase_ = val[-dim:, :] else: lowerCamelCase_ = val return orig_state_dict def _SCREAMING_SNAKE_CASE ( ): '''simple docstring''' lowerCamelCase_ = hf_hub_download( repo_id='hf-internal-testing/spaghetti-video' , filename='eating_spaghetti.npy' , repo_type='dataset' ) lowerCamelCase_ = np.load(lowercase ) return list(lowercase ) def _SCREAMING_SNAKE_CASE ( lowercase : int , lowercase : List[str] , lowercase : Union[str, Any] , lowercase : str ): '''simple docstring''' lowerCamelCase_ = get_videomae_config(lowercase ) if "finetuned" in model_name: lowerCamelCase_ = VideoMAEForVideoClassification(lowercase ) else: lowerCamelCase_ = VideoMAEForPreTraining(lowercase ) # download original checkpoint, hosted on Google Drive lowerCamelCase_ = 'pytorch_model.bin' gdown.cached_download(lowercase , lowercase , quiet=lowercase ) lowerCamelCase_ = torch.load(lowercase , map_location='cpu' ) if "model" in files: lowerCamelCase_ = files['model'] else: lowerCamelCase_ = files['module'] lowerCamelCase_ = convert_state_dict(lowercase , lowercase ) model.load_state_dict(lowercase ) model.eval() # verify model on basic input lowerCamelCase_ = VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5] , image_std=[0.5, 0.5, 0.5] ) lowerCamelCase_ = prepare_video() lowerCamelCase_ = image_processor(lowercase , return_tensors='pt' ) if "finetuned" not in model_name: lowerCamelCase_ = hf_hub_download(repo_id='hf-internal-testing/bool-masked-pos' , filename='bool_masked_pos.pt' ) lowerCamelCase_ = torch.load(lowercase ) lowerCamelCase_ = model(**lowercase ) lowerCamelCase_ = outputs.logits lowerCamelCase_ = [ 'videomae-small-finetuned-kinetics', 'videomae-small-finetuned-ssv2', # Kinetics-400 checkpoints (short = pretrained only for 800 epochs instead of 1600) 'videomae-base-short', 'videomae-base-short-finetuned-kinetics', 'videomae-base', 'videomae-base-finetuned-kinetics', 'videomae-large', 'videomae-large-finetuned-kinetics', 'videomae-huge-finetuned-kinetics', # Something-Something-v2 checkpoints (short = pretrained only for 800 epochs instead of 2400) 'videomae-base-short-ssv2', 'videomae-base-short-finetuned-ssv2', 'videomae-base-ssv2', 'videomae-base-finetuned-ssv2', ] # NOTE: logits were tested with image_mean and image_std equal to [0.5, 0.5, 0.5] and [0.5, 0.5, 0.5] if model_name == "videomae-small-finetuned-kinetics": lowerCamelCase_ = torch.Size([1, 4_00] ) lowerCamelCase_ = torch.tensor([-0.9291, -0.4061, -0.9307] ) elif model_name == "videomae-small-finetuned-ssv2": lowerCamelCase_ = torch.Size([1, 1_74] ) lowerCamelCase_ = torch.tensor([0.2671, -0.4689, -0.8235] ) elif model_name == "videomae-base": lowerCamelCase_ = torch.Size([1, 14_08, 15_36] ) lowerCamelCase_ = torch.tensor([[0.7739, 0.7968, 0.7089], [0.6701, 0.7487, 0.6209], [0.4287, 0.5158, 0.4773]] ) elif model_name == "videomae-base-short": lowerCamelCase_ = torch.Size([1, 14_08, 15_36] ) lowerCamelCase_ = torch.tensor([[0.7994, 0.9612, 0.8508], [0.7401, 0.8958, 0.8302], [0.5862, 0.7468, 0.7325]] ) # we verified the loss both for normalized and unnormalized targets for this one lowerCamelCase_ = torch.tensor([0.5142] ) if config.norm_pix_loss else torch.tensor([0.6469] ) elif model_name == "videomae-large": lowerCamelCase_ = torch.Size([1, 14_08, 15_36] ) lowerCamelCase_ = torch.tensor([[0.7149, 0.7997, 0.6966], [0.6768, 0.7869, 0.6948], [0.5139, 0.6221, 0.5605]] ) elif model_name == "videomae-large-finetuned-kinetics": lowerCamelCase_ = torch.Size([1, 4_00] ) lowerCamelCase_ = torch.tensor([0.0771, 0.0011, -0.3625] ) elif model_name == "videomae-huge-finetuned-kinetics": lowerCamelCase_ = torch.Size([1, 4_00] ) lowerCamelCase_ = torch.tensor([0.2433, 0.1632, -0.4894] ) elif model_name == "videomae-base-short-finetuned-kinetics": lowerCamelCase_ = torch.Size([1, 4_00] ) lowerCamelCase_ = torch.tensor([0.6588, 0.0990, -0.2493] ) elif model_name == "videomae-base-finetuned-kinetics": lowerCamelCase_ = torch.Size([1, 4_00] ) lowerCamelCase_ = torch.tensor([0.3669, -0.0688, -0.2421] ) elif model_name == "videomae-base-short-ssv2": lowerCamelCase_ = torch.Size([1, 14_08, 15_36] ) lowerCamelCase_ = torch.tensor([[0.4712, 0.5296, 0.5786], [0.2278, 0.2729, 0.4026], [0.0352, 0.0730, 0.2506]] ) elif model_name == "videomae-base-short-finetuned-ssv2": lowerCamelCase_ = torch.Size([1, 1_74] ) lowerCamelCase_ = torch.tensor([-0.0537, -0.1539, -0.3266] ) elif model_name == "videomae-base-ssv2": lowerCamelCase_ = torch.Size([1, 14_08, 15_36] ) lowerCamelCase_ = torch.tensor([[0.8131, 0.8727, 0.8546], [0.7366, 0.9377, 0.8870], [0.5935, 0.8874, 0.8564]] ) elif model_name == "videomae-base-finetuned-ssv2": lowerCamelCase_ = torch.Size([1, 1_74] ) lowerCamelCase_ = torch.tensor([0.1961, -0.8337, -0.6389] ) else: raise ValueError(f"""Model name not supported. Should be one of {model_names}""" ) # verify logits assert logits.shape == expected_shape if "finetuned" in model_name: assert torch.allclose(logits[0, :3] , lowercase , atol=1e-4 ) else: print('Logits:' , logits[0, :3, :3] ) assert torch.allclose(logits[0, :3, :3] , lowercase , atol=1e-4 ) print('Logits ok!' ) # verify loss, if applicable if model_name == "videomae-base-short": lowerCamelCase_ = outputs.loss assert torch.allclose(lowercase , lowercase , atol=1e-4 ) print('Loss ok!' ) if pytorch_dump_folder_path is not None: print(f"""Saving model and image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(lowercase ) model.save_pretrained(lowercase ) if push_to_hub: print('Pushing to the hub...' ) model.push_to_hub(lowercase , organization='nielsr' ) if __name__ == "__main__": lowerCamelCase : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--checkpoint_url", default="https://drive.google.com/u/1/uc?id=1tEhLyskjb755TJ65ptsrafUG2llSwQE1&amp;export=download&amp;confirm=t&amp;uuid=aa3276eb-fb7e-482a-adec-dc7171df14c4", type=str, help=( "URL of the original PyTorch checkpoint (on Google Drive) you'd like to convert. Should be a direct" " download link." ), ) parser.add_argument( "--pytorch_dump_folder_path", default="/Users/nielsrogge/Documents/VideoMAE/Test", type=str, help="Path to the output PyTorch model directory.", ) parser.add_argument("--model_name", default="videomae-base", type=str, help="Name of the model.") parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub." ) lowerCamelCase : List[str] = parser.parse_args() convert_videomae_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.model_name, args.push_to_hub)
70
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A_ : Optional[Any] = logging.get_logger(__name__) A_ : Optional[Any] = { 'distilbert-base-uncased': 'https://huggingface.co/distilbert-base-uncased/resolve/main/config.json', 'distilbert-base-uncased-distilled-squad': ( 'https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/config.json' ), 'distilbert-base-cased': 'https://huggingface.co/distilbert-base-cased/resolve/main/config.json', 'distilbert-base-cased-distilled-squad': ( 'https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/config.json' ), 'distilbert-base-german-cased': 'https://huggingface.co/distilbert-base-german-cased/resolve/main/config.json', 'distilbert-base-multilingual-cased': ( 'https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/config.json' ), 'distilbert-base-uncased-finetuned-sst-2-english': ( 'https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-english/resolve/main/config.json' ), } class _lowerCAmelCase( UpperCAmelCase_ ): """simple docstring""" a : Dict ='''distilbert''' a : List[str] ={ '''hidden_size''': '''dim''', '''num_attention_heads''': '''n_heads''', '''num_hidden_layers''': '''n_layers''', } def __init__( self , _lowerCamelCase=3_0_5_2_2 , _lowerCamelCase=5_1_2 , _lowerCamelCase=False , _lowerCamelCase=6 , _lowerCamelCase=1_2 , _lowerCamelCase=7_6_8 , _lowerCamelCase=4 * 7_6_8 , _lowerCamelCase=0.1 , _lowerCamelCase=0.1 , _lowerCamelCase="gelu" , _lowerCamelCase=0.0_2 , _lowerCamelCase=0.1 , _lowerCamelCase=0.2 , _lowerCamelCase=0 , **_lowerCamelCase , ): UpperCamelCase_: Tuple = vocab_size UpperCamelCase_: str = max_position_embeddings UpperCamelCase_: Optional[int] = sinusoidal_pos_embds UpperCamelCase_: Union[str, Any] = n_layers UpperCamelCase_: Optional[int] = n_heads UpperCamelCase_: int = dim UpperCamelCase_: Tuple = hidden_dim UpperCamelCase_: Any = dropout UpperCamelCase_: Optional[Any] = attention_dropout UpperCamelCase_: List[str] = activation UpperCamelCase_: Optional[Any] = initializer_range UpperCamelCase_: Optional[Any] = qa_dropout UpperCamelCase_: List[str] = seq_classif_dropout super().__init__(**_lowerCamelCase , pad_token_id=_lowerCamelCase ) class _lowerCAmelCase( UpperCAmelCase_ ): """simple docstring""" @property def _a ( self ): if self.task == "multiple-choice": UpperCamelCase_: Any = {0: 'batch', 1: 'choice', 2: 'sequence'} else: UpperCamelCase_: List[Any] = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
57
0
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, XLMRobertaTokenizer from diffusers import AltDiffusionPipeline, AutoencoderKL, DDIMScheduler, PNDMScheduler, UNetaDConditionModel from diffusers.pipelines.alt_diffusion.modeling_roberta_series import ( RobertaSeriesConfig, RobertaSeriesModelWithTransformation, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class _snake_case (__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase): __A : Any =AltDiffusionPipeline __A : List[str] =TEXT_TO_IMAGE_PARAMS __A : Optional[int] =TEXT_TO_IMAGE_BATCH_PARAMS __A : List[Any] =TEXT_TO_IMAGE_IMAGE_PARAMS __A : Dict =TEXT_TO_IMAGE_IMAGE_PARAMS def UpperCamelCase__ ( self ): torch.manual_seed(0 ) UpperCAmelCase_ : Tuple = UNetaDConditionModel( block_out_channels=(32, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=4 ,out_channels=4 ,down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") ,up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") ,cross_attention_dim=32 ,) UpperCAmelCase_ : int = DDIMScheduler( beta_start=0.00085 ,beta_end=0.012 ,beta_schedule="scaled_linear" ,clip_sample=_snake_case ,set_alpha_to_one=_snake_case ,) torch.manual_seed(0 ) UpperCAmelCase_ : Optional[int] = AutoencoderKL( block_out_channels=[32, 64] ,in_channels=3 ,out_channels=3 ,down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] ,up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] ,latent_channels=4 ,) # TODO: address the non-deterministic text encoder (fails for save-load tests) # torch.manual_seed(0) # text_encoder_config = RobertaSeriesConfig( # hidden_size=32, # project_dim=32, # intermediate_size=37, # layer_norm_eps=1e-05, # num_attention_heads=4, # num_hidden_layers=5, # vocab_size=5002, # ) # text_encoder = RobertaSeriesModelWithTransformation(text_encoder_config) torch.manual_seed(0 ) UpperCAmelCase_ : str = CLIPTextConfig( bos_token_id=0 ,eos_token_id=2 ,hidden_size=32 ,projection_dim=32 ,intermediate_size=37 ,layer_norm_eps=1E-05 ,num_attention_heads=4 ,num_hidden_layers=5 ,pad_token_id=1 ,vocab_size=50_02 ,) UpperCAmelCase_ : Union[str, Any] = CLIPTextModel(_snake_case ) UpperCAmelCase_ : Optional[Any] = XLMRobertaTokenizer.from_pretrained("hf-internal-testing/tiny-xlm-roberta" ) UpperCAmelCase_ : List[Any] = 77 UpperCAmelCase_ : Optional[Any] = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "safety_checker": None, "feature_extractor": None, } return components def UpperCamelCase__ ( self ,_snake_case ,_snake_case=0 ): if str(_snake_case ).startswith("mps" ): UpperCAmelCase_ : int = torch.manual_seed(_snake_case ) else: UpperCAmelCase_ : Dict = torch.Generator(device=_snake_case ).manual_seed(_snake_case ) UpperCAmelCase_ : int = { "prompt": "A painting of a squirrel eating a burger", "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "output_type": "numpy", } return inputs def UpperCamelCase__ ( self ): super().test_attention_slicing_forward_pass(expected_max_diff=3E-3 ) def UpperCamelCase__ ( self ): super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) def UpperCamelCase__ ( self ): UpperCAmelCase_ : str = "cpu" # ensure determinism for the device-dependent torch.Generator UpperCAmelCase_ : List[Any] = self.get_dummy_components() torch.manual_seed(0 ) UpperCAmelCase_ : Union[str, Any] = RobertaSeriesConfig( hidden_size=32 ,project_dim=32 ,intermediate_size=37 ,layer_norm_eps=1E-05 ,num_attention_heads=4 ,num_hidden_layers=5 ,vocab_size=50_02 ,) # TODO: remove after fixing the non-deterministic text encoder UpperCAmelCase_ : Any = RobertaSeriesModelWithTransformation(_snake_case ) UpperCAmelCase_ : int = text_encoder UpperCAmelCase_ : int = AltDiffusionPipeline(**_snake_case ) UpperCAmelCase_ : Dict = alt_pipe.to(_snake_case ) alt_pipe.set_progress_bar_config(disable=_snake_case ) UpperCAmelCase_ : Any = self.get_dummy_inputs(_snake_case ) UpperCAmelCase_ : Any = "A photo of an astronaut" UpperCAmelCase_ : Tuple = alt_pipe(**_snake_case ) UpperCAmelCase_ : Union[str, Any] = output.images UpperCAmelCase_ : int = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) UpperCAmelCase_ : int = np.array( [0.5748162, 0.60447145, 0.48821217, 0.50100636, 0.5431185, 0.45763683, 0.49657696, 0.48132733, 0.47573093] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCamelCase__ ( self ): UpperCAmelCase_ : Optional[int] = "cpu" # ensure determinism for the device-dependent torch.Generator UpperCAmelCase_ : int = self.get_dummy_components() UpperCAmelCase_ : Union[str, Any] = PNDMScheduler(skip_prk_steps=_snake_case ) torch.manual_seed(0 ) UpperCAmelCase_ : List[str] = RobertaSeriesConfig( hidden_size=32 ,project_dim=32 ,intermediate_size=37 ,layer_norm_eps=1E-05 ,num_attention_heads=4 ,num_hidden_layers=5 ,vocab_size=50_02 ,) # TODO: remove after fixing the non-deterministic text encoder UpperCAmelCase_ : Union[str, Any] = RobertaSeriesModelWithTransformation(_snake_case ) UpperCAmelCase_ : Tuple = text_encoder UpperCAmelCase_ : List[str] = AltDiffusionPipeline(**_snake_case ) UpperCAmelCase_ : int = alt_pipe.to(_snake_case ) alt_pipe.set_progress_bar_config(disable=_snake_case ) UpperCAmelCase_ : Dict = self.get_dummy_inputs(_snake_case ) UpperCAmelCase_ : List[Any] = alt_pipe(**_snake_case ) UpperCAmelCase_ : Optional[Any] = output.images UpperCAmelCase_ : int = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) UpperCAmelCase_ : Optional[int] = np.array( [0.51605093, 0.5707241, 0.47365507, 0.50578886, 0.5633877, 0.4642503, 0.5182081, 0.48763484, 0.49084237] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch_gpu class _snake_case (unittest.TestCase): def UpperCamelCase__ ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase__ ( self ): # make sure here that pndm scheduler skips prk UpperCAmelCase_ : Optional[Any] = AltDiffusionPipeline.from_pretrained("BAAI/AltDiffusion" ,safety_checker=_snake_case ) UpperCAmelCase_ : str = alt_pipe.to(_snake_case ) alt_pipe.set_progress_bar_config(disable=_snake_case ) UpperCAmelCase_ : str = "A painting of a squirrel eating a burger" UpperCAmelCase_ : Any = torch.manual_seed(0 ) UpperCAmelCase_ : Optional[Any] = alt_pipe([prompt] ,generator=_snake_case ,guidance_scale=6.0 ,num_inference_steps=20 ,output_type="np" ) UpperCAmelCase_ : str = output.images UpperCAmelCase_ : Optional[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 5_12, 5_12, 3) UpperCAmelCase_ : Union[str, Any] = np.array([0.1010, 0.0800, 0.0794, 0.0885, 0.0843, 0.0762, 0.0769, 0.0729, 0.0586] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCamelCase__ ( self ): UpperCAmelCase_ : List[str] = DDIMScheduler.from_pretrained("BAAI/AltDiffusion" ,subfolder="scheduler" ) UpperCAmelCase_ : Union[str, Any] = AltDiffusionPipeline.from_pretrained("BAAI/AltDiffusion" ,scheduler=_snake_case ,safety_checker=_snake_case ) UpperCAmelCase_ : int = alt_pipe.to(_snake_case ) alt_pipe.set_progress_bar_config(disable=_snake_case ) UpperCAmelCase_ : List[Any] = "A painting of a squirrel eating a burger" UpperCAmelCase_ : Optional[int] = torch.manual_seed(0 ) UpperCAmelCase_ : Dict = alt_pipe([prompt] ,generator=_snake_case ,num_inference_steps=2 ,output_type="numpy" ) UpperCAmelCase_ : int = output.images UpperCAmelCase_ : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 5_12, 5_12, 3) UpperCAmelCase_ : Union[str, Any] = np.array([0.4019, 0.4052, 0.3810, 0.4119, 0.3916, 0.3982, 0.4651, 0.4195, 0.5323] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
71
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A_ : int = { 'configuration_lilt': ['LILT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LiltConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : Any = [ 'LILT_PRETRAINED_MODEL_ARCHIVE_LIST', 'LiltForQuestionAnswering', 'LiltForSequenceClassification', 'LiltForTokenClassification', 'LiltModel', 'LiltPreTrainedModel', ] if TYPE_CHECKING: from .configuration_lilt import LILT_PRETRAINED_CONFIG_ARCHIVE_MAP, LiltConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_lilt import ( LILT_PRETRAINED_MODEL_ARCHIVE_LIST, LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, LiltPreTrainedModel, ) else: import sys A_ : Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
57
0
'''simple docstring''' import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import SPIECE_UNDERLINE, logging _UpperCAmelCase : Dict = logging.get_logger(__name__) _UpperCAmelCase : List[Any] = {'''vocab_file''': '''spiece.model'''} _UpperCAmelCase : List[Any] = { '''vocab_file''': { '''xlnet-base-cased''': '''https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model''', '''xlnet-large-cased''': '''https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model''', } } _UpperCAmelCase : Any = { '''xlnet-base-cased''': None, '''xlnet-large-cased''': None, } # Segments (not really needed) _UpperCAmelCase : Any = 0 _UpperCAmelCase : List[Any] = 1 _UpperCAmelCase : str = 2 _UpperCAmelCase : Dict = 3 _UpperCAmelCase : Optional[int] = 4 class __magic_name__ ( __SCREAMING_SNAKE_CASE ): UpperCamelCase__ = VOCAB_FILES_NAMES UpperCamelCase__ = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase__ = 'left' def __init__( self , snake_case_ , snake_case_=False , snake_case_=True , snake_case_=False , snake_case_="<s>" , snake_case_="</s>" , snake_case_="<unk>" , snake_case_="<sep>" , snake_case_="<pad>" , snake_case_="<cls>" , snake_case_="<mask>" , snake_case_=["<eop>", "<eod>"] , snake_case_ = None , **snake_case_ , ): # Mask token behave like a normal word, i.e. include the space before it lowercase =AddedToken(snake_case_ , lstrip=snake_case_ , rstrip=snake_case_ ) if isinstance(snake_case_ , snake_case_ ) else mask_token lowercase ={} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=snake_case_ , remove_space=snake_case_ , keep_accents=snake_case_ , bos_token=snake_case_ , eos_token=snake_case_ , unk_token=snake_case_ , sep_token=snake_case_ , pad_token=snake_case_ , cls_token=snake_case_ , mask_token=snake_case_ , additional_special_tokens=snake_case_ , sp_model_kwargs=self.sp_model_kwargs , **snake_case_ , ) lowercase =3 lowercase =do_lower_case lowercase =remove_space lowercase =keep_accents lowercase =vocab_file lowercase =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(snake_case_ ) @property def _A( self ): return len(self.sp_model ) def _A( self ): lowercase ={self.convert_ids_to_tokens(snake_case_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ): lowercase =self.__dict__.copy() lowercase =None return state def __setstate__( self , snake_case_ ): lowercase =d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): lowercase ={} lowercase =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _A( self , snake_case_ ): if self.remove_space: lowercase =''' '''.join(inputs.strip().split() ) else: lowercase =inputs lowercase =outputs.replace('''``''' , '''"''' ).replace('''\'\'''' , '''"''' ) if not self.keep_accents: lowercase =unicodedata.normalize('''NFKD''' , snake_case_ ) lowercase =''''''.join([c for c in outputs if not unicodedata.combining(snake_case_ )] ) if self.do_lower_case: lowercase =outputs.lower() return outputs def _A( self , snake_case_ ): lowercase =self.preprocess_text(snake_case_ ) lowercase =self.sp_model.encode(snake_case_ , out_type=snake_case_ ) lowercase =[] for piece in pieces: if len(snake_case_ ) > 1 and piece[-1] == str(''',''' ) and piece[-2].isdigit(): lowercase =self.sp_model.EncodeAsPieces(piece[:-1].replace(snake_case_ , '''''' ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: lowercase =cur_pieces[1:] else: lowercase =cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(snake_case_ ) else: new_pieces.append(snake_case_ ) return new_pieces def _A( self , snake_case_ ): return self.sp_model.PieceToId(snake_case_ ) def _A( self , snake_case_ ): return self.sp_model.IdToPiece(snake_case_ ) def _A( self , snake_case_ ): lowercase =''''''.join(snake_case_ ).replace(snake_case_ , ''' ''' ).strip() return out_string def _A( self , snake_case_ , snake_case_ = False , snake_case_ = None , snake_case_ = True , **snake_case_ , ): lowercase =kwargs.pop('''use_source_tokenizer''' , snake_case_ ) lowercase =self.convert_ids_to_tokens(snake_case_ , skip_special_tokens=snake_case_ ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 lowercase =[] lowercase =[] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(snake_case_ ) ) lowercase =[] sub_texts.append(snake_case_ ) else: current_sub_text.append(snake_case_ ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(snake_case_ ) ) # Mimic the behavior of the Rust tokenizer: # By default, there are no spaces between special tokens lowercase =''''''.join(snake_case_ ) lowercase =( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: lowercase =self.clean_up_tokenization(snake_case_ ) return clean_text else: return text def _A( self , snake_case_ , snake_case_ = None ): lowercase =[self.sep_token_id] lowercase =[self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def _A( self , snake_case_ , snake_case_ = None , snake_case_ = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=snake_case_ , token_ids_a=snake_case_ , already_has_special_tokens=snake_case_ ) if token_ids_a is not None: return ([0] * len(snake_case_ )) + [1] + ([0] * len(snake_case_ )) + [1, 1] return ([0] * len(snake_case_ )) + [1, 1] def _A( self , snake_case_ , snake_case_ = None ): lowercase =[self.sep_token_id] lowercase =[2] if token_ids_a is None: return len(token_ids_a + sep ) * [0] + cls_segment_id return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id def _A( self , snake_case_ , snake_case_ = None ): if not os.path.isdir(snake_case_ ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return lowercase =os.path.join( snake_case_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(snake_case_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , snake_case_ ) elif not os.path.isfile(self.vocab_file ): with open(snake_case_ , '''wb''' ) as fi: lowercase =self.sp_model.serialized_model_proto() fi.write(snake_case_ ) return (out_vocab_file,)
72
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available A_ : List[str] = { 'configuration_roc_bert': ['ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'RoCBertConfig'], 'tokenization_roc_bert': ['RoCBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: pass try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : Union[str, Any] = [ 'ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'RoCBertForCausalLM', 'RoCBertForMaskedLM', 'RoCBertForMultipleChoice', 'RoCBertForPreTraining', 'RoCBertForQuestionAnswering', 'RoCBertForSequenceClassification', 'RoCBertForTokenClassification', 'RoCBertLayer', 'RoCBertModel', 'RoCBertPreTrainedModel', 'load_tf_weights_in_roc_bert', ] if TYPE_CHECKING: from .configuration_roc_bert import ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RoCBertConfig from .tokenization_roc_bert import RoCBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: raise OptionalDependencyNotAvailable() try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roc_bert import ( ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, RoCBertForCausalLM, RoCBertForMaskedLM, RoCBertForMultipleChoice, RoCBertForPreTraining, RoCBertForQuestionAnswering, RoCBertForSequenceClassification, RoCBertForTokenClassification, RoCBertLayer, RoCBertModel, RoCBertPreTrainedModel, load_tf_weights_in_roc_bert, ) else: import sys A_ : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
57
0
import json import logging import math import os import sys from dataclasses import dataclass, field from typing import Optional from datasets import Dataset, load_dataset import transformers from transformers import ( CONFIG_MAPPING, MODEL_FOR_MASKED_LM_MAPPING, AutoConfig, AutoModelForMaskedLM, AutoTokenizer, DataCollatorForWholeWordMask, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import get_last_checkpoint, is_main_process a_ : str = logging.getLogger(__name__) a_ : Dict = list(MODEL_FOR_MASKED_LM_MAPPING.keys()) a_ : Tuple = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class _snake_case : _lowercase : Optional[str] = field( default=A__ , metadata={ '''help''': ( '''The model checkpoint for weights initialization.Don\'t set if you want to train a model from scratch.''' ) } , ) _lowercase : Optional[str] = field( default=A__ , metadata={'''help''': '''If training from scratch, pass a model type from the list: ''' + ''', '''.join(A__ )} , ) _lowercase : Optional[str] = field( default=A__ , metadata={ '''help''': ( '''Override some existing default config settings when a model is trained from scratch. Example: ''' '''n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index''' ) } , ) _lowercase : Optional[str] = field( default=A__ , metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} ) _lowercase : Optional[str] = field( default=A__ , metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''} ) _lowercase : Optional[str] = field( default=A__ , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''} , ) _lowercase : bool = field( default=A__ , metadata={'''help''': '''Whether to use one of the fast tokenizer (backed by the tokenizers library) or not.'''} , ) _lowercase : str = field( default='''main''' , metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''} , ) _lowercase : bool = field( default=A__ , metadata={ '''help''': ( '''Will use the token generated when running `huggingface-cli login` (necessary to use this script ''' '''with private models).''' ) } , ) def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: if self.config_overrides is not None and (self.config_name is not None or self.model_name_or_path is not None): raise ValueError( '--config_overrides can\'t be used in combination with --config_name or --model_name_or_path') @dataclass class _snake_case : _lowercase : Optional[str] = field( default=A__ , metadata={'''help''': '''The name of the dataset to use (via the datasets library).'''} ) _lowercase : Optional[str] = field( default=A__ , metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''} ) _lowercase : Optional[str] = field(default=A__ , metadata={'''help''': '''The input training data file (a text file).'''} ) _lowercase : Optional[str] = field( default=A__ , metadata={'''help''': '''An optional input evaluation data file to evaluate the perplexity on (a text file).'''} , ) _lowercase : Optional[str] = field( default=A__ , metadata={'''help''': '''An optional input train ref data file for whole word masking in Chinese.'''} , ) _lowercase : Optional[str] = field( default=A__ , metadata={'''help''': '''An optional input validation ref data file for whole word masking in Chinese.'''} , ) _lowercase : bool = field( default=A__ , metadata={'''help''': '''Overwrite the cached training and evaluation sets'''} ) _lowercase : Optional[int] = field( default=5 , metadata={ '''help''': '''The percentage of the train set used as validation set in case there\'s no validation split''' } , ) _lowercase : Optional[int] = field( default=A__ , metadata={ '''help''': ( '''The maximum total input sequence length after tokenization. Sequences longer ''' '''than this will be truncated. Default to the max input length of the model.''' ) } , ) _lowercase : Optional[int] = field( default=A__ , metadata={'''help''': '''The number of processes to use for the preprocessing.'''} , ) _lowercase : float = field( default=0.15 , metadata={'''help''': '''Ratio of tokens to mask for masked language modeling loss'''} ) _lowercase : bool = 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.''' ) } , ) def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: if self.train_file is not None: SCREAMING_SNAKE_CASE = self.train_file.split('.')[-1] assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file." if self.validation_file is not None: SCREAMING_SNAKE_CASE = self.validation_file.split('.')[-1] assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file." def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): with open(_UpperCAmelCase , 'r' , encoding='utf-8') as f: SCREAMING_SNAKE_CASE = [json.loads(_UpperCAmelCase) for line in f.read().splitlines() if (len(_UpperCAmelCase) > 0 and not line.isspace())] assert len(_UpperCAmelCase) == len(_UpperCAmelCase) SCREAMING_SNAKE_CASE = {c: dataset[c] for c in dataset.column_names} SCREAMING_SNAKE_CASE = refs return Dataset.from_dict(_UpperCAmelCase) def lowerCamelCase__ (): # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. 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() # 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.') # 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)] , ) logger.setLevel(logging.INFO if is_main_process(training_args.local_rank) else logging.WARN) # 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}''') # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info('Training/evaluation parameters %s' , _UpperCAmelCase) # 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.dataset_name is not None: # Downloading and loading a dataset from the hub. SCREAMING_SNAKE_CASE = load_dataset(data_args.dataset_name , data_args.dataset_config_name) if "validation" not in datasets.keys(): SCREAMING_SNAKE_CASE = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=F'''train[:{data_args.validation_split_percentage}%]''' , ) SCREAMING_SNAKE_CASE = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=F'''train[{data_args.validation_split_percentage}%:]''' , ) else: 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] if extension == "txt": SCREAMING_SNAKE_CASE = 'text' SCREAMING_SNAKE_CASE = load_dataset(_UpperCAmelCase , data_files=_UpperCAmelCase) # 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 = { 'cache_dir': model_args.cache_dir, 'revision': model_args.model_revision, 'use_auth_token': True if model_args.use_auth_token else None, } if model_args.config_name: SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(model_args.config_name , **_UpperCAmelCase) elif model_args.model_name_or_path: SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(model_args.model_name_or_path , **_UpperCAmelCase) else: SCREAMING_SNAKE_CASE = CONFIG_MAPPING[model_args.model_type]() logger.warning('You are instantiating a new config instance from scratch.') if model_args.config_overrides is not None: logger.info(F'''Overriding config: {model_args.config_overrides}''') config.update_from_string(model_args.config_overrides) logger.info(F'''New config: {config}''') SCREAMING_SNAKE_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, } if model_args.tokenizer_name: SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(model_args.tokenizer_name , **_UpperCAmelCase) elif model_args.model_name_or_path: SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(model_args.model_name_or_path , **_UpperCAmelCase) else: raise ValueError( 'You are instantiating a new tokenizer from scratch. This is not supported by this script.' 'You can do it from another script, save it, and load it from here, using --tokenizer_name.') if model_args.model_name_or_path: SCREAMING_SNAKE_CASE = AutoModelForMaskedLM.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 , ) else: logger.info('Training new model from scratch') SCREAMING_SNAKE_CASE = AutoModelForMaskedLM.from_config(_UpperCAmelCase) model.resize_token_embeddings(len(_UpperCAmelCase)) # Preprocessing the datasets. # First we tokenize all the texts. if training_args.do_train: SCREAMING_SNAKE_CASE = datasets['train'].column_names else: SCREAMING_SNAKE_CASE = datasets['validation'].column_names SCREAMING_SNAKE_CASE = 'text' if 'text' in column_names else column_names[0] SCREAMING_SNAKE_CASE = 'max_length' if data_args.pad_to_max_length else False def tokenize_function(_UpperCAmelCase): # Remove empty lines SCREAMING_SNAKE_CASE = [line for line in examples['text'] if len(_UpperCAmelCase) > 0 and not line.isspace()] return tokenizer(examples['text'] , padding=_UpperCAmelCase , truncation=_UpperCAmelCase , max_length=data_args.max_seq_length) SCREAMING_SNAKE_CASE = datasets.map( _UpperCAmelCase , batched=_UpperCAmelCase , num_proc=data_args.preprocessing_num_workers , remove_columns=[text_column_name] , load_from_cache_file=not data_args.overwrite_cache , ) # Add the chinese references if provided if data_args.train_ref_file is not None: SCREAMING_SNAKE_CASE = add_chinese_references(tokenized_datasets['train'] , data_args.train_ref_file) if data_args.validation_ref_file is not None: SCREAMING_SNAKE_CASE = add_chinese_references( tokenized_datasets['validation'] , data_args.validation_ref_file) # If we have ref files, need to avoid it removed by trainer SCREAMING_SNAKE_CASE = data_args.train_ref_file or data_args.validation_ref_file if has_ref: SCREAMING_SNAKE_CASE = False # Data collator # This one will take care of randomly masking the tokens. SCREAMING_SNAKE_CASE = DataCollatorForWholeWordMask(tokenizer=_UpperCAmelCase , mlm_probability=data_args.mlm_probability) # Initialize our Trainer SCREAMING_SNAKE_CASE = Trainer( model=_UpperCAmelCase , args=_UpperCAmelCase , train_dataset=tokenized_datasets['train'] if training_args.do_train else None , eval_dataset=tokenized_datasets['validation'] if training_args.do_eval else None , tokenizer=_UpperCAmelCase , data_collator=_UpperCAmelCase , ) # Training if training_args.do_train: if last_checkpoint is not None: SCREAMING_SNAKE_CASE = last_checkpoint elif model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path): SCREAMING_SNAKE_CASE = model_args.model_name_or_path else: SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = trainer.train(resume_from_checkpoint=_UpperCAmelCase) trainer.save_model() # Saves the tokenizer too for easy upload SCREAMING_SNAKE_CASE = os.path.join(training_args.output_dir , 'train_results.txt') if trainer.is_world_process_zero(): with open(_UpperCAmelCase , 'w') as writer: logger.info('***** Train results *****') for key, value in sorted(train_result.metrics.items()): logger.info(F''' {key} = {value}''') writer.write(F'''{key} = {value}\n''') # Need to save the state, since Trainer.save_model saves only the tokenizer with the model trainer.state.save_to_json(os.path.join(training_args.output_dir , 'trainer_state.json')) # Evaluation SCREAMING_SNAKE_CASE = {} if training_args.do_eval: logger.info('*** Evaluate ***') SCREAMING_SNAKE_CASE = trainer.evaluate() SCREAMING_SNAKE_CASE = math.exp(eval_output['eval_loss']) SCREAMING_SNAKE_CASE = perplexity SCREAMING_SNAKE_CASE = os.path.join(training_args.output_dir , 'eval_results_mlm_wwm.txt') if trainer.is_world_process_zero(): with open(_UpperCAmelCase , 'w') as writer: logger.info('***** Eval results *****') for key, value in sorted(results.items()): logger.info(F''' {key} = {value}''') writer.write(F'''{key} = {value}\n''') return results def lowerCamelCase__ (_UpperCAmelCase): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
73
from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import BaseOutput, is_torch_available, is_transformers_available @dataclass class _lowerCAmelCase( UpperCAmelCase_ ): """simple docstring""" a : Union[List[PIL.Image.Image], np.ndarray] a : Optional[List[bool]] if is_transformers_available() and is_torch_available(): from .pipeline_semantic_stable_diffusion import SemanticStableDiffusionPipeline
57
0
from __future__ import annotations def a__ ( snake_case , snake_case , snake_case ): """simple docstring""" 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()
74
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConfig, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaForCTC, WavaVecaForPreTraining, WavaVecaProcessor, logging, ) from transformers.models.wavaveca.modeling_wavaveca import WavaVecaForSequenceClassification logging.set_verbosity_info() A_ : Tuple = logging.get_logger(__name__) A_ : Optional[int] = { 'post_extract_proj': 'feature_projection.projection', 'encoder.pos_conv.0': 'encoder.pos_conv_embed.conv', 'self_attn.k_proj': 'encoder.layers.*.attention.k_proj', 'self_attn.v_proj': 'encoder.layers.*.attention.v_proj', 'self_attn.q_proj': 'encoder.layers.*.attention.q_proj', 'self_attn.out_proj': 'encoder.layers.*.attention.out_proj', 'self_attn_layer_norm': 'encoder.layers.*.layer_norm', 'fc1': 'encoder.layers.*.feed_forward.intermediate_dense', 'fc2': 'encoder.layers.*.feed_forward.output_dense', 'final_layer_norm': 'encoder.layers.*.final_layer_norm', 'encoder.layer_norm': 'encoder.layer_norm', 'adapter_layer': 'encoder.layers.*.adapter_layer', 'w2v_model.layer_norm': 'feature_projection.layer_norm', 'quantizer.weight_proj': 'quantizer.weight_proj', 'quantizer.vars': 'quantizer.codevectors', 'project_q': 'project_q', 'final_proj': 'project_hid', 'w2v_encoder.proj': 'lm_head', 'mask_emb': 'masked_spec_embed', 'pooling_layer.linear': 'projector', 'pooling_layer.projection': 'classifier', } A_ : int = [ 'lm_head', 'quantizer.weight_proj', 'quantizer.codevectors', 'project_q', 'project_hid', 'projector', 'classifier', ] def snake_case (UpperCAmelCase__ ) -> str: UpperCamelCase_: Tuple = {} with open(UpperCAmelCase__ , 'r' ) as file: for line_number, line in enumerate(UpperCAmelCase__ ): UpperCamelCase_: List[Any] = line.strip() if line: UpperCamelCase_: List[Any] = line.split() UpperCamelCase_: Optional[Any] = line_number UpperCamelCase_: Any = words[0] UpperCamelCase_: List[Any] = value return result def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) -> List[str]: for attribute in key.split('.' ): UpperCamelCase_: str = getattr(UpperCAmelCase__ , UpperCAmelCase__ ) UpperCamelCase_: str = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(UpperCAmelCase__ ): UpperCamelCase_: Any = PARAM_MAPPING[full_name.split('.' )[-1]] UpperCamelCase_: Dict = 'param' if weight_type is not None and weight_type != "param": UpperCamelCase_: Optional[Any] = getattr(UpperCAmelCase__ , UpperCAmelCase__ ).shape elif weight_type is not None and weight_type == "param": UpperCamelCase_: Optional[Any] = hf_pointer for attribute in hf_param_name.split('.' ): UpperCamelCase_: str = getattr(UpperCAmelCase__ , UpperCAmelCase__ ) UpperCamelCase_: Tuple = shape_pointer.shape # let's reduce dimension UpperCamelCase_: int = value[0] else: UpperCamelCase_: Union[str, Any] = hf_pointer.shape if hf_shape != value.shape: raise ValueError( F'''Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be''' F''' {value.shape} for {full_name}''' ) if weight_type == "weight": UpperCamelCase_: Optional[int] = value elif weight_type == "weight_g": UpperCamelCase_: Any = value elif weight_type == "weight_v": UpperCamelCase_: Union[str, Any] = value elif weight_type == "bias": UpperCamelCase_: Union[str, Any] = value elif weight_type == "param": for attribute in hf_param_name.split('.' ): UpperCamelCase_: Dict = getattr(UpperCAmelCase__ , UpperCAmelCase__ ) UpperCamelCase_: Optional[Any] = value else: UpperCamelCase_: int = value logger.info(F'''{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.''' ) def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) -> Any: UpperCamelCase_: Union[str, Any] = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(UpperCAmelCase__ ): UpperCamelCase_: Dict = PARAM_MAPPING[full_name.split('.' )[-1]] UpperCamelCase_: List[Any] = 'param' if weight_type is not None and weight_type != "param": UpperCamelCase_: List[Any] = '.'.join([key, weight_type] ) elif weight_type is not None and weight_type == "param": UpperCamelCase_: Any = '.'.join([key, hf_param_name] ) else: UpperCamelCase_: Union[str, Any] = key UpperCamelCase_: Any = value if 'lm_head' in full_key else value[0] A_ : str = { 'W_a': 'linear_1.weight', 'W_b': 'linear_2.weight', 'b_a': 'linear_1.bias', 'b_b': 'linear_2.bias', 'ln_W': 'norm.weight', 'ln_b': 'norm.bias', } def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__=None , UpperCAmelCase__=None ) -> Any: UpperCamelCase_: Optional[int] = False for key, mapped_key in MAPPING.items(): UpperCamelCase_: Tuple = 'wav2vec2.' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]: UpperCamelCase_: Optional[Any] = True if "*" in mapped_key: UpperCamelCase_: Optional[int] = name.split(UpperCAmelCase__ )[0].split('.' )[-2] UpperCamelCase_: Any = mapped_key.replace('*' , UpperCAmelCase__ ) if "weight_g" in name: UpperCamelCase_: Union[str, Any] = 'weight_g' elif "weight_v" in name: UpperCamelCase_: Dict = 'weight_v' elif "bias" in name: UpperCamelCase_: int = 'bias' elif "weight" in name: # TODO: don't match quantizer.weight_proj UpperCamelCase_: str = 'weight' else: UpperCamelCase_: Union[str, Any] = None if hf_dict is not None: rename_dict(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) else: set_recursively(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) return is_used return is_used def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) -> List[str]: UpperCamelCase_: List[Any] = [] UpperCamelCase_: Dict = fairseq_model.state_dict() UpperCamelCase_: Optional[Any] = hf_model.wavaveca.feature_extractor for name, value in fairseq_dict.items(): UpperCamelCase_: Union[str, Any] = False if "conv_layers" in name: load_conv_layer( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , hf_model.config.feat_extract_norm == 'group' , ) UpperCamelCase_: List[Any] = True else: UpperCamelCase_: Tuple = load_wavaveca_layer(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) if not is_used: unused_weights.append(UpperCAmelCase__ ) logger.warning(F'''Unused weights: {unused_weights}''' ) def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) -> Any: UpperCamelCase_: Any = full_name.split('conv_layers.' )[-1] UpperCamelCase_: int = name.split('.' ) UpperCamelCase_: int = int(items[0] ) UpperCamelCase_: Union[str, Any] = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.''' ) UpperCamelCase_: Union[str, Any] = value logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.''' ) UpperCamelCase_: int = value logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.''' ) UpperCamelCase_: Union[str, Any] = value logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.''' ) UpperCamelCase_: List[Any] = value logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) else: unused_weights.append(UpperCAmelCase__ ) @torch.no_grad() def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__=None , UpperCAmelCase__=None , UpperCAmelCase__=True , UpperCAmelCase__=False ) -> Dict: if config_path is not None: UpperCamelCase_: Tuple = WavaVecaConfig.from_pretrained(UpperCAmelCase__ ) else: UpperCamelCase_: List[str] = WavaVecaConfig() if is_seq_class: UpperCamelCase_: int = read_txt_into_dict(UpperCAmelCase__ ) UpperCamelCase_: Tuple = idalabel UpperCamelCase_: str = WavaVecaForSequenceClassification(UpperCAmelCase__ ) UpperCamelCase_: Optional[int] = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6_0_0_0 , padding_value=0 , do_normalize=UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , ) feature_extractor.save_pretrained(UpperCAmelCase__ ) elif is_finetuned: if dict_path: UpperCamelCase_: List[Any] = Dictionary.load(UpperCAmelCase__ ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq UpperCamelCase_: Dict = target_dict.pad_index UpperCamelCase_: Tuple = target_dict.bos_index UpperCamelCase_: Optional[Any] = target_dict.eos_index UpperCamelCase_: Union[str, Any] = len(target_dict.symbols ) UpperCamelCase_: int = os.path.join(UpperCAmelCase__ , 'vocab.json' ) if not os.path.isdir(UpperCAmelCase__ ): logger.error('--pytorch_dump_folder_path ({}) should be a directory'.format(UpperCAmelCase__ ) ) return os.makedirs(UpperCAmelCase__ , exist_ok=UpperCAmelCase__ ) UpperCamelCase_: str = target_dict.indices # fairseq has the <pad> and <s> switched UpperCamelCase_: List[str] = 0 UpperCamelCase_: List[Any] = 1 with open(UpperCAmelCase__ , 'w' , encoding='utf-8' ) as vocab_handle: json.dump(UpperCAmelCase__ , UpperCAmelCase__ ) UpperCamelCase_: Union[str, Any] = WavaVecaCTCTokenizer( UpperCAmelCase__ , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token='|' , do_lower_case=UpperCAmelCase__ , ) UpperCamelCase_: Any = True if config.feat_extract_norm == 'layer' else False UpperCamelCase_: Tuple = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6_0_0_0 , padding_value=0 , do_normalize=UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , ) UpperCamelCase_: Dict = WavaVecaProcessor(feature_extractor=UpperCAmelCase__ , tokenizer=UpperCAmelCase__ ) processor.save_pretrained(UpperCAmelCase__ ) UpperCamelCase_: Any = WavaVecaForCTC(UpperCAmelCase__ ) else: UpperCamelCase_: Any = WavaVecaForPreTraining(UpperCAmelCase__ ) if is_finetuned or is_seq_class: UpperCamelCase_ ,UpperCamelCase_ ,UpperCamelCase_: Dict = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] )} ) else: UpperCamelCase_: List[str] = argparse.Namespace(task='audio_pretraining' ) UpperCamelCase_: Any = fairseq.tasks.setup_task(UpperCAmelCase__ ) UpperCamelCase_ ,UpperCamelCase_ ,UpperCamelCase_: Union[str, Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=UpperCAmelCase__ ) UpperCamelCase_: str = model[0].eval() recursively_load_weights(UpperCAmelCase__ , UpperCAmelCase__ , not is_finetuned ) hf_wavavec.save_pretrained(UpperCAmelCase__ ) if __name__ == "__main__": A_ : str = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint') parser.add_argument('--dict_path', default=None, type=str, help='Path to dict of fine-tuned model') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') parser.add_argument( '--not_finetuned', action='store_true', help='Whether the model to convert is a fine-tuned model or not' ) parser.add_argument( '--is_seq_class', action='store_true', help='Whether the model to convert is a fine-tuned sequence classification model or not', ) A_ : int = parser.parse_args() A_ : str = not args.not_finetuned and not args.is_seq_class convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, is_finetuned, args.is_seq_class, )
57
0
'''simple docstring''' import argparse import re import torch from CLAP import create_model from transformers import AutoFeatureExtractor, ClapConfig, ClapModel UpperCamelCase__ = { '''text_branch''': '''text_model''', '''audio_branch''': '''audio_model.audio_encoder''', '''attn''': '''attention.self''', '''self.proj''': '''output.dense''', '''attention.self_mask''': '''attn_mask''', '''mlp.fc1''': '''intermediate.dense''', '''mlp.fc2''': '''output.dense''', '''norm1''': '''layernorm_before''', '''norm2''': '''layernorm_after''', '''bn0''': '''batch_norm''', } UpperCamelCase__ = AutoFeatureExtractor.from_pretrained('''laion/clap-htsat-unfused''', truncation='''rand_trunc''') def a__ ( lowerCAmelCase__ , lowerCAmelCase__=False ) -> List[str]: UpperCAmelCase__ , UpperCAmelCase__ : List[str] = create_model( '''HTSAT-tiny''' , '''roberta''' , lowerCAmelCase__ , precision='''fp32''' , device='''cuda:0''' if torch.cuda.is_available() else '''cpu''' , enable_fusion=lowerCAmelCase__ , fusion_type='''aff_2d''' if enable_fusion else None , ) return model, model_cfg def a__ ( lowerCAmelCase__ ) -> Optional[Any]: UpperCAmelCase__ : int = {} UpperCAmelCase__ : Any = R'''.*sequential.(\d+).*''' UpperCAmelCase__ : Optional[int] = R'''.*_projection.(\d+).*''' for key, value in state_dict.items(): # check if any key needs to be modified for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items(): if key_to_modify in key: UpperCAmelCase__ : List[str] = key.replace(lowerCAmelCase__ , lowerCAmelCase__ ) if re.match(lowerCAmelCase__ , lowerCAmelCase__ ): # replace sequential layers with list UpperCAmelCase__ : Any = re.match(lowerCAmelCase__ , lowerCAmelCase__ ).group(1 ) UpperCAmelCase__ : Any = key.replace(F"""sequential.{sequential_layer}.""" , F"""layers.{int(lowerCAmelCase__ )//3}.linear.""" ) elif re.match(lowerCAmelCase__ , lowerCAmelCase__ ): UpperCAmelCase__ : Union[str, Any] = int(re.match(lowerCAmelCase__ , lowerCAmelCase__ ).group(1 ) ) # Because in CLAP they use `nn.Sequential`... UpperCAmelCase__ : Dict = 1 if projecton_layer == 0 else 2 UpperCAmelCase__ : Union[str, Any] = key.replace(F"""_projection.{projecton_layer}.""" , F"""_projection.linear{transformers_projection_layer}.""" ) if "audio" and "qkv" in key: # split qkv into query key and value UpperCAmelCase__ : Dict = value UpperCAmelCase__ : List[Any] = mixed_qkv.size(0 ) // 3 UpperCAmelCase__ : str = mixed_qkv[:qkv_dim] UpperCAmelCase__ : Dict = mixed_qkv[qkv_dim : qkv_dim * 2] UpperCAmelCase__ : Union[str, Any] = mixed_qkv[qkv_dim * 2 :] UpperCAmelCase__ : str = query_layer UpperCAmelCase__ : Tuple = key_layer UpperCAmelCase__ : int = value_layer else: UpperCAmelCase__ : List[Any] = value return model_state_dict def a__ ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__=False ) -> Optional[int]: UpperCAmelCase__ , UpperCAmelCase__ : Dict = init_clap(lowerCAmelCase__ , enable_fusion=lowerCAmelCase__ ) clap_model.eval() UpperCAmelCase__ : Union[str, Any] = clap_model.state_dict() UpperCAmelCase__ : Optional[int] = rename_state_dict(lowerCAmelCase__ ) UpperCAmelCase__ : Tuple = ClapConfig() UpperCAmelCase__ : Tuple = enable_fusion UpperCAmelCase__ : Union[str, Any] = ClapModel(lowerCAmelCase__ ) # ignore the spectrogram embedding layer model.load_state_dict(lowerCAmelCase__ , strict=lowerCAmelCase__ ) model.save_pretrained(lowerCAmelCase__ ) transformers_config.save_pretrained(lowerCAmelCase__ ) if __name__ == "__main__": UpperCamelCase__ = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument('''--enable_fusion''', action='''store_true''', help='''Whether to enable fusion or not''') UpperCamelCase__ = parser.parse_args() convert_clap_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.enable_fusion)
75
import inspect import os import unittest import torch import accelerate from accelerate import debug_launcher from accelerate.test_utils import ( execute_subprocess_async, require_cpu, require_huggingface_suite, require_multi_gpu, require_single_gpu, ) from accelerate.utils import patch_environment @require_huggingface_suite class _lowerCAmelCase( unittest.TestCase ): """simple docstring""" def _a ( self ): UpperCamelCase_: Optional[int] = inspect.getfile(accelerate.test_utils ) UpperCamelCase_: Dict = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ['scripts', 'external_deps', 'test_metrics.py'] ) from accelerate.test_utils.scripts.external_deps import test_metrics # noqa: F401 UpperCamelCase_: Tuple = test_metrics @require_cpu def _a ( self ): debug_launcher(self.test_metrics.main , num_processes=1 ) @require_cpu def _a ( self ): debug_launcher(self.test_metrics.main ) @require_single_gpu def _a ( self ): self.test_metrics.main() @require_multi_gpu def _a ( self ): print(f'''Found {torch.cuda.device_count()} devices.''' ) UpperCamelCase_: List[Any] = ['torchrun', f'''--nproc_per_node={torch.cuda.device_count()}''', self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(_lowerCamelCase , env=os.environ.copy() )
57
0
"""simple docstring""" def __UpperCAmelCase ( __UpperCamelCase , __UpperCamelCase ): if density <= 0: raise ValueError('''Impossible fluid density''' ) if bulk_modulus <= 0: raise ValueError('''Impossible bulk modulus''' ) return (bulk_modulus / density) ** 0.5 if __name__ == "__main__": import doctest doctest.testmod()
76
import math class _lowerCAmelCase: """simple docstring""" def _a ( self , _lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: int = 0.0 UpperCamelCase_: Tuple = 0.0 for i in range(len(_lowerCamelCase ) ): da += math.pow((sample[i] - weights[0][i]) , 2 ) da += math.pow((sample[i] - weights[1][i]) , 2 ) return 0 if da > da else 1 return 0 def _a ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): for i in range(len(_lowerCamelCase ) ): weights[j][i] += alpha * (sample[i] - weights[j][i]) return weights def snake_case () -> None: # Training Examples ( m, n ) UpperCamelCase_: List[str] = [[1, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 1, 1]] # weight initialization ( n, C ) UpperCamelCase_: List[Any] = [[0.2, 0.6, 0.5, 0.9], [0.8, 0.4, 0.7, 0.3]] # training UpperCamelCase_: Dict = SelfOrganizingMap() UpperCamelCase_: List[Any] = 3 UpperCamelCase_: List[str] = 0.5 for _ in range(UpperCAmelCase__ ): for j in range(len(UpperCAmelCase__ ) ): # training sample UpperCamelCase_: int = training_samples[j] # Compute the winning vector UpperCamelCase_: Tuple = self_organizing_map.get_winner(UpperCAmelCase__ , UpperCAmelCase__ ) # Update the winning vector UpperCamelCase_: Union[str, Any] = self_organizing_map.update(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) # classify test sample UpperCamelCase_: Dict = [0, 0, 0, 1] UpperCamelCase_: Union[str, Any] = self_organizing_map.get_winner(UpperCAmelCase__ , UpperCAmelCase__ ) # results print(F'''Clusters that the test sample belongs to : {winner}''' ) print(F'''Weights that have been trained : {weights}''' ) # running the main() function if __name__ == "__main__": main()
57
0
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A = logging.get_logger(__name__) A = { """distilbert-base-uncased""": """https://huggingface.co/distilbert-base-uncased/resolve/main/config.json""", """distilbert-base-uncased-distilled-squad""": ( """https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/config.json""" ), """distilbert-base-cased""": """https://huggingface.co/distilbert-base-cased/resolve/main/config.json""", """distilbert-base-cased-distilled-squad""": ( """https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/config.json""" ), """distilbert-base-german-cased""": """https://huggingface.co/distilbert-base-german-cased/resolve/main/config.json""", """distilbert-base-multilingual-cased""": ( """https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/config.json""" ), """distilbert-base-uncased-finetuned-sst-2-english""": ( """https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-english/resolve/main/config.json""" ), } class a__ ( __magic_name__ ): lowercase_ = "distilbert" lowercase_ = { "hidden_size": "dim", "num_attention_heads": "n_heads", "num_hidden_layers": "n_layers", } def __init__( self : Optional[int] , UpperCamelCase_ : str=30522 , UpperCamelCase_ : Tuple=512 , UpperCamelCase_ : Optional[int]=False , UpperCamelCase_ : List[str]=6 , UpperCamelCase_ : str=12 , UpperCamelCase_ : List[Any]=768 , UpperCamelCase_ : Optional[Any]=4 * 768 , UpperCamelCase_ : int=0.1 , UpperCamelCase_ : Any=0.1 , UpperCamelCase_ : Tuple="gelu" , UpperCamelCase_ : Any=0.02 , UpperCamelCase_ : Optional[int]=0.1 , UpperCamelCase_ : Tuple=0.2 , UpperCamelCase_ : Optional[int]=0 , **UpperCamelCase_ : List[str] , ): """simple docstring""" __UpperCAmelCase : int = vocab_size __UpperCAmelCase : Tuple = max_position_embeddings __UpperCAmelCase : str = sinusoidal_pos_embds __UpperCAmelCase : Union[str, Any] = n_layers __UpperCAmelCase : str = n_heads __UpperCAmelCase : Union[str, Any] = dim __UpperCAmelCase : str = hidden_dim __UpperCAmelCase : Optional[int] = dropout __UpperCAmelCase : Optional[int] = attention_dropout __UpperCAmelCase : Optional[int] = activation __UpperCAmelCase : int = initializer_range __UpperCAmelCase : int = qa_dropout __UpperCAmelCase : Optional[Any] = seq_classif_dropout super().__init__(**UpperCamelCase_ , pad_token_id=UpperCamelCase_) class a__ ( __magic_name__ ): @property def a_ ( self : Union[str, Any]): """simple docstring""" if self.task == "multiple-choice": __UpperCAmelCase : Dict = {0: "batch", 1: "choice", 2: "sequence"} else: __UpperCAmelCase : Optional[int] = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ])
77
from collections import namedtuple A_ : Tuple = namedtuple('from_to', 'from_ to') A_ : int = { 'cubicmeter': from_to(1, 1), 'litre': from_to(0.001, 1000), 'kilolitre': from_to(1, 1), 'gallon': from_to(0.00454, 264.172), 'cubicyard': from_to(0.76455, 1.30795), 'cubicfoot': from_to(0.028, 35.3147), 'cup': from_to(0.000236588, 4226.75), } def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) -> float: if from_type not in METRIC_CONVERSION: raise ValueError( F'''Invalid \'from_type\' value: {from_type!r} Supported values are:\n''' + ', '.join(UpperCAmelCase__ ) ) if to_type not in METRIC_CONVERSION: raise ValueError( F'''Invalid \'to_type\' value: {to_type!r}. Supported values are:\n''' + ', '.join(UpperCAmelCase__ ) ) return value * METRIC_CONVERSION[from_type].from_ * METRIC_CONVERSION[to_type].to if __name__ == "__main__": import doctest doctest.testmod()
57
0
'''simple docstring''' from collections import OrderedDict from typing import Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...feature_extraction_utils import FeatureExtractionMixin from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import TensorType, logging SCREAMING_SNAKE_CASE_: Optional[Any] =logging.get_logger(__name__) SCREAMING_SNAKE_CASE_: List[Any] ={ 'deepmind/language-perceiver': 'https://huggingface.co/deepmind/language-perceiver/resolve/main/config.json', # See all Perceiver models at https://huggingface.co/models?filter=perceiver } class __A ( UpperCamelCase__ ): a__ : List[Any] = """perceiver""" def __init__(self : Optional[int] , __a : Tuple=256 , __a : Optional[Any]=1280 , __a : Optional[int]=768 , __a : Any=1 , __a : List[str]=26 , __a : Dict=8 , __a : List[Any]=8 , __a : Tuple=None , __a : List[str]=None , __a : Optional[int]="kv" , __a : Union[str, Any]=1 , __a : List[str]=1 , __a : List[Any]="gelu" , __a : List[str]=0.1 , __a : str=0.02 , __a : List[str]=1E-12 , __a : Optional[int]=True , __a : Tuple=262 , __a : Dict=2048 , __a : int=56 , __a : Optional[int]=[368, 496] , __a : Any=16 , __a : Optional[Any]=1920 , __a : Any=16 , __a : str=[1, 16, 224, 224] , **__a : Any , ): super().__init__(**__a ) UpperCAmelCase_ = num_latents UpperCAmelCase_ = d_latents UpperCAmelCase_ = d_model UpperCAmelCase_ = num_blocks UpperCAmelCase_ = num_self_attends_per_block UpperCAmelCase_ = num_self_attention_heads UpperCAmelCase_ = num_cross_attention_heads UpperCAmelCase_ = qk_channels UpperCAmelCase_ = v_channels UpperCAmelCase_ = cross_attention_shape_for_attention UpperCAmelCase_ = self_attention_widening_factor UpperCAmelCase_ = cross_attention_widening_factor UpperCAmelCase_ = hidden_act UpperCAmelCase_ = attention_probs_dropout_prob UpperCAmelCase_ = initializer_range UpperCAmelCase_ = layer_norm_eps UpperCAmelCase_ = use_query_residual # masked language modeling attributes UpperCAmelCase_ = vocab_size UpperCAmelCase_ = max_position_embeddings # image classification attributes UpperCAmelCase_ = image_size # flow attributes UpperCAmelCase_ = train_size # multimodal autoencoding attributes UpperCAmelCase_ = num_frames UpperCAmelCase_ = audio_samples_per_frame UpperCAmelCase_ = samples_per_patch UpperCAmelCase_ = output_shape class __A ( UpperCamelCase__ ): @property def _lowercase (self : Dict ): if self.task == "multiple-choice": UpperCAmelCase_ = {0: "batch", 1: "choice", 2: "sequence"} else: UpperCAmelCase_ = {0: "batch", 1: "sequence"} return OrderedDict( [ ("inputs", dynamic_axis), ("attention_mask", dynamic_axis), ] ) @property def _lowercase (self : Optional[Any] ): return 1E-4 def _lowercase (self : Union[str, Any] , __a : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , __a : int = -1 , __a : int = -1 , __a : int = -1 , __a : bool = False , __a : Optional[TensorType] = None , __a : int = 3 , __a : int = 40 , __a : int = 40 , ): # copied from `transformers.onnx.config.OnnxConfig` and slightly altered/simplified if isinstance(__a , __a ): # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX UpperCAmelCase_ = compute_effective_axis_dimension( __a , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX UpperCAmelCase_ = preprocessor.num_special_tokens_to_add(__a ) UpperCAmelCase_ = compute_effective_axis_dimension( __a , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=__a ) # Generate dummy inputs according to compute batch and sequence UpperCAmelCase_ = [" ".join(["a"] ) * seq_length] * batch_size UpperCAmelCase_ = dict(preprocessor(__a , return_tensors=__a ) ) UpperCAmelCase_ = inputs.pop("input_ids" ) return inputs elif isinstance(__a , __a ) and preprocessor.model_input_names[0] == "pixel_values": # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX UpperCAmelCase_ = compute_effective_axis_dimension(__a , fixed_dimension=OnnxConfig.default_fixed_batch ) UpperCAmelCase_ = self._generate_dummy_images(__a , __a , __a , __a ) UpperCAmelCase_ = dict(preprocessor(images=__a , return_tensors=__a ) ) UpperCAmelCase_ = inputs.pop("pixel_values" ) return inputs else: raise ValueError( "Unable to generate dummy inputs for the model. Please provide a tokenizer or a preprocessor." )
78
import warnings from ...utils import logging from .image_processing_clip import CLIPImageProcessor A_ : int = logging.get_logger(__name__) class _lowerCAmelCase( UpperCAmelCase_ ): """simple docstring""" def __init__( self , *_lowerCamelCase , **_lowerCamelCase ): warnings.warn( 'The class CLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use CLIPImageProcessor instead.' , _lowerCamelCase , ) super().__init__(*_lowerCamelCase , **_lowerCamelCase )
57
0
from __future__ import annotations import unittest from transformers import BlenderbotConfig, BlenderbotTokenizer, is_tf_available from transformers.testing_utils import require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFBlenderbotForConditionalGeneration, TFBlenderbotModel @require_tf class UpperCAmelCase_ : __lowerCamelCase = BlenderbotConfig __lowerCamelCase = {} __lowerCamelCase = 'gelu' def __init__( self , _lowerCAmelCase , _lowerCAmelCase=13 , _lowerCAmelCase=7 , _lowerCAmelCase=True , _lowerCAmelCase=False , _lowerCAmelCase=99 , _lowerCAmelCase=32 , _lowerCAmelCase=2 , _lowerCAmelCase=4 , _lowerCAmelCase=37 , _lowerCAmelCase=0.1 , _lowerCAmelCase=0.1 , _lowerCAmelCase=20 , _lowerCAmelCase=2 , _lowerCAmelCase=1 , _lowerCAmelCase=0 , ): UpperCAmelCase__ : List[str] = parent UpperCAmelCase__ : str = batch_size UpperCAmelCase__ : Optional[int] = seq_length UpperCAmelCase__ : Dict = is_training UpperCAmelCase__ : List[Any] = use_labels UpperCAmelCase__ : List[Any] = vocab_size UpperCAmelCase__ : Optional[int] = hidden_size UpperCAmelCase__ : Optional[Any] = num_hidden_layers UpperCAmelCase__ : int = num_attention_heads UpperCAmelCase__ : Any = intermediate_size UpperCAmelCase__ : Dict = hidden_dropout_prob UpperCAmelCase__ : int = attention_probs_dropout_prob UpperCAmelCase__ : Any = max_position_embeddings UpperCAmelCase__ : Dict = eos_token_id UpperCAmelCase__ : List[Any] = pad_token_id UpperCAmelCase__ : Optional[int] = bos_token_id def __UpperCAmelCase ( self ): UpperCAmelCase__ : List[Any] = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) UpperCAmelCase__ : List[str] = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) UpperCAmelCase__ : Any = tf.concat([input_ids, eos_tensor] , axis=1 ) UpperCAmelCase__ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCAmelCase__ : Dict = 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 , ) UpperCAmelCase__ : Tuple = prepare_blenderbot_inputs_dict(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) return config, inputs_dict def __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase ): UpperCAmelCase__ : Union[str, Any] = TFBlenderbotModel(config=_lowerCAmelCase ).get_decoder() UpperCAmelCase__ : Dict = inputs_dict["""input_ids"""] UpperCAmelCase__ : Union[str, Any] = input_ids[:1, :] UpperCAmelCase__ : Dict = inputs_dict["""attention_mask"""][:1, :] UpperCAmelCase__ : List[Any] = inputs_dict["""head_mask"""] UpperCAmelCase__ : Optional[Any] = 1 # first forward pass UpperCAmelCase__ : List[str] = model(_lowerCAmelCase , attention_mask=_lowerCAmelCase , head_mask=_lowerCAmelCase , use_cache=_lowerCAmelCase ) UpperCAmelCase__ , UpperCAmelCase__ : List[Any] = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids UpperCAmelCase__ : List[str] = ids_tensor((self.batch_size, 3) , config.vocab_size ) UpperCAmelCase__ : Tuple = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and UpperCAmelCase__ : str = tf.concat([input_ids, next_tokens] , axis=-1 ) UpperCAmelCase__ : int = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) UpperCAmelCase__ : List[str] = model(_lowerCAmelCase , attention_mask=_lowerCAmelCase )[0] UpperCAmelCase__ : Optional[Any] = model(_lowerCAmelCase , attention_mask=_lowerCAmelCase , past_key_values=_lowerCAmelCase )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice UpperCAmelCase__ : Any = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) UpperCAmelCase__ : Any = output_from_no_past[:, -3:, random_slice_idx] UpperCAmelCase__ : Any = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(_lowerCAmelCase , _lowerCAmelCase , rtol=1e-3 ) def _lowerCamelCase ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=None , __lowerCamelCase=None , __lowerCamelCase=None , __lowerCamelCase=None , __lowerCamelCase=None , ) -> List[Any]: '''simple docstring''' if attention_mask is None: UpperCAmelCase__ : Tuple = tf.cast(tf.math.not_equal(__lowerCamelCase , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: UpperCAmelCase__ : Tuple = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: UpperCAmelCase__ : Any = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: UpperCAmelCase__ : int = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: UpperCAmelCase__ : int = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class UpperCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , unittest.TestCase ): __lowerCamelCase = (TFBlenderbotForConditionalGeneration, TFBlenderbotModel) if is_tf_available() else () __lowerCamelCase = (TFBlenderbotForConditionalGeneration,) if is_tf_available() else () __lowerCamelCase = ( { 'conversational': TFBlenderbotForConditionalGeneration, 'feature-extraction': TFBlenderbotModel, 'summarization': TFBlenderbotForConditionalGeneration, 'text2text-generation': TFBlenderbotForConditionalGeneration, 'translation': TFBlenderbotForConditionalGeneration, } if is_tf_available() else {} ) __lowerCamelCase = True __lowerCamelCase = False __lowerCamelCase = False def __UpperCAmelCase ( self ): UpperCAmelCase__ : Union[str, Any] = TFBlenderbotModelTester(self ) UpperCAmelCase__ : int = ConfigTester(self , config_class=_lowerCAmelCase ) def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): UpperCAmelCase__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*_lowerCAmelCase ) @require_tokenizers @require_tf class UpperCAmelCase_ ( unittest.TestCase ): __lowerCamelCase = ['My friends are cool but they eat too many carbs.'] __lowerCamelCase = 'facebook/blenderbot-400M-distill' @cached_property def __UpperCAmelCase ( self ): return BlenderbotTokenizer.from_pretrained(self.model_name ) @cached_property def __UpperCAmelCase ( self ): UpperCAmelCase__ : Tuple = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model @slow def __UpperCAmelCase ( self ): UpperCAmelCase__ : Optional[int] = self.tokenizer(self.src_text , return_tensors="""tf""" ) UpperCAmelCase__ : Union[str, Any] = self.model.generate( model_inputs.input_ids , ) UpperCAmelCase__ : List[str] = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=_lowerCAmelCase )[0] assert ( generated_words == " That's unfortunate. Are they trying to lose weight or are they just trying to be healthier?" )
79
import math from typing import Any, Callable, List, Optional, Tuple, Union import numpy as np import torch from ...models import TaFilmDecoder from ...schedulers import DDPMScheduler from ...utils import is_onnx_available, logging, randn_tensor if is_onnx_available(): from ..onnx_utils import OnnxRuntimeModel from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline from .continous_encoder import SpectrogramContEncoder from .notes_encoder import SpectrogramNotesEncoder A_ : List[Any] = logging.get_logger(__name__) # pylint: disable=invalid-name A_ : Optional[int] = 256 class _lowerCAmelCase( UpperCAmelCase_ ): """simple docstring""" a : Union[str, Any] =['''melgan'''] def __init__( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , ): super().__init__() # From MELGAN UpperCamelCase_: Any = math.log(1e-5 ) # Matches MelGAN training. UpperCamelCase_: List[Any] = 4.0 # Largest value for most examples UpperCamelCase_: Tuple = 1_2_8 self.register_modules( notes_encoder=_lowerCamelCase , continuous_encoder=_lowerCamelCase , decoder=_lowerCamelCase , scheduler=_lowerCamelCase , melgan=_lowerCamelCase , ) def _a ( self , _lowerCamelCase , _lowerCamelCase=(-1.0, 1.0) , _lowerCamelCase=False ): UpperCamelCase_ ,UpperCamelCase_: Union[str, Any] = output_range if clip: UpperCamelCase_: int = torch.clip(_lowerCamelCase , self.min_value , self.max_value ) # Scale to [0, 1]. UpperCamelCase_: List[Any] = (features - self.min_value) / (self.max_value - self.min_value) # Scale to [min_out, max_out]. return zero_one * (max_out - min_out) + min_out def _a ( self , _lowerCamelCase , _lowerCamelCase=(-1.0, 1.0) , _lowerCamelCase=False ): UpperCamelCase_ ,UpperCamelCase_: Dict = input_range UpperCamelCase_: List[str] = torch.clip(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) if clip else outputs # Scale to [0, 1]. UpperCamelCase_: Optional[Any] = (outputs - min_out) / (max_out - min_out) # Scale to [self.min_value, self.max_value]. return zero_one * (self.max_value - self.min_value) + self.min_value def _a ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: str = input_tokens > 0 UpperCamelCase_ ,UpperCamelCase_: Tuple = self.notes_encoder( encoder_input_tokens=_lowerCamelCase , encoder_inputs_mask=_lowerCamelCase ) UpperCamelCase_ ,UpperCamelCase_: Any = self.continuous_encoder( encoder_inputs=_lowerCamelCase , encoder_inputs_mask=_lowerCamelCase ) return [(tokens_encoded, tokens_mask), (continuous_encoded, continuous_mask)] def _a ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: Dict = noise_time if not torch.is_tensor(_lowerCamelCase ): UpperCamelCase_: List[str] = torch.tensor([timesteps] , dtype=torch.long , device=input_tokens.device ) elif torch.is_tensor(_lowerCamelCase ) and len(timesteps.shape ) == 0: UpperCamelCase_: Dict = timesteps[None].to(input_tokens.device ) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML UpperCamelCase_: Union[str, Any] = timesteps * torch.ones(input_tokens.shape[0] , dtype=timesteps.dtype , device=timesteps.device ) UpperCamelCase_: Any = self.decoder( encodings_and_masks=_lowerCamelCase , decoder_input_tokens=_lowerCamelCase , decoder_noise_time=_lowerCamelCase ) return logits @torch.no_grad() def __call__( self , _lowerCamelCase , _lowerCamelCase = None , _lowerCamelCase = 1_0_0 , _lowerCamelCase = True , _lowerCamelCase = "numpy" , _lowerCamelCase = None , _lowerCamelCase = 1 , ): if (callback_steps is None) or ( callback_steps is not None and (not isinstance(_lowerCamelCase , _lowerCamelCase ) or callback_steps <= 0) ): raise ValueError( f'''`callback_steps` has to be a positive integer but is {callback_steps} of type''' f''' {type(_lowerCamelCase )}.''' ) UpperCamelCase_: List[str] = np.zeros([1, TARGET_FEATURE_LENGTH, self.n_dims] , dtype=np.floataa ) UpperCamelCase_: str = np.zeros([1, 0, self.n_dims] , np.floataa ) UpperCamelCase_: Dict = torch.ones((1, TARGET_FEATURE_LENGTH) , dtype=_lowerCamelCase , device=self.device ) for i, encoder_input_tokens in enumerate(_lowerCamelCase ): if i == 0: UpperCamelCase_: str = torch.from_numpy(pred_mel[:1].copy() ).to( device=self.device , dtype=self.decoder.dtype ) # The first chunk has no previous context. UpperCamelCase_: Tuple = torch.zeros((1, TARGET_FEATURE_LENGTH) , dtype=_lowerCamelCase , device=self.device ) else: # The full song pipeline does not feed in a context feature, so the mask # will be all 0s after the feature converter. Because we know we're # feeding in a full context chunk from the previous prediction, set it # to all 1s. UpperCamelCase_: Any = ones UpperCamelCase_: str = self.scale_features( _lowerCamelCase , output_range=[-1.0, 1.0] , clip=_lowerCamelCase ) UpperCamelCase_: Union[str, Any] = self.encode( input_tokens=torch.IntTensor([encoder_input_tokens] ).to(device=self.device ) , continuous_inputs=_lowerCamelCase , continuous_mask=_lowerCamelCase , ) # Sample encoder_continuous_inputs shaped gaussian noise to begin loop UpperCamelCase_: List[str] = randn_tensor( shape=encoder_continuous_inputs.shape , generator=_lowerCamelCase , device=self.device , dtype=self.decoder.dtype , ) # set step values self.scheduler.set_timesteps(_lowerCamelCase ) # Denoising diffusion loop for j, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): UpperCamelCase_: int = self.decode( encodings_and_masks=_lowerCamelCase , input_tokens=_lowerCamelCase , noise_time=t / self.scheduler.config.num_train_timesteps , ) # Compute previous output: x_t -> x_t-1 UpperCamelCase_: Tuple = self.scheduler.step(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , generator=_lowerCamelCase ).prev_sample UpperCamelCase_: List[Any] = self.scale_to_features(_lowerCamelCase , input_range=[-1.0, 1.0] ) UpperCamelCase_: Any = mel[:1] UpperCamelCase_: List[str] = mel.cpu().float().numpy() UpperCamelCase_: Tuple = np.concatenate([full_pred_mel, pred_mel[:1]] , axis=1 ) # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(_lowerCamelCase , _lowerCamelCase ) logger.info('Generated segment' , _lowerCamelCase ) if output_type == "numpy" and not is_onnx_available(): raise ValueError( 'Cannot return output in \'np\' format if ONNX is not available. Make sure to have ONNX installed or set \'output_type\' to \'mel\'.' ) elif output_type == "numpy" and self.melgan is None: raise ValueError( 'Cannot return output in \'np\' format if melgan component is not defined. Make sure to define `self.melgan` or set \'output_type\' to \'mel\'.' ) if output_type == "numpy": UpperCamelCase_: int = self.melgan(input_features=full_pred_mel.astype(np.floataa ) ) else: UpperCamelCase_: int = full_pred_mel if not return_dict: return (output,) return AudioPipelineOutput(audios=_lowerCamelCase )
57
0
def snake_case ( lowerCamelCase = 1_000 ): '''simple docstring''' __lowercase = -1 __lowercase = 0 for a in range(1 , n // 3 ): # Solving the two equations a**2+b**2=c**2 and a+b+c=N eliminating c __lowercase = (n * n - 2 * a * n) // (2 * n - 2 * a) __lowercase = n - a - b if c * c == (a * a + b * b): __lowercase = a * b * c if candidate >= product: __lowercase = candidate return product if __name__ == "__main__": print(F'''{solution() = }''')
80
import itertools from dataclasses import dataclass from typing import Any, Callable, Dict, List, Optional, Union import pandas as pd import pyarrow as pa import datasets import datasets.config from datasets.features.features import require_storage_cast from datasets.table import table_cast from datasets.utils.py_utils import Literal A_ : Union[str, Any] = datasets.utils.logging.get_logger(__name__) A_ : Optional[Any] = ['names', 'prefix'] A_ : List[str] = ['warn_bad_lines', 'error_bad_lines', 'mangle_dupe_cols'] A_ : List[Any] = ['encoding_errors', 'on_bad_lines'] A_ : Optional[Any] = ['date_format'] @dataclass class _lowerCAmelCase( datasets.BuilderConfig ): """simple docstring""" a : str ="," a : Optional[str] =None a : Optional[Union[int, List[int], str]] ="infer" a : Optional[List[str]] =None a : Optional[List[str]] =None a : Optional[Union[int, str, List[int], List[str]]] =None a : Optional[Union[List[int], List[str]]] =None a : Optional[str] =None a : bool =True a : Optional[Literal["c", "python", "pyarrow"]] =None a : Dict[Union[int, str], Callable[[Any], Any]] =None a : Optional[list] =None a : Optional[list] =None a : bool =False a : Optional[Union[int, List[int]]] =None a : Optional[int] =None a : Optional[Union[str, List[str]]] =None a : bool =True a : bool =True a : bool =False a : bool =True a : Optional[str] =None a : str ="." a : Optional[str] =None a : str ='"' a : int =0 a : Optional[str] =None a : Optional[str] =None a : Optional[str] =None a : Optional[str] =None a : bool =True a : bool =True a : int =0 a : bool =True a : bool =False a : Optional[str] =None a : int =10000 a : Optional[datasets.Features] =None a : Optional[str] ="strict" a : Literal["error", "warn", "skip"] ="error" a : Optional[str] =None def _a ( self ): if self.delimiter is not None: UpperCamelCase_: Optional[Any] = self.delimiter if self.column_names is not None: UpperCamelCase_: int = self.column_names @property def _a ( self ): UpperCamelCase_: Any = { 'sep': self.sep, 'header': self.header, 'names': self.names, 'index_col': self.index_col, 'usecols': self.usecols, 'prefix': self.prefix, 'mangle_dupe_cols': self.mangle_dupe_cols, 'engine': self.engine, 'converters': self.converters, 'true_values': self.true_values, 'false_values': self.false_values, 'skipinitialspace': self.skipinitialspace, 'skiprows': self.skiprows, 'nrows': self.nrows, 'na_values': self.na_values, 'keep_default_na': self.keep_default_na, 'na_filter': self.na_filter, 'verbose': self.verbose, 'skip_blank_lines': self.skip_blank_lines, 'thousands': self.thousands, 'decimal': self.decimal, 'lineterminator': self.lineterminator, 'quotechar': self.quotechar, 'quoting': self.quoting, 'escapechar': self.escapechar, 'comment': self.comment, 'encoding': self.encoding, 'dialect': self.dialect, 'error_bad_lines': self.error_bad_lines, 'warn_bad_lines': self.warn_bad_lines, 'skipfooter': self.skipfooter, 'doublequote': self.doublequote, 'memory_map': self.memory_map, 'float_precision': self.float_precision, 'chunksize': self.chunksize, 'encoding_errors': self.encoding_errors, 'on_bad_lines': self.on_bad_lines, 'date_format': self.date_format, } # some kwargs must not be passed if they don't have a default value # some others are deprecated and we can also not pass them if they are the default value for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS: if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig() , _lowerCamelCase ): del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 2.0 new arguments if not (datasets.config.PANDAS_VERSION.major >= 2): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 1.3 new arguments if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] return pd_read_csv_kwargs class _lowerCAmelCase( datasets.ArrowBasedBuilder ): """simple docstring""" a : Dict =CsvConfig def _a ( self ): return datasets.DatasetInfo(features=self.config.features ) def _a ( self , _lowerCamelCase ): if not self.config.data_files: raise ValueError(f'''At least one data file must be specified, but got data_files={self.config.data_files}''' ) UpperCamelCase_: Tuple = dl_manager.download_and_extract(self.config.data_files ) if isinstance(_lowerCamelCase , (str, list, tuple) ): UpperCamelCase_: List[Any] = data_files if isinstance(_lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: str = [files] UpperCamelCase_: Tuple = [dl_manager.iter_files(_lowerCamelCase ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'files': files} )] UpperCamelCase_: Tuple = [] for split_name, files in data_files.items(): if isinstance(_lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: Dict = [files] UpperCamelCase_: int = [dl_manager.iter_files(_lowerCamelCase ) for file in files] splits.append(datasets.SplitGenerator(name=_lowerCamelCase , gen_kwargs={'files': files} ) ) return splits def _a ( self , _lowerCamelCase ): if self.config.features is not None: UpperCamelCase_: List[Any] = self.config.features.arrow_schema if all(not require_storage_cast(_lowerCamelCase ) for feature in self.config.features.values() ): # cheaper cast UpperCamelCase_: Optional[int] = pa.Table.from_arrays([pa_table[field.name] for field in schema] , schema=_lowerCamelCase ) else: # more expensive cast; allows str <-> int/float or str to Audio for example UpperCamelCase_: int = table_cast(_lowerCamelCase , _lowerCamelCase ) return pa_table def _a ( self , _lowerCamelCase ): UpperCamelCase_: List[str] = self.config.features.arrow_schema if self.config.features else None # dtype allows reading an int column as str UpperCamelCase_: Dict = ( { name: dtype.to_pandas_dtype() if not require_storage_cast(_lowerCamelCase ) else object for name, dtype, feature in zip(schema.names , schema.types , self.config.features.values() ) } if schema is not None else None ) for file_idx, file in enumerate(itertools.chain.from_iterable(_lowerCamelCase ) ): UpperCamelCase_: Optional[Any] = pd.read_csv(_lowerCamelCase , iterator=_lowerCamelCase , dtype=_lowerCamelCase , **self.config.pd_read_csv_kwargs ) try: for batch_idx, df in enumerate(_lowerCamelCase ): UpperCamelCase_: Union[str, Any] = pa.Table.from_pandas(_lowerCamelCase ) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(_lowerCamelCase ) except ValueError as e: logger.error(f'''Failed to read file \'{file}\' with error {type(_lowerCamelCase )}: {e}''' ) raise
57
0
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_distilbert import DistilBertTokenizer _snake_case : List[str] = logging.get_logger(__name__) _snake_case : Dict = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} _snake_case : Any = { "vocab_file": { "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/vocab.txt", "distilbert-base-uncased-distilled-squad": ( "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/vocab.txt" ), "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/vocab.txt", "distilbert-base-cased-distilled-squad": ( "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/vocab.txt" ), "distilbert-base-german-cased": "https://huggingface.co/distilbert-base-german-cased/resolve/main/vocab.txt", "distilbert-base-multilingual-cased": ( "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/vocab.txt" ), }, "tokenizer_file": { "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/tokenizer.json", "distilbert-base-uncased-distilled-squad": ( "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/tokenizer.json" ), "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/tokenizer.json", "distilbert-base-cased-distilled-squad": ( "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/tokenizer.json" ), "distilbert-base-german-cased": ( "https://huggingface.co/distilbert-base-german-cased/resolve/main/tokenizer.json" ), "distilbert-base-multilingual-cased": ( "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/tokenizer.json" ), }, } _snake_case : str = { "distilbert-base-uncased": 512, "distilbert-base-uncased-distilled-squad": 512, "distilbert-base-cased": 512, "distilbert-base-cased-distilled-squad": 512, "distilbert-base-german-cased": 512, "distilbert-base-multilingual-cased": 512, } _snake_case : Dict = { "distilbert-base-uncased": {"do_lower_case": True}, "distilbert-base-uncased-distilled-squad": {"do_lower_case": True}, "distilbert-base-cased": {"do_lower_case": False}, "distilbert-base-cased-distilled-squad": {"do_lower_case": False}, "distilbert-base-german-cased": {"do_lower_case": False}, "distilbert-base-multilingual-cased": {"do_lower_case": False}, } class a (_lowerCAmelCase ): """simple docstring""" __UpperCAmelCase : Dict = VOCAB_FILES_NAMES __UpperCAmelCase : int = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase : Optional[Any] = PRETRAINED_INIT_CONFIGURATION __UpperCAmelCase : int = ["input_ids", "attention_mask"] __UpperCAmelCase : Tuple = DistilBertTokenizer def __init__( self : int , lowerCamelCase : Any=None , lowerCamelCase : int=None , lowerCamelCase : Tuple=True , lowerCamelCase : int="[UNK]" , lowerCamelCase : int="[SEP]" , lowerCamelCase : Optional[Any]="[PAD]" , lowerCamelCase : List[str]="[CLS]" , lowerCamelCase : List[Any]="[MASK]" , lowerCamelCase : Dict=True , lowerCamelCase : str=None , **lowerCamelCase : int , ) -> List[Any]: super().__init__( lowerCamelCase , tokenizer_file=lowerCamelCase , do_lower_case=lowerCamelCase , unk_token=lowerCamelCase , sep_token=lowerCamelCase , pad_token=lowerCamelCase , cls_token=lowerCamelCase , mask_token=lowerCamelCase , tokenize_chinese_chars=lowerCamelCase , strip_accents=lowerCamelCase , **lowerCamelCase , ) __snake_case : Dict = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("lowercase" , lowerCamelCase ) != do_lower_case or normalizer_state.get("strip_accents" , lowerCamelCase ) != strip_accents or normalizer_state.get("handle_chinese_chars" , lowerCamelCase ) != tokenize_chinese_chars ): __snake_case : List[Any] = getattr(lowerCamelCase , normalizer_state.pop("type" ) ) __snake_case : Union[str, Any] = do_lower_case __snake_case : Union[str, Any] = strip_accents __snake_case : List[str] = tokenize_chinese_chars __snake_case : Optional[Any] = normalizer_class(**lowerCamelCase ) __snake_case : List[Any] = do_lower_case def __snake_case ( self : Dict , lowerCamelCase : Any , lowerCamelCase : Any=None ) -> Any: __snake_case : Tuple = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __snake_case ( self : List[Any] , lowerCamelCase : List[int] , lowerCamelCase : Optional[List[int]] = None ) -> List[int]: __snake_case : Union[str, Any] = [self.sep_token_id] __snake_case : int = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __snake_case ( self : str , lowerCamelCase : str , lowerCamelCase : Optional[str] = None ) -> Tuple[str]: __snake_case : str = self._tokenizer.model.save(lowerCamelCase , name=lowerCamelCase ) return tuple(lowerCamelCase )
81
from ...configuration_utils import PretrainedConfig from ...utils import logging A_ : str = logging.get_logger(__name__) A_ : Union[str, Any] = { 's-JoL/Open-Llama-V1': 'https://huggingface.co/s-JoL/Open-Llama-V1/blob/main/config.json', } class _lowerCAmelCase( UpperCAmelCase_ ): """simple docstring""" a : Tuple ='''open-llama''' def __init__( self , _lowerCamelCase=1_0_0_0_0_0 , _lowerCamelCase=4_0_9_6 , _lowerCamelCase=1_1_0_0_8 , _lowerCamelCase=3_2 , _lowerCamelCase=3_2 , _lowerCamelCase="silu" , _lowerCamelCase=2_0_4_8 , _lowerCamelCase=0.0_2 , _lowerCamelCase=1e-6 , _lowerCamelCase=True , _lowerCamelCase=0 , _lowerCamelCase=1 , _lowerCamelCase=2 , _lowerCamelCase=False , _lowerCamelCase=True , _lowerCamelCase=0.1 , _lowerCamelCase=0.1 , _lowerCamelCase=True , _lowerCamelCase=True , _lowerCamelCase=None , **_lowerCamelCase , ): UpperCamelCase_: int = vocab_size UpperCamelCase_: List[Any] = max_position_embeddings UpperCamelCase_: Dict = hidden_size UpperCamelCase_: Dict = intermediate_size UpperCamelCase_: Union[str, Any] = num_hidden_layers UpperCamelCase_: Dict = num_attention_heads UpperCamelCase_: Union[str, Any] = hidden_act UpperCamelCase_: Union[str, Any] = initializer_range UpperCamelCase_: List[Any] = rms_norm_eps UpperCamelCase_: Union[str, Any] = use_cache UpperCamelCase_: Dict = kwargs.pop( 'use_memorry_efficient_attention' , _lowerCamelCase ) UpperCamelCase_: Union[str, Any] = hidden_dropout_prob UpperCamelCase_: Any = attention_dropout_prob UpperCamelCase_: int = use_stable_embedding UpperCamelCase_: Tuple = shared_input_output_embedding UpperCamelCase_: str = rope_scaling self._rope_scaling_validation() super().__init__( pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , tie_word_embeddings=_lowerCamelCase , **_lowerCamelCase , ) def _a ( self ): if self.rope_scaling is None: return if not isinstance(self.rope_scaling , _lowerCamelCase ) or len(self.rope_scaling ) != 2: raise ValueError( '`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, ' f'''got {self.rope_scaling}''' ) UpperCamelCase_: str = self.rope_scaling.get('type' , _lowerCamelCase ) UpperCamelCase_: int = self.rope_scaling.get('factor' , _lowerCamelCase ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( f'''`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}''' ) if rope_scaling_factor is None or not isinstance(_lowerCamelCase , _lowerCamelCase ) or rope_scaling_factor <= 1.0: raise ValueError(f'''`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}''' )
57
0
"""simple docstring""" import math from typing import Dict, Iterable, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, get_image_size, is_torch_available, is_torch_tensor, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_torch_available(): import torch if is_vision_available(): import PIL lowerCamelCase = logging.get_logger(__name__) def a__ ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ): def constraint_to_multiple_of(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__=0 , lowerCAmelCase__=None ): UpperCAmelCase_ = round(val / multiple ) * multiple if max_val is not None and x > max_val: UpperCAmelCase_ = math.floor(val / multiple ) * multiple if x < min_val: UpperCAmelCase_ = math.ceil(val / multiple ) * multiple return x UpperCAmelCase_ = (output_size, output_size) if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) else output_size UpperCAmelCase_ , UpperCAmelCase_ = get_image_size(lowerCAmelCase__ ) UpperCAmelCase_ , UpperCAmelCase_ = output_size # determine new height and width UpperCAmelCase_ = output_height / input_height UpperCAmelCase_ = output_width / input_width if keep_aspect_ratio: # scale as little as possible if abs(1 - scale_width ) < abs(1 - scale_height ): # fit width UpperCAmelCase_ = scale_width else: # fit height UpperCAmelCase_ = scale_height UpperCAmelCase_ = constraint_to_multiple_of(scale_height * input_height , multiple=lowerCAmelCase__ ) UpperCAmelCase_ = constraint_to_multiple_of(scale_width * input_width , multiple=lowerCAmelCase__ ) return (new_height, new_width) class lowercase__ ( SCREAMING_SNAKE_CASE ): '''simple docstring''' UpperCamelCase = ['''pixel_values'''] def __init__( self : Optional[int] , _UpperCAmelCase : bool = True , _UpperCAmelCase : Dict[str, int] = None , _UpperCAmelCase : PILImageResampling = PILImageResampling.BILINEAR , _UpperCAmelCase : bool = False , _UpperCAmelCase : int = 1 , _UpperCAmelCase : bool = True , _UpperCAmelCase : Union[int, float] = 1 / 255 , _UpperCAmelCase : bool = True , _UpperCAmelCase : Optional[Union[float, List[float]]] = None , _UpperCAmelCase : Optional[Union[float, List[float]]] = None , **_UpperCAmelCase : int , ) -> None: '''simple docstring''' super().__init__(**_UpperCAmelCase ) UpperCAmelCase_ = size if size is not None else {"height": 384, "width": 384} UpperCAmelCase_ = get_size_dict(_UpperCAmelCase ) UpperCAmelCase_ = do_resize UpperCAmelCase_ = size UpperCAmelCase_ = keep_aspect_ratio UpperCAmelCase_ = ensure_multiple_of UpperCAmelCase_ = resample UpperCAmelCase_ = do_rescale UpperCAmelCase_ = rescale_factor UpperCAmelCase_ = do_normalize UpperCAmelCase_ = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN UpperCAmelCase_ = image_std if image_std is not None else IMAGENET_STANDARD_STD def lowercase__ ( self : List[Any] , _UpperCAmelCase : np.ndarray , _UpperCAmelCase : Dict[str, int] , _UpperCAmelCase : bool = False , _UpperCAmelCase : int = 1 , _UpperCAmelCase : PILImageResampling = PILImageResampling.BICUBIC , _UpperCAmelCase : Optional[Union[str, ChannelDimension]] = None , **_UpperCAmelCase : List[Any] , ) -> np.ndarray: '''simple docstring''' UpperCAmelCase_ = get_size_dict(_UpperCAmelCase ) if "height" not in size or "width" not in size: raise ValueError(F"""The size dictionary must contain the keys 'height' and 'width'. Got {size.keys()}""" ) UpperCAmelCase_ = get_resize_output_image_size( _UpperCAmelCase , output_size=(size["height"], size["width"]) , keep_aspect_ratio=_UpperCAmelCase , multiple=_UpperCAmelCase , ) return resize(_UpperCAmelCase , size=_UpperCAmelCase , resample=_UpperCAmelCase , data_format=_UpperCAmelCase , **_UpperCAmelCase ) def lowercase__ ( self : List[str] , _UpperCAmelCase : np.ndarray , _UpperCAmelCase : Union[int, float] , _UpperCAmelCase : Optional[Union[str, ChannelDimension]] = None , **_UpperCAmelCase : Union[str, Any] , ) -> Tuple: '''simple docstring''' return rescale(_UpperCAmelCase , scale=_UpperCAmelCase , data_format=_UpperCAmelCase , **_UpperCAmelCase ) def lowercase__ ( self : Union[str, Any] , _UpperCAmelCase : np.ndarray , _UpperCAmelCase : Union[float, List[float]] , _UpperCAmelCase : Union[float, List[float]] , _UpperCAmelCase : Optional[Union[str, ChannelDimension]] = None , **_UpperCAmelCase : Any , ) -> np.ndarray: '''simple docstring''' return normalize(_UpperCAmelCase , mean=_UpperCAmelCase , std=_UpperCAmelCase , data_format=_UpperCAmelCase , **_UpperCAmelCase ) def lowercase__ ( self : int , _UpperCAmelCase : ImageInput , _UpperCAmelCase : bool = None , _UpperCAmelCase : int = None , _UpperCAmelCase : bool = None , _UpperCAmelCase : int = None , _UpperCAmelCase : PILImageResampling = None , _UpperCAmelCase : bool = None , _UpperCAmelCase : float = None , _UpperCAmelCase : bool = None , _UpperCAmelCase : Optional[Union[float, List[float]]] = None , _UpperCAmelCase : Optional[Union[float, List[float]]] = None , _UpperCAmelCase : Optional[Union[str, TensorType]] = None , _UpperCAmelCase : ChannelDimension = ChannelDimension.FIRST , **_UpperCAmelCase : Any , ) -> PIL.Image.Image: '''simple docstring''' UpperCAmelCase_ = do_resize if do_resize is not None else self.do_resize UpperCAmelCase_ = size if size is not None else self.size UpperCAmelCase_ = get_size_dict(_UpperCAmelCase ) UpperCAmelCase_ = keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio UpperCAmelCase_ = ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of UpperCAmelCase_ = resample if resample is not None else self.resample UpperCAmelCase_ = do_rescale if do_rescale is not None else self.do_rescale UpperCAmelCase_ = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCAmelCase_ = do_normalize if do_normalize is not None else self.do_normalize UpperCAmelCase_ = image_mean if image_mean is not None else self.image_mean UpperCAmelCase_ = image_std if image_std is not None else self.image_std UpperCAmelCase_ = make_list_of_images(_UpperCAmelCase ) if not valid_images(_UpperCAmelCase ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # All transformations expect numpy arrays. UpperCAmelCase_ = [to_numpy_array(_UpperCAmelCase ) for image in images] if do_resize: UpperCAmelCase_ = [self.resize(image=_UpperCAmelCase , size=_UpperCAmelCase , resample=_UpperCAmelCase ) for image in images] if do_rescale: UpperCAmelCase_ = [self.rescale(image=_UpperCAmelCase , scale=_UpperCAmelCase ) for image in images] if do_normalize: UpperCAmelCase_ = [self.normalize(image=_UpperCAmelCase , mean=_UpperCAmelCase , std=_UpperCAmelCase ) for image in images] UpperCAmelCase_ = [to_channel_dimension_format(_UpperCAmelCase , _UpperCAmelCase ) for image in images] UpperCAmelCase_ = {"pixel_values": images} return BatchFeature(data=_UpperCAmelCase , tensor_type=_UpperCAmelCase ) def lowercase__ ( self : Union[str, Any] , _UpperCAmelCase : Optional[int] , _UpperCAmelCase : List[Tuple] = None ) -> int: '''simple docstring''' UpperCAmelCase_ = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(_UpperCAmelCase ) != len(_UpperCAmelCase ): raise ValueError( "Make sure that you pass in as many target sizes as the batch dimension of the logits" ) if is_torch_tensor(_UpperCAmelCase ): UpperCAmelCase_ = target_sizes.numpy() UpperCAmelCase_ = [] for idx in range(len(_UpperCAmelCase ) ): UpperCAmelCase_ = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode="bilinear" , align_corners=_UpperCAmelCase ) UpperCAmelCase_ = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(_UpperCAmelCase ) else: UpperCAmelCase_ = logits.argmax(dim=1 ) UpperCAmelCase_ = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
82
import collections import inspect import unittest from transformers import FocalNetConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( FocalNetBackbone, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetModel, ) from transformers.models.focalnet.modeling_focalnet import FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class _lowerCAmelCase: """simple docstring""" def __init__( self , _lowerCamelCase , _lowerCamelCase=1_3 , _lowerCamelCase=3_2 , _lowerCamelCase=2 , _lowerCamelCase=3 , _lowerCamelCase=1_6 , _lowerCamelCase=[3_2, 6_4, 1_2_8] , _lowerCamelCase=[1, 2, 1] , _lowerCamelCase=[2, 2, 4] , _lowerCamelCase=2 , _lowerCamelCase=2.0 , _lowerCamelCase=True , _lowerCamelCase=0.0 , _lowerCamelCase=0.0 , _lowerCamelCase=0.1 , _lowerCamelCase="gelu" , _lowerCamelCase=False , _lowerCamelCase=True , _lowerCamelCase=0.0_2 , _lowerCamelCase=1e-5 , _lowerCamelCase=True , _lowerCamelCase=None , _lowerCamelCase=True , _lowerCamelCase=1_0 , _lowerCamelCase=8 , _lowerCamelCase=["stage1", "stage2"] , _lowerCamelCase=[1, 2] , ): UpperCamelCase_: Tuple = parent UpperCamelCase_: Dict = batch_size UpperCamelCase_: List[str] = image_size UpperCamelCase_: Tuple = patch_size UpperCamelCase_: Tuple = num_channels UpperCamelCase_: Dict = embed_dim UpperCamelCase_: List[Any] = hidden_sizes UpperCamelCase_: List[str] = depths UpperCamelCase_: List[str] = num_heads UpperCamelCase_: Optional[int] = window_size UpperCamelCase_: Tuple = mlp_ratio UpperCamelCase_: Dict = qkv_bias UpperCamelCase_: str = hidden_dropout_prob UpperCamelCase_: Optional[Any] = attention_probs_dropout_prob UpperCamelCase_: int = drop_path_rate UpperCamelCase_: Dict = hidden_act UpperCamelCase_: List[str] = use_absolute_embeddings UpperCamelCase_: Dict = patch_norm UpperCamelCase_: Optional[Any] = layer_norm_eps UpperCamelCase_: List[str] = initializer_range UpperCamelCase_: List[Any] = is_training UpperCamelCase_: Optional[int] = scope UpperCamelCase_: str = use_labels UpperCamelCase_: List[str] = type_sequence_label_size UpperCamelCase_: Union[str, Any] = encoder_stride UpperCamelCase_: Dict = out_features UpperCamelCase_: str = out_indices def _a ( self ): UpperCamelCase_: int = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase_: List[Any] = None if self.use_labels: UpperCamelCase_: Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase_: Optional[Any] = self.get_config() return config, pixel_values, labels def _a ( self ): return FocalNetConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , hidden_sizes=self.hidden_sizes , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , out_features=self.out_features , out_indices=self.out_indices , ) def _a ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: Optional[int] = FocalNetModel(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() UpperCamelCase_: int = model(_lowerCamelCase ) UpperCamelCase_: int = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) UpperCamelCase_: int = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) ) def _a ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: List[str] = FocalNetBackbone(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() UpperCamelCase_: Optional[int] = model(_lowerCamelCase ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.image_size, 8, 8] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[:-1] ) # verify backbone works with out_features=None UpperCamelCase_: int = None UpperCamelCase_: List[Any] = FocalNetBackbone(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() UpperCamelCase_: Any = model(_lowerCamelCase ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.image_size * 2, 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def _a ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: Tuple = FocalNetForMaskedImageModeling(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() UpperCamelCase_: Any = model(_lowerCamelCase ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images UpperCamelCase_: List[Any] = 1 UpperCamelCase_: Dict = FocalNetForMaskedImageModeling(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() UpperCamelCase_: Optional[int] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) UpperCamelCase_: Union[str, Any] = model(_lowerCamelCase ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def _a ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: Tuple = self.type_sequence_label_size UpperCamelCase_: List[Any] = FocalNetForImageClassification(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() UpperCamelCase_: str = model(_lowerCamelCase , labels=_lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images UpperCamelCase_: Union[str, Any] = 1 UpperCamelCase_: Dict = FocalNetForImageClassification(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() UpperCamelCase_: Dict = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) UpperCamelCase_: Union[str, Any] = model(_lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def _a ( self ): UpperCamelCase_: Dict = self.prepare_config_and_inputs() UpperCamelCase_ ,UpperCamelCase_ ,UpperCamelCase_: List[str] = config_and_inputs UpperCamelCase_: int = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class _lowerCAmelCase( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase ): """simple docstring""" a : Optional[int] =( ( FocalNetModel, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetBackbone, ) if is_torch_available() else () ) a : Any =( {'''feature-extraction''': FocalNetModel, '''image-classification''': FocalNetForImageClassification} if is_torch_available() else {} ) a : Dict =False a : Union[str, Any] =False a : Tuple =False a : Optional[int] =False a : Union[str, Any] =False def _a ( self ): UpperCamelCase_: str = FocalNetModelTester(self ) UpperCamelCase_: Tuple = ConfigTester(self , config_class=_lowerCamelCase , embed_dim=3_7 , has_text_modality=_lowerCamelCase ) def _a ( self ): self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _a ( self ): return def _a ( self ): UpperCamelCase_: Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowerCamelCase ) def _a ( self ): UpperCamelCase_: List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*_lowerCamelCase ) def _a ( self ): UpperCamelCase_: Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*_lowerCamelCase ) def _a ( self ): UpperCamelCase_: Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_lowerCamelCase ) @unittest.skip(reason='FocalNet does not use inputs_embeds' ) def _a ( self ): pass @unittest.skip(reason='FocalNet does not use feedforward chunking' ) def _a ( self ): pass def _a ( self ): UpperCamelCase_ ,UpperCamelCase_: List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes[:-1]: UpperCamelCase_: Union[str, Any] = model_class(_lowerCamelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) UpperCamelCase_: List[str] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_lowerCamelCase , nn.Linear ) ) def _a ( self ): UpperCamelCase_ ,UpperCamelCase_: Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes[:-1]: UpperCamelCase_: List[Any] = model_class(_lowerCamelCase ) UpperCamelCase_: Optional[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase_: Any = [*signature.parameters.keys()] UpperCamelCase_: List[Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] , _lowerCamelCase ) def _a ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: Tuple = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() with torch.no_grad(): UpperCamelCase_: Tuple = model(**self._prepare_for_class(_lowerCamelCase , _lowerCamelCase ) ) UpperCamelCase_: Union[str, Any] = outputs.hidden_states UpperCamelCase_: Tuple = getattr( self.model_tester , 'expected_num_hidden_layers' , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(_lowerCamelCase ) , _lowerCamelCase ) # FocalNet has a different seq_length UpperCamelCase_: Optional[Any] = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) UpperCamelCase_: int = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) UpperCamelCase_: Dict = outputs.reshaped_hidden_states self.assertEqual(len(_lowerCamelCase ) , _lowerCamelCase ) UpperCamelCase_ ,UpperCamelCase_ ,UpperCamelCase_ ,UpperCamelCase_: int = reshaped_hidden_states[0].shape UpperCamelCase_: List[str] = ( reshaped_hidden_states[0].view(_lowerCamelCase , _lowerCamelCase , height * width ).permute(0 , 2 , 1 ) ) self.assertListEqual( list(reshaped_hidden_states.shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def _a ( self ): UpperCamelCase_ ,UpperCamelCase_: Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase_: int = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes[:-1]: UpperCamelCase_: int = True self.check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCamelCase_: Optional[Any] = True self.check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def _a ( self ): UpperCamelCase_ ,UpperCamelCase_: Dict = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase_: str = 3 UpperCamelCase_: Any = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) UpperCamelCase_: int = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) UpperCamelCase_: List[Any] = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) UpperCamelCase_: str = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes[:-1]: UpperCamelCase_: Dict = True self.check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCamelCase_: Optional[Any] = True self.check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , (padded_height, padded_width) ) @slow def _a ( self ): for model_name in FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase_: List[Any] = FocalNetModel.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) def _a ( self ): UpperCamelCase_ ,UpperCamelCase_: Dict = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase_: Dict = _config_zero_init(_lowerCamelCase ) for model_class in self.all_model_classes: UpperCamelCase_: List[str] = model_class(config=_lowerCamelCase ) for name, param in model.named_parameters(): if "embeddings" not in name and param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=f'''Parameter {name} of model {model_class} seems not properly initialized''' , ) @require_vision @require_torch class _lowerCAmelCase( unittest.TestCase ): """simple docstring""" @cached_property def _a ( self ): # TODO update organization return AutoImageProcessor.from_pretrained('microsoft/focalnet-tiny' ) if is_vision_available() else None @slow def _a ( self ): UpperCamelCase_: Optional[int] = FocalNetForImageClassification.from_pretrained('microsoft/focalnet-tiny' ).to(_lowerCamelCase ) UpperCamelCase_: Optional[Any] = self.default_image_processor UpperCamelCase_: str = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) UpperCamelCase_: str = image_processor(images=_lowerCamelCase , return_tensors='pt' ).to(_lowerCamelCase ) # forward pass with torch.no_grad(): UpperCamelCase_: List[str] = model(**_lowerCamelCase ) # verify the logits UpperCamelCase_: Optional[int] = torch.Size((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , _lowerCamelCase ) UpperCamelCase_: Optional[int] = torch.tensor([0.2_1_6_6, -0.4_3_6_8, 0.2_1_9_1] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _lowerCamelCase , atol=1e-4 ) ) self.assertTrue(outputs.logits.argmax(dim=-1 ).item() , 2_8_1 ) @require_torch class _lowerCAmelCase( UpperCAmelCase_ , unittest.TestCase ): """simple docstring""" a : Optional[Any] =(FocalNetBackbone,) if is_torch_available() else () a : List[str] =FocalNetConfig a : List[str] =False def _a ( self ): UpperCamelCase_: Any = FocalNetModelTester(self )
57
0
"""simple docstring""" import argparse import re import numpy as np import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( SamConfig, SamImageProcessor, SamModel, SamProcessor, SamVisionConfig, ) lowerCAmelCase__ = { '''iou_prediction_head.layers.0''': '''iou_prediction_head.proj_in''', '''iou_prediction_head.layers.1''': '''iou_prediction_head.layers.0''', '''iou_prediction_head.layers.2''': '''iou_prediction_head.proj_out''', '''mask_decoder.output_upscaling.0''': '''mask_decoder.upscale_conv1''', '''mask_decoder.output_upscaling.1''': '''mask_decoder.upscale_layer_norm''', '''mask_decoder.output_upscaling.3''': '''mask_decoder.upscale_conv2''', '''mask_downscaling.0''': '''mask_embed.conv1''', '''mask_downscaling.1''': '''mask_embed.layer_norm1''', '''mask_downscaling.3''': '''mask_embed.conv2''', '''mask_downscaling.4''': '''mask_embed.layer_norm2''', '''mask_downscaling.6''': '''mask_embed.conv3''', '''point_embeddings''': '''point_embed''', '''pe_layer.positional_encoding_gaussian_matrix''': '''shared_embedding.positional_embedding''', '''image_encoder''': '''vision_encoder''', '''neck.0''': '''neck.conv1''', '''neck.1''': '''neck.layer_norm1''', '''neck.2''': '''neck.conv2''', '''neck.3''': '''neck.layer_norm2''', '''patch_embed.proj''': '''patch_embed.projection''', '''.norm''': '''.layer_norm''', '''blocks''': '''layers''', } def snake_case_ ( A_ : Any ): '''simple docstring''' _lowerCamelCase : Tuple = {} state_dict.pop('''pixel_mean''', A_ ) state_dict.pop('''pixel_std''', A_ ) _lowerCamelCase : List[Any] = R'''.*.output_hypernetworks_mlps.(\d+).layers.(\d+).*''' for key, value in state_dict.items(): for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items(): if key_to_modify in key: _lowerCamelCase : Dict = key.replace(A_, A_ ) if re.match(A_, A_ ): _lowerCamelCase : Union[str, Any] = int(re.match(A_, A_ ).group(2 ) ) if layer_nb == 0: _lowerCamelCase : Tuple = key.replace('''layers.0''', '''proj_in''' ) elif layer_nb == 1: _lowerCamelCase : Any = key.replace('''layers.1''', '''layers.0''' ) elif layer_nb == 2: _lowerCamelCase : Optional[int] = key.replace('''layers.2''', '''proj_out''' ) _lowerCamelCase : Optional[Any] = value _lowerCamelCase : int = model_state_dict[ '''prompt_encoder.shared_embedding.positional_embedding''' ] return model_state_dict def snake_case_ ( A_ : List[Any], A_ : int, A_ : List[Any], A_ : Union[str, Any]="ybelkada/segment-anything" ): '''simple docstring''' _lowerCamelCase : Tuple = hf_hub_download(A_, F'''checkpoints/{model_name}.pth''' ) if "sam_vit_b" in model_name: _lowerCamelCase : Union[str, Any] = SamConfig() elif "sam_vit_l" in model_name: _lowerCamelCase : Tuple = SamVisionConfig( hidden_size=10_24, num_hidden_layers=24, num_attention_heads=16, global_attn_indexes=[5, 11, 17, 23], ) _lowerCamelCase : List[Any] = SamConfig( vision_config=A_, ) elif "sam_vit_h" in model_name: _lowerCamelCase : Dict = SamVisionConfig( hidden_size=12_80, num_hidden_layers=32, num_attention_heads=16, global_attn_indexes=[7, 15, 23, 31], ) _lowerCamelCase : Any = SamConfig( vision_config=A_, ) _lowerCamelCase : List[str] = torch.load(A_, map_location='''cpu''' ) _lowerCamelCase : int = replace_keys(A_ ) _lowerCamelCase : str = SamImageProcessor() _lowerCamelCase : Tuple = SamProcessor(image_processor=A_ ) _lowerCamelCase : List[Any] = SamModel(A_ ) hf_model.load_state_dict(A_ ) _lowerCamelCase : Any = hf_model.to('''cuda''' ) _lowerCamelCase : List[str] = '''https://huggingface.co/ybelkada/segment-anything/resolve/main/assets/car.png''' _lowerCamelCase : Tuple = Image.open(requests.get(A_, stream=A_ ).raw ).convert('''RGB''' ) _lowerCamelCase : Any = [[[4_00, 6_50]]] _lowerCamelCase : Tuple = [[1]] _lowerCamelCase : Union[str, Any] = processor(images=np.array(A_ ), return_tensors='''pt''' ).to('''cuda''' ) with torch.no_grad(): _lowerCamelCase : List[str] = hf_model(**A_ ) _lowerCamelCase : Tuple = output.iou_scores.squeeze() if model_name == "sam_vit_h_4b8939": assert scores[-1].item() == 0.579890251159668 _lowerCamelCase : int = processor( images=np.array(A_ ), input_points=A_, input_labels=A_, return_tensors='''pt''' ).to('''cuda''' ) with torch.no_grad(): _lowerCamelCase : str = hf_model(**A_ ) _lowerCamelCase : List[Any] = output.iou_scores.squeeze() assert scores[-1].item() == 0.9712603092193604 _lowerCamelCase : List[str] = ((75, 2_75, 17_25, 8_50),) _lowerCamelCase : Tuple = processor(images=np.array(A_ ), input_boxes=A_, return_tensors='''pt''' ).to('''cuda''' ) with torch.no_grad(): _lowerCamelCase : List[Any] = hf_model(**A_ ) _lowerCamelCase : List[Any] = output.iou_scores.squeeze() assert scores[-1].item() == 0.8686015605926514 # Test with 2 points and 1 image. _lowerCamelCase : Dict = [[[4_00, 6_50], [8_00, 6_50]]] _lowerCamelCase : Tuple = [[1, 1]] _lowerCamelCase : List[Any] = processor( images=np.array(A_ ), input_points=A_, input_labels=A_, return_tensors='''pt''' ).to('''cuda''' ) with torch.no_grad(): _lowerCamelCase : Any = hf_model(**A_ ) _lowerCamelCase : Optional[Any] = output.iou_scores.squeeze() assert scores[-1].item() == 0.9936047792434692 if __name__ == "__main__": lowerCAmelCase__ = argparse.ArgumentParser() lowerCAmelCase__ = ['''sam_vit_b_01ec64''', '''sam_vit_h_4b8939''', '''sam_vit_l_0b3195'''] parser.add_argument( '''--model_name''', default='''sam_vit_h_4b8939''', choices=choices, type=str, help='''Path to hf config.json of model to convert''', ) parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument( '''--push_to_hub''', action='''store_true''', help='''Whether to push the model and processor to the hub after converting''', ) parser.add_argument( '''--model_hub_id''', default='''ybelkada/segment-anything''', choices=choices, type=str, help='''Path to hf config.json of model to convert''', ) lowerCAmelCase__ = parser.parse_args() convert_sam_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub, args.model_hub_id)
83
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) A_ : Tuple = { 'configuration_distilbert': [ 'DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'DistilBertConfig', 'DistilBertOnnxConfig', ], 'tokenization_distilbert': ['DistilBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : Optional[Any] = ['DistilBertTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : int = [ 'DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'DistilBertForMaskedLM', 'DistilBertForMultipleChoice', 'DistilBertForQuestionAnswering', 'DistilBertForSequenceClassification', 'DistilBertForTokenClassification', 'DistilBertModel', 'DistilBertPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : List[Any] = [ 'TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFDistilBertForMaskedLM', 'TFDistilBertForMultipleChoice', 'TFDistilBertForQuestionAnswering', 'TFDistilBertForSequenceClassification', 'TFDistilBertForTokenClassification', 'TFDistilBertMainLayer', 'TFDistilBertModel', 'TFDistilBertPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : int = [ 'FlaxDistilBertForMaskedLM', 'FlaxDistilBertForMultipleChoice', 'FlaxDistilBertForQuestionAnswering', 'FlaxDistilBertForSequenceClassification', 'FlaxDistilBertForTokenClassification', 'FlaxDistilBertModel', 'FlaxDistilBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_distilbert import ( DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DistilBertConfig, DistilBertOnnxConfig, ) from .tokenization_distilbert import DistilBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_distilbert_fast import DistilBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_distilbert import ( DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, DistilBertModel, DistilBertPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_distilbert import ( TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDistilBertForMaskedLM, TFDistilBertForMultipleChoice, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertMainLayer, TFDistilBertModel, TFDistilBertPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, FlaxDistilBertPreTrainedModel, ) else: import sys A_ : Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
57
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) UpperCAmelCase = {'''configuration_encoder_decoder''': ['''EncoderDecoderConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = ['''EncoderDecoderModel'''] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = ['''TFEncoderDecoderModel'''] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = ['''FlaxEncoderDecoderModel'''] if TYPE_CHECKING: from .configuration_encoder_decoder import EncoderDecoderConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_encoder_decoder import EncoderDecoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_encoder_decoder import TFEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_encoder_decoder import FlaxEncoderDecoderModel else: import sys UpperCAmelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
84
import os import socket from contextlib import contextmanager import torch from ..commands.config.default import write_basic_config # noqa: F401 from ..state import PartialState from .dataclasses import DistributedType from .imports import is_deepspeed_available, is_tpu_available from .transformer_engine import convert_model from .versions import is_torch_version if is_deepspeed_available(): from deepspeed import DeepSpeedEngine if is_tpu_available(check_device=False): import torch_xla.core.xla_model as xm def snake_case (UpperCAmelCase__ ) -> Union[str, Any]: if is_torch_version('<' , '2.0.0' ) or not hasattr(UpperCAmelCase__ , '_dynamo' ): return False return isinstance(UpperCAmelCase__ , torch._dynamo.eval_frame.OptimizedModule ) def snake_case (UpperCAmelCase__ , UpperCAmelCase__ = True ) -> Any: UpperCamelCase_: Optional[Any] = (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel) UpperCamelCase_: int = is_compiled_module(UpperCAmelCase__ ) if is_compiled: UpperCamelCase_: List[str] = model UpperCamelCase_: Dict = model._orig_mod if is_deepspeed_available(): options += (DeepSpeedEngine,) while isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): UpperCamelCase_: Dict = model.module if not keep_fpaa_wrapper: UpperCamelCase_: int = getattr(UpperCAmelCase__ , 'forward' ) UpperCamelCase_: List[str] = model.__dict__.pop('_original_forward' , UpperCAmelCase__ ) if original_forward is not None: while hasattr(UpperCAmelCase__ , '__wrapped__' ): UpperCamelCase_: Any = forward.__wrapped__ if forward == original_forward: break UpperCamelCase_: Optional[int] = forward if getattr(UpperCAmelCase__ , '_converted_to_transformer_engine' , UpperCAmelCase__ ): convert_model(UpperCAmelCase__ , to_transformer_engine=UpperCAmelCase__ ) if is_compiled: UpperCamelCase_: Union[str, Any] = model UpperCamelCase_: Tuple = compiled_model return model def snake_case () -> List[str]: PartialState().wait_for_everyone() def snake_case (UpperCAmelCase__ , UpperCAmelCase__ ) -> Dict: if PartialState().distributed_type == DistributedType.TPU: xm.save(UpperCAmelCase__ , UpperCAmelCase__ ) elif PartialState().local_process_index == 0: torch.save(UpperCAmelCase__ , UpperCAmelCase__ ) @contextmanager def snake_case (**UpperCAmelCase__ ) -> Any: for key, value in kwargs.items(): UpperCamelCase_: int = str(UpperCAmelCase__ ) yield for key in kwargs: if key.upper() in os.environ: del os.environ[key.upper()] def snake_case (UpperCAmelCase__ ) -> str: if not hasattr(UpperCAmelCase__ , '__qualname__' ) and not hasattr(UpperCAmelCase__ , '__name__' ): UpperCamelCase_: List[Any] = getattr(UpperCAmelCase__ , '__class__' , UpperCAmelCase__ ) if hasattr(UpperCAmelCase__ , '__qualname__' ): return obj.__qualname__ if hasattr(UpperCAmelCase__ , '__name__' ): return obj.__name__ return str(UpperCAmelCase__ ) def snake_case (UpperCAmelCase__ , UpperCAmelCase__ ) -> Any: for key, value in source.items(): if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): UpperCamelCase_: Any = destination.setdefault(UpperCAmelCase__ , {} ) merge_dicts(UpperCAmelCase__ , UpperCAmelCase__ ) else: UpperCamelCase_: str = value return destination def snake_case (UpperCAmelCase__ = None ) -> bool: if port is None: UpperCamelCase_: List[str] = 2_9_5_0_0 with socket.socket(socket.AF_INET , socket.SOCK_STREAM ) as s: return s.connect_ex(('localhost', port) ) == 0
57
0
def _a ( lowercase__ : Tuple , lowercase__ : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = [1] for i in range(2 , lowercase__ ): factorials.append(factorials[-1] * i ) assert 0 <= k < factorials[-1] * n, "k out of bounds" SCREAMING_SNAKE_CASE__ : Optional[Any] = [] SCREAMING_SNAKE_CASE__ : str = list(range(lowercase__ ) ) # Find permutation while factorials: SCREAMING_SNAKE_CASE__ : Optional[int] = factorials.pop() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = divmod(lowercase__ , lowercase__ ) permutation.append(elements[number] ) elements.remove(elements[number] ) permutation.append(elements[0] ) return permutation if __name__ == "__main__": import doctest doctest.testmod()
85
import argparse import os import pickle import sys import torch from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() # We do this to be able to load python 2 datasets pickles # See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918 A_ : Optional[Any] = data_utils.TransfoXLTokenizer A_ : Union[str, Any] = data_utils.TransfoXLCorpus A_ : Any = data_utils A_ : Optional[Any] = data_utils def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) -> List[str]: if transfo_xl_dataset_file: # Convert a pre-processed corpus (see original TensorFlow repo) with open(UpperCAmelCase__ , 'rb' ) as fp: UpperCamelCase_: Union[str, Any] = pickle.load(UpperCAmelCase__ , encoding='latin1' ) # Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term) UpperCamelCase_: Any = pytorch_dump_folder_path + '/' + VOCAB_FILES_NAMES['pretrained_vocab_file'] print(F'''Save vocabulary to {pytorch_vocab_dump_path}''' ) UpperCamelCase_: Union[str, Any] = corpus.vocab.__dict__ torch.save(UpperCAmelCase__ , UpperCAmelCase__ ) UpperCamelCase_: str = corpus.__dict__ corpus_dict_no_vocab.pop('vocab' , UpperCAmelCase__ ) UpperCamelCase_: str = pytorch_dump_folder_path + '/' + CORPUS_NAME print(F'''Save dataset to {pytorch_dataset_dump_path}''' ) torch.save(UpperCAmelCase__ , UpperCAmelCase__ ) if tf_checkpoint_path: # Convert a pre-trained TensorFlow model UpperCamelCase_: Any = os.path.abspath(UpperCAmelCase__ ) UpperCamelCase_: Dict = os.path.abspath(UpperCAmelCase__ ) print(F'''Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.''' ) # Initialise PyTorch model if transfo_xl_config_file == "": UpperCamelCase_: List[str] = TransfoXLConfig() else: UpperCamelCase_: Optional[int] = TransfoXLConfig.from_json_file(UpperCAmelCase__ ) print(F'''Building PyTorch model from configuration: {config}''' ) UpperCamelCase_: Union[str, Any] = TransfoXLLMHeadModel(UpperCAmelCase__ ) UpperCamelCase_: Tuple = load_tf_weights_in_transfo_xl(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) # Save pytorch-model UpperCamelCase_: str = os.path.join(UpperCAmelCase__ , UpperCAmelCase__ ) UpperCamelCase_: Union[str, Any] = os.path.join(UpperCAmelCase__ , UpperCAmelCase__ ) print(F'''Save PyTorch model to {os.path.abspath(UpperCAmelCase__ )}''' ) torch.save(model.state_dict() , UpperCAmelCase__ ) print(F'''Save configuration file to {os.path.abspath(UpperCAmelCase__ )}''' ) with open(UpperCAmelCase__ , 'w' , encoding='utf-8' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": A_ : int = argparse.ArgumentParser() parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the folder to store the PyTorch model or dataset/vocab.', ) parser.add_argument( '--tf_checkpoint_path', default='', type=str, help='An optional path to a TensorFlow checkpoint path to be converted.', ) parser.add_argument( '--transfo_xl_config_file', default='', type=str, help=( 'An optional config json file corresponding to the pre-trained BERT model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--transfo_xl_dataset_file', default='', type=str, help='An optional dataset file to be converted in a vocabulary.', ) A_ : Tuple = parser.parse_args() convert_transfo_xl_checkpoint_to_pytorch( args.tf_checkpoint_path, args.transfo_xl_config_file, args.pytorch_dump_folder_path, args.transfo_xl_dataset_file, )
57
0
from .imports import is_tqdm_available if is_tqdm_available(): from tqdm.auto import tqdm as _tqdm from ..state import PartialState def __snake_case ( __UpperCamelCase : bool = True ,*__UpperCamelCase : Tuple ,**__UpperCamelCase : Dict ): """simple docstring""" if not is_tqdm_available(): raise ImportError("Accelerate's `tqdm` module requires `tqdm` to be installed. Please run `pip install tqdm`." ) A_ = False if main_process_only: A_ = PartialState().local_process_index == 0 return _tqdm(*__UpperCamelCase ,**__UpperCamelCase ,disable=__UpperCamelCase )
86
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL A_ : List[str] = logging.get_logger(__name__) def snake_case (UpperCAmelCase__ , UpperCAmelCase__ ) -> Union[str, Any]: UpperCamelCase_: Tuple = b.T UpperCamelCase_: Tuple = np.sum(np.square(UpperCAmelCase__ ) , axis=1 ) UpperCamelCase_: Optional[Any] = np.sum(np.square(UpperCAmelCase__ ) , axis=0 ) UpperCamelCase_: Optional[int] = np.matmul(UpperCAmelCase__ , UpperCAmelCase__ ) UpperCamelCase_: List[Any] = aa[:, None] - 2 * ab + ba[None, :] return d def snake_case (UpperCAmelCase__ , UpperCAmelCase__ ) -> Optional[Any]: UpperCamelCase_: List[str] = x.reshape(-1 , 3 ) UpperCamelCase_: Union[str, Any] = squared_euclidean_distance(UpperCAmelCase__ , UpperCAmelCase__ ) return np.argmin(UpperCAmelCase__ , axis=1 ) class _lowerCAmelCase( UpperCAmelCase_ ): """simple docstring""" a : Any =['''pixel_values'''] def __init__( self , _lowerCamelCase = None , _lowerCamelCase = True , _lowerCamelCase = None , _lowerCamelCase = PILImageResampling.BILINEAR , _lowerCamelCase = True , _lowerCamelCase = True , **_lowerCamelCase , ): super().__init__(**_lowerCamelCase ) UpperCamelCase_: List[str] = size if size is not None else {'height': 2_5_6, 'width': 2_5_6} UpperCamelCase_: str = get_size_dict(_lowerCamelCase ) UpperCamelCase_: Any = np.array(_lowerCamelCase ) if clusters is not None else None UpperCamelCase_: Optional[int] = do_resize UpperCamelCase_: List[Any] = size UpperCamelCase_: Optional[int] = resample UpperCamelCase_: str = do_normalize UpperCamelCase_: str = do_color_quantize def _a ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = PILImageResampling.BILINEAR , _lowerCamelCase = None , **_lowerCamelCase , ): UpperCamelCase_: Any = get_size_dict(_lowerCamelCase ) if "height" not in size or "width" not in size: raise ValueError(f'''Size dictionary must contain both height and width keys. Got {size.keys()}''' ) return resize( _lowerCamelCase , size=(size['height'], size['width']) , resample=_lowerCamelCase , data_format=_lowerCamelCase , **_lowerCamelCase ) def _a ( self , _lowerCamelCase , _lowerCamelCase = None , ): UpperCamelCase_: Optional[Any] = rescale(image=_lowerCamelCase , scale=1 / 1_2_7.5 , data_format=_lowerCamelCase ) UpperCamelCase_: Optional[Any] = image - 1 return image def _a ( self , _lowerCamelCase , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = ChannelDimension.FIRST , **_lowerCamelCase , ): UpperCamelCase_: Optional[Any] = do_resize if do_resize is not None else self.do_resize UpperCamelCase_: Tuple = size if size is not None else self.size UpperCamelCase_: Union[str, Any] = get_size_dict(_lowerCamelCase ) UpperCamelCase_: Union[str, Any] = resample if resample is not None else self.resample UpperCamelCase_: Any = do_normalize if do_normalize is not None else self.do_normalize UpperCamelCase_: str = do_color_quantize if do_color_quantize is not None else self.do_color_quantize UpperCamelCase_: Dict = clusters if clusters is not None else self.clusters UpperCamelCase_: Dict = np.array(_lowerCamelCase ) UpperCamelCase_: Optional[int] = make_list_of_images(_lowerCamelCase ) if not valid_images(_lowerCamelCase ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None or resample is None: raise ValueError('Size and resample must be specified if do_resize is True.' ) if do_color_quantize and clusters is None: raise ValueError('Clusters must be specified if do_color_quantize is True.' ) # All transformations expect numpy arrays. UpperCamelCase_: Union[str, Any] = [to_numpy_array(_lowerCamelCase ) for image in images] if do_resize: UpperCamelCase_: Union[str, Any] = [self.resize(image=_lowerCamelCase , size=_lowerCamelCase , resample=_lowerCamelCase ) for image in images] if do_normalize: UpperCamelCase_: Optional[Any] = [self.normalize(image=_lowerCamelCase ) for image in images] if do_color_quantize: UpperCamelCase_: Any = [to_channel_dimension_format(_lowerCamelCase , ChannelDimension.LAST ) for image in images] # color quantize from (batch_size, height, width, 3) to (batch_size, height, width) UpperCamelCase_: Optional[Any] = np.array(_lowerCamelCase ) UpperCamelCase_: Optional[Any] = color_quantize(_lowerCamelCase , _lowerCamelCase ).reshape(images.shape[:-1] ) # flatten to (batch_size, height*width) UpperCamelCase_: Dict = images.shape[0] UpperCamelCase_: Any = images.reshape(_lowerCamelCase , -1 ) # We need to convert back to a list of images to keep consistent behaviour across processors. UpperCamelCase_: List[Any] = list(_lowerCamelCase ) else: UpperCamelCase_: int = [to_channel_dimension_format(_lowerCamelCase , _lowerCamelCase ) for image in images] UpperCamelCase_: str = {'input_ids': images} return BatchFeature(data=_lowerCamelCase , tensor_type=_lowerCamelCase )
57
0
_lowerCamelCase : int = { """meter""": """m""", """kilometer""": """km""", """megametre""": """Mm""", """gigametre""": """Gm""", """terametre""": """Tm""", """petametre""": """Pm""", """exametre""": """Em""", """zettametre""": """Zm""", """yottametre""": """Ym""", } # Exponent of the factor(meter) _lowerCamelCase : Union[str, Any] = { """m""": 0, """km""": 3, """Mm""": 6, """Gm""": 9, """Tm""": 12, """Pm""": 15, """Em""": 18, """Zm""": 21, """Ym""": 24, } def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ ) -> float: """simple docstring""" A__ = from_type.lower().strip('''s''' ) A__ = to_type.lower().strip('''s''' ) A__ = UNIT_SYMBOL.get(lowercase_ , lowercase_ ) A__ = UNIT_SYMBOL.get(lowercase_ , lowercase_ ) if from_sanitized not in METRIC_CONVERSION: A__ = ( f"""Invalid 'from_type' value: {from_type!r}.\n""" f"""Conversion abbreviations are: {", ".join(lowercase_ )}""" ) raise ValueError(lowercase_ ) if to_sanitized not in METRIC_CONVERSION: A__ = ( f"""Invalid 'to_type' value: {to_type!r}.\n""" f"""Conversion abbreviations are: {", ".join(lowercase_ )}""" ) raise ValueError(lowercase_ ) A__ = METRIC_CONVERSION[from_sanitized] A__ = METRIC_CONVERSION[to_sanitized] A__ = 1 if from_exponent > to_exponent: A__ = from_exponent - to_exponent else: A__ = -(to_exponent - from_exponent) return value * pow(10 , lowercase_ ) if __name__ == "__main__": from doctest import testmod testmod()
87
import numpy # List of input, output pairs A_ : Any = ( ((5, 2, 3), 15), ((6, 5, 9), 25), ((11, 12, 13), 41), ((1, 1, 1), 8), ((11, 12, 13), 41), ) A_ : List[Any] = (((515, 22, 13), 555), ((61, 35, 49), 150)) A_ : Any = [2, 4, 1, 5] A_ : List[Any] = len(train_data) A_ : List[Any] = 0.009 def snake_case (UpperCAmelCase__ , UpperCAmelCase__="train" ) -> Optional[int]: return calculate_hypothesis_value(UpperCAmelCase__ , UpperCAmelCase__ ) - output( UpperCAmelCase__ , UpperCAmelCase__ ) def snake_case (UpperCAmelCase__ ) -> Optional[Any]: UpperCamelCase_: Optional[Any] = 0 for i in range(len(UpperCAmelCase__ ) - 1 ): hyp_val += data_input_tuple[i] * parameter_vector[i + 1] hyp_val += parameter_vector[0] return hyp_val def snake_case (UpperCAmelCase__ , UpperCAmelCase__ ) -> List[Any]: if data_set == "train": return train_data[example_no][1] elif data_set == "test": return test_data[example_no][1] return None def snake_case (UpperCAmelCase__ , UpperCAmelCase__ ) -> Optional[Any]: if data_set == "train": return _hypothesis_value(train_data[example_no][0] ) elif data_set == "test": return _hypothesis_value(test_data[example_no][0] ) return None def snake_case (UpperCAmelCase__ , UpperCAmelCase__=m ) -> Optional[Any]: UpperCamelCase_: Any = 0 for i in range(UpperCAmelCase__ ): if index == -1: summation_value += _error(UpperCAmelCase__ ) else: summation_value += _error(UpperCAmelCase__ ) * train_data[i][0][index] return summation_value def snake_case (UpperCAmelCase__ ) -> Optional[Any]: UpperCamelCase_: Optional[int] = summation_of_cost_derivative(UpperCAmelCase__ , UpperCAmelCase__ ) / m return cost_derivative_value def snake_case () -> Union[str, Any]: global parameter_vector # Tune these values to set a tolerance value for predicted output UpperCamelCase_: str = 0.00_0002 UpperCamelCase_: Any = 0 UpperCamelCase_: int = 0 while True: j += 1 UpperCamelCase_: int = [0, 0, 0, 0] for i in range(0 , len(UpperCAmelCase__ ) ): UpperCamelCase_: Any = get_cost_derivative(i - 1 ) UpperCamelCase_: Optional[int] = ( parameter_vector[i] - LEARNING_RATE * cost_derivative ) if numpy.allclose( UpperCAmelCase__ , UpperCAmelCase__ , atol=UpperCAmelCase__ , rtol=UpperCAmelCase__ , ): break UpperCamelCase_: Optional[int] = temp_parameter_vector print(('Number of iterations:', j) ) def snake_case () -> int: for i in range(len(UpperCAmelCase__ ) ): print(('Actual output value:', output(UpperCAmelCase__ , 'test' )) ) print(('Hypothesis output:', calculate_hypothesis_value(UpperCAmelCase__ , 'test' )) ) if __name__ == "__main__": run_gradient_descent() print('\nTesting gradient descent for a linear hypothesis function.\n') test_gradient_descent()
57
0
"""simple docstring""" from __future__ import annotations import random import unittest from transformers import TransfoXLConfig, 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 from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST, TFTransfoXLForSequenceClassification, TFTransfoXLLMHeadModel, TFTransfoXLModel, ) class lowercase__ : def __init__( self , SCREAMING_SNAKE_CASE , ) -> Dict: _lowerCamelCase : Union[str, Any] = parent _lowerCamelCase : str = 13 _lowerCamelCase : Union[str, Any] = 7 _lowerCamelCase : Optional[int] = 30 _lowerCamelCase : Optional[int] = self.seq_length + self.mem_len _lowerCamelCase : Dict = 15 _lowerCamelCase : int = True _lowerCamelCase : Union[str, Any] = True _lowerCamelCase : List[Any] = 99 _lowerCamelCase : Tuple = [10, 50, 80] _lowerCamelCase : Tuple = 32 _lowerCamelCase : int = 32 _lowerCamelCase : Optional[Any] = 4 _lowerCamelCase : Optional[Any] = 8 _lowerCamelCase : List[Any] = 128 _lowerCamelCase : Dict = 2 _lowerCamelCase : str = 2 _lowerCamelCase : Any = None _lowerCamelCase : Union[str, Any] = 1 _lowerCamelCase : int = 0 _lowerCamelCase : Tuple = 3 _lowerCamelCase : str = self.vocab_size - 1 _lowerCamelCase : str = 0.01 def UpperCamelCase_ ( self) -> Optional[Any]: _lowerCamelCase : Any = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) _lowerCamelCase : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) _lowerCamelCase : Dict = None if self.use_labels: _lowerCamelCase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) _lowerCamelCase : Optional[Any] = TransfoXLConfig( vocab_size=self.vocab_size , mem_len=self.mem_len , clamp_len=self.clamp_len , cutoffs=self.cutoffs , d_model=self.hidden_size , d_embed=self.d_embed , n_head=self.num_attention_heads , d_head=self.d_head , d_inner=self.d_inner , div_val=self.div_val , n_layer=self.num_hidden_layers , eos_token_id=self.eos_token_id , pad_token_id=self.vocab_size - 1 , init_range=self.init_range , num_labels=self.num_labels , ) return (config, input_ids_a, input_ids_a, lm_labels) def UpperCamelCase_ ( self) -> int: random.seed(self.seed) tf.random.set_seed(self.seed) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> Any: _lowerCamelCase : str = TFTransfoXLModel(SCREAMING_SNAKE_CASE) _lowerCamelCase , _lowerCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE).to_tuple() _lowerCamelCase : int = {"""input_ids""": input_ids_a, """mems""": mems_a} _lowerCamelCase , _lowerCamelCase : Optional[Any] = model(SCREAMING_SNAKE_CASE).to_tuple() self.parent.assertEqual(hidden_states_a.shape , (self.batch_size, self.seq_length, self.hidden_size)) self.parent.assertEqual(hidden_states_a.shape , (self.batch_size, self.seq_length, self.hidden_size)) self.parent.assertListEqual( [mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , ) self.parent.assertListEqual( [mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , ) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> Tuple: _lowerCamelCase : str = TFTransfoXLLMHeadModel(SCREAMING_SNAKE_CASE) _lowerCamelCase , _lowerCamelCase : Optional[Any] = model(SCREAMING_SNAKE_CASE).to_tuple() _lowerCamelCase : Tuple = {"""input_ids""": input_ids_a, """labels""": lm_labels} _lowerCamelCase , _lowerCamelCase : Tuple = model(SCREAMING_SNAKE_CASE).to_tuple() _lowerCamelCase , _lowerCamelCase : int = model([input_ids_a, mems_a]).to_tuple() _lowerCamelCase : Optional[Any] = {"""input_ids""": input_ids_a, """mems""": mems_a, """labels""": lm_labels} _lowerCamelCase , _lowerCamelCase : Optional[int] = model(SCREAMING_SNAKE_CASE).to_tuple() self.parent.assertEqual(lm_logits_a.shape , (self.batch_size, self.seq_length, self.vocab_size)) self.parent.assertListEqual( [mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , ) self.parent.assertEqual(lm_logits_a.shape , (self.batch_size, self.seq_length, self.vocab_size)) self.parent.assertListEqual( [mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , ) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> List[str]: _lowerCamelCase : Tuple = TFTransfoXLForSequenceClassification(SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = model(SCREAMING_SNAKE_CASE) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def UpperCamelCase_ ( self) -> List[Any]: _lowerCamelCase : str = self.prepare_config_and_inputs() ((_lowerCamelCase) , (_lowerCamelCase) , (_lowerCamelCase) , (_lowerCamelCase)) : int = config_and_inputs _lowerCamelCase : Optional[Any] = {"""input_ids""": input_ids_a} return config, inputs_dict @require_tf class lowercase__ ( A_ ,A_ ,unittest.TestCase ): __UpperCAmelCase = ( (TFTransfoXLModel, TFTransfoXLLMHeadModel, TFTransfoXLForSequenceClassification) if is_tf_available() else () ) __UpperCAmelCase = () if is_tf_available() else () __UpperCAmelCase = ( { '''feature-extraction''': TFTransfoXLModel, '''text-classification''': TFTransfoXLForSequenceClassification, '''text-generation''': TFTransfoXLLMHeadModel, '''zero-shot''': TFTransfoXLForSequenceClassification, } if is_tf_available() else {} ) # TODO: add this test when TFTransfoXLLMHead has a linear output layer implemented __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> Optional[Any]: if pipeline_test_casse_name == "TextGenerationPipelineTests": # Get `ValueError: AttributeError: 'NoneType' object has no attribute 'new_ones'` or `AssertionError`. # `TransfoXLConfig` was never used in pipeline tests: cannot create a simple # tokenizer. return True return False def UpperCamelCase_ ( self) -> Any: _lowerCamelCase : List[str] = TFTransfoXLModelTester(self) _lowerCamelCase : Any = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , d_embed=37) def UpperCamelCase_ ( self) -> Any: self.config_tester.run_common_tests() def UpperCamelCase_ ( self) -> Optional[Any]: self.model_tester.set_seed() _lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_model(*SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Tuple: self.model_tester.set_seed() _lowerCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_lm_head(*SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> List[Any]: _lowerCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_for_sequence_classification(*SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> str: _lowerCamelCase , _lowerCamelCase : int = self.model_tester.prepare_config_and_inputs_for_common() _lowerCamelCase : Any = [TFTransfoXLForSequenceClassification] for model_class in self.all_model_classes: _lowerCamelCase : str = model_class(SCREAMING_SNAKE_CASE) assert isinstance(model.get_input_embeddings() , tf.keras.layers.Layer) if model_class in list_other_models_with_output_ebd: _lowerCamelCase : Union[str, Any] = model.get_output_embeddings() assert isinstance(SCREAMING_SNAKE_CASE , tf.keras.layers.Layer) _lowerCamelCase : Tuple = model.get_bias() assert name is None else: _lowerCamelCase : Dict = model.get_output_embeddings() assert x is None _lowerCamelCase : List[str] = model.get_bias() assert name is None def UpperCamelCase_ ( self) -> Dict: # TODO JP: Make TransfoXL XLA compliant pass @slow def UpperCamelCase_ ( self) -> int: for model_name in TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCamelCase : Any = TFTransfoXLModel.from_pretrained(SCREAMING_SNAKE_CASE) self.assertIsNotNone(SCREAMING_SNAKE_CASE) @unittest.skip(reason="""This model doesn't play well with fit() due to not returning a single loss.""") def UpperCamelCase_ ( self) -> Any: pass @require_tf class lowercase__ ( unittest.TestCase ): @unittest.skip("""Skip test until #12651 is resolved.""") @slow def UpperCamelCase_ ( self) -> List[Any]: _lowerCamelCase : Optional[int] = TFTransfoXLLMHeadModel.from_pretrained("""transfo-xl-wt103""") # fmt: off _lowerCamelCase : int = tf.convert_to_tensor([[33,1297,2,1,1009,4,1109,1_1739,4762,358,5,25,245,22,1706,17,2_0098,5,3215,21,37,1110,3,13,1041,4,24,603,490,2,7_1477,2_0098,10_4447,2,2_0961,1,2604,4,1,329,3,6224,831,1_6002,2,8,603,7_8967,2_9546,23,803,20,25,416,5,8,232,4,277,6,1855,4601,3,2_9546,54,8,3609,5,5_7211,49,4,1,277,18,8,1755,1_5691,3,341,25,416,693,4_2573,71,17,401,94,31,1_7919,2,2_9546,7873,18,1,435,23,1_1011,755,5,5167,3,7983,98,84,2,2_9546,3267,8,3609,4,1,4865,1075,2,6087,71,6,346,8,5854,3,2_9546,824,1400,1868,2,19,160,2,311,8,5496,2,2_0920,17,25,1_5097,3,24,24,0]] , dtype=tf.intaa) # noqa: E231 # fmt: on # In 1991 , the remains of Russian Tsar Nicholas II and his family # ( except for Alexei and Maria ) are discovered . # The voice of Nicholas's young son , Tsarevich Alexei Nikolaevich , narrates the # remainder of the story . 1883 Western Siberia , # a young Grigori Rasputin is asked by his father and a group of men to perform magic . # Rasputin has a vision and denounces one of the men as a horse thief . Although his # father initially slaps him for making such an accusation , Rasputin watches as the # man is chased outside and beaten . Twenty years later , Rasputin sees a vision of # the Virgin Mary , prompting him to become a priest . Rasputin quickly becomes famous , # with people , even a bishop , begging for his blessing . <eod> </s> <eos> # fmt: off _lowerCamelCase : List[str] = [33,1297,2,1,1009,4,1109,1_1739,4762,358,5,25,245,22,1706,17,2_0098,5,3215,21,37,1110,3,13,1041,4,24,603,490,2,7_1477,2_0098,10_4447,2,2_0961,1,2604,4,1,329,3,6224,831,1_6002,2,8,603,7_8967,2_9546,23,803,20,25,416,5,8,232,4,277,6,1855,4601,3,2_9546,54,8,3609,5,5_7211,49,4,1,277,18,8,1755,1_5691,3,341,25,416,693,4_2573,71,17,401,94,31,1_7919,2,2_9546,7873,18,1,435,23,1_1011,755,5,5167,3,7983,98,84,2,2_9546,3267,8,3609,4,1,4865,1075,2,6087,71,6,346,8,5854,3,2_9546,824,1400,1868,2,19,160,2,311,8,5496,2,2_0920,17,25,1_5097,3,24,24,0,33,1,1857,2,1,1009,4,1109,1_1739,4762,358,5,25,245,28,1110,3,13,1041,4,24,603,490,2,7_1477,2_0098,10_4447,2,2_0961,1,2604,4,1,329,3,0] # noqa: E231 # fmt: on # In 1991, the remains of Russian Tsar Nicholas II and his family ( # except for Alexei and Maria ) are discovered. The voice of young son, # Tsarevich Alexei Nikolaevich, narrates the remainder of the story. # 1883 Western Siberia, a young Grigori Rasputin is asked by his father # and a group of men to perform magic. Rasputin has a vision and # denounces one of the men as a horse thief. Although his father initially # slaps him for making such an accusation, Rasputin watches as the man # is chased outside and beaten. Twenty years later, Rasputin sees a vision # of the Virgin Mary, prompting him to become a priest. # Rasputin quickly becomes famous, with people, even a bishop, begging for # his blessing. <unk> <unk> <eos> In the 1990s, the remains of Russian Tsar # Nicholas II and his family were discovered. The voice of <unk> young son, # Tsarevich Alexei Nikolaevich, narrates the remainder of the story.<eos> _lowerCamelCase : Optional[int] = model.generate(SCREAMING_SNAKE_CASE , max_length=200 , do_sample=SCREAMING_SNAKE_CASE) self.assertListEqual(output_ids[0].numpy().tolist() , SCREAMING_SNAKE_CASE)
88
from ...utils import ( OptionalDependencyNotAvailable, is_flax_available, is_torch_available, is_transformers_available, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .multicontrolnet import MultiControlNetModel from .pipeline_controlnet import StableDiffusionControlNetPipeline from .pipeline_controlnet_imgaimg import StableDiffusionControlNetImgaImgPipeline from .pipeline_controlnet_inpaint import StableDiffusionControlNetInpaintPipeline if is_transformers_available() and is_flax_available(): from .pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline
57
0
import gc import unittest import numpy as np import torch from diffusers import StableDiffusionKDiffusionPipeline from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() @slow @require_torch_gpu class _lowerCamelCase( unittest.TestCase ): def UpperCamelCase ( self) -> Tuple: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase ( self) -> Union[str, Any]: """simple docstring""" _lowercase : Any = StableDiffusionKDiffusionPipeline.from_pretrained('CompVis/stable-diffusion-v1-4') _lowercase : Optional[Any] = sd_pipe.to(lowerCamelCase) sd_pipe.set_progress_bar_config(disable=lowerCamelCase) sd_pipe.set_scheduler('sample_euler') _lowercase : str = 'A painting of a squirrel eating a burger' _lowercase : int = torch.manual_seed(0) _lowercase : int = sd_pipe([prompt], generator=lowerCamelCase, guidance_scale=9.0, num_inference_steps=20, output_type='np') _lowercase : Union[str, Any] = output.images _lowercase : Optional[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 5_12, 5_12, 3) _lowercase : Dict = np.array([0.0_4_4_7, 0.0_4_9_2, 0.0_4_6_8, 0.0_4_0_8, 0.0_3_8_3, 0.0_4_0_8, 0.0_3_5_4, 0.0_3_8_0, 0.0_3_3_9]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-2 def UpperCamelCase ( self) -> Dict: """simple docstring""" _lowercase : int = StableDiffusionKDiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-1-base') _lowercase : Optional[int] = sd_pipe.to(lowerCamelCase) sd_pipe.set_progress_bar_config(disable=lowerCamelCase) sd_pipe.set_scheduler('sample_euler') _lowercase : Any = 'A painting of a squirrel eating a burger' _lowercase : Any = torch.manual_seed(0) _lowercase : Union[str, Any] = sd_pipe([prompt], generator=lowerCamelCase, guidance_scale=9.0, num_inference_steps=20, output_type='np') _lowercase : List[str] = output.images _lowercase : str = image[0, -3:, -3:, -1] assert image.shape == (1, 5_12, 5_12, 3) _lowercase : Tuple = np.array([0.1_2_3_7, 0.1_3_2_0, 0.1_4_3_8, 0.1_3_5_9, 0.1_3_9_0, 0.1_1_3_2, 0.1_2_7_7, 0.1_1_7_5, 0.1_1_1_2]) assert np.abs(image_slice.flatten() - expected_slice).max() < 5E-1 def UpperCamelCase ( self) -> Tuple: """simple docstring""" _lowercase : Any = StableDiffusionKDiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-1-base') _lowercase : List[str] = sd_pipe.to(lowerCamelCase) sd_pipe.set_progress_bar_config(disable=lowerCamelCase) sd_pipe.set_scheduler('sample_dpmpp_2m') _lowercase : Optional[Any] = 'A painting of a squirrel eating a burger' _lowercase : Optional[Any] = torch.manual_seed(0) _lowercase : Union[str, Any] = sd_pipe( [prompt], generator=lowerCamelCase, guidance_scale=7.5, num_inference_steps=15, output_type='np', use_karras_sigmas=lowerCamelCase, ) _lowercase : List[Any] = output.images _lowercase : Tuple = image[0, -3:, -3:, -1] assert image.shape == (1, 5_12, 5_12, 3) _lowercase : Dict = np.array( [0.1_1_3_8_1_6_8_9, 0.1_2_1_1_2_9_2_1, 0.1_3_8_9_4_5_7, 0.1_2_5_4_9_6_0_6, 0.1_2_4_4_9_6_4, 0.1_0_8_3_1_5_1_7, 0.1_1_5_6_2_8_6_6, 0.1_0_8_6_7_8_1_6, 0.1_0_4_9_9_0_4_8]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-2
89
from __future__ import annotations import unittest from transformers import AutoTokenizer, PegasusConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFPegasusForConditionalGeneration, TFPegasusModel @require_tf class _lowerCAmelCase: """simple docstring""" a : int =PegasusConfig a : List[str] ={} a : Optional[int] ='''gelu''' def __init__( self , _lowerCamelCase , _lowerCamelCase=1_3 , _lowerCamelCase=7 , _lowerCamelCase=True , _lowerCamelCase=False , _lowerCamelCase=9_9 , _lowerCamelCase=3_2 , _lowerCamelCase=2 , _lowerCamelCase=4 , _lowerCamelCase=3_7 , _lowerCamelCase=0.1 , _lowerCamelCase=0.1 , _lowerCamelCase=4_0 , _lowerCamelCase=2 , _lowerCamelCase=1 , _lowerCamelCase=0 , ): UpperCamelCase_: List[Any] = parent UpperCamelCase_: Dict = batch_size UpperCamelCase_: List[str] = seq_length UpperCamelCase_: List[str] = is_training UpperCamelCase_: Any = use_labels UpperCamelCase_: Optional[Any] = vocab_size UpperCamelCase_: Tuple = hidden_size UpperCamelCase_: List[Any] = num_hidden_layers UpperCamelCase_: Any = num_attention_heads UpperCamelCase_: Optional[Any] = intermediate_size UpperCamelCase_: Optional[int] = hidden_dropout_prob UpperCamelCase_: int = attention_probs_dropout_prob UpperCamelCase_: Union[str, Any] = max_position_embeddings UpperCamelCase_: Dict = eos_token_id UpperCamelCase_: Union[str, Any] = pad_token_id UpperCamelCase_: List[Any] = bos_token_id def _a ( self ): UpperCamelCase_: Union[str, Any] = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) UpperCamelCase_: int = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) UpperCamelCase_: List[str] = tf.concat([input_ids, eos_tensor] , axis=1 ) UpperCamelCase_: Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase_: Tuple = 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 , ) UpperCamelCase_: Optional[Any] = prepare_pegasus_inputs_dict(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) return config, inputs_dict def _a ( self , _lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: Optional[Any] = TFPegasusModel(config=_lowerCamelCase ).get_decoder() UpperCamelCase_: Optional[int] = inputs_dict['input_ids'] UpperCamelCase_: Optional[int] = input_ids[:1, :] UpperCamelCase_: int = inputs_dict['attention_mask'][:1, :] UpperCamelCase_: Optional[int] = inputs_dict['head_mask'] UpperCamelCase_: Optional[int] = 1 # first forward pass UpperCamelCase_: Union[str, Any] = model(_lowerCamelCase , attention_mask=_lowerCamelCase , head_mask=_lowerCamelCase , use_cache=_lowerCamelCase ) UpperCamelCase_ ,UpperCamelCase_: int = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids UpperCamelCase_: int = ids_tensor((self.batch_size, 3) , config.vocab_size ) UpperCamelCase_: List[Any] = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and UpperCamelCase_: Union[str, Any] = tf.concat([input_ids, next_tokens] , axis=-1 ) UpperCamelCase_: int = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) UpperCamelCase_: Any = model(_lowerCamelCase , attention_mask=_lowerCamelCase )[0] UpperCamelCase_: int = model(_lowerCamelCase , attention_mask=_lowerCamelCase , past_key_values=_lowerCamelCase )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice UpperCamelCase_: Optional[int] = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) UpperCamelCase_: Any = output_from_no_past[:, -3:, random_slice_idx] UpperCamelCase_: Union[str, Any] = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(_lowerCamelCase , _lowerCamelCase , rtol=1e-3 ) def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__=None , UpperCAmelCase__=None , UpperCAmelCase__=None , UpperCAmelCase__=None , UpperCAmelCase__=None , ) -> str: if attention_mask is None: UpperCamelCase_: Optional[Any] = tf.cast(tf.math.not_equal(UpperCAmelCase__ , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: UpperCamelCase_: int = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: UpperCamelCase_: str = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: UpperCamelCase_: Any = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: UpperCamelCase_: int = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class _lowerCAmelCase( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase ): """simple docstring""" a : Tuple =(TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else () a : int =(TFPegasusForConditionalGeneration,) if is_tf_available() else () a : Tuple =( { '''conversational''': TFPegasusForConditionalGeneration, '''feature-extraction''': TFPegasusModel, '''summarization''': TFPegasusForConditionalGeneration, '''text2text-generation''': TFPegasusForConditionalGeneration, '''translation''': TFPegasusForConditionalGeneration, } if is_tf_available() else {} ) a : List[str] =True a : List[str] =False a : Tuple =False def _a ( self ): UpperCamelCase_: Dict = TFPegasusModelTester(self ) UpperCamelCase_: Any = ConfigTester(self , config_class=_lowerCamelCase ) def _a ( self ): self.config_tester.run_common_tests() def _a ( self ): UpperCamelCase_: Any = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*_lowerCamelCase ) @require_sentencepiece @require_tokenizers @require_tf class _lowerCAmelCase( unittest.TestCase ): """simple docstring""" a : Dict =[ ''' 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!" ''', ] a : int =[ '''California\'s largest electricity provider has cut power to hundreds of thousands of customers in an effort to''' ''' reduce the risk of wildfires.''', '''N-Dubz have revealed they\'re "grateful" to have been nominated for four Mobo Awards.''', ] # differs slightly from pytorch, likely due to numerical differences in linear layers a : Union[str, Any] ='''google/pegasus-xsum''' @cached_property def _a ( self ): return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def _a ( self ): UpperCamelCase_: Optional[Any] = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def _a ( self , **_lowerCamelCase ): UpperCamelCase_: Dict = self.translate_src_text(**_lowerCamelCase ) assert self.expected_text == generated_words def _a ( self , **_lowerCamelCase ): UpperCamelCase_: Union[str, Any] = self.tokenizer(self.src_text , **_lowerCamelCase , padding=_lowerCamelCase , return_tensors='tf' ) UpperCamelCase_: Any = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=_lowerCamelCase , ) UpperCamelCase_: str = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=_lowerCamelCase ) return generated_words @slow def _a ( self ): self._assert_generated_batch_equal_expected()
57
0
'''simple docstring''' from __future__ import annotations def _snake_case ( A ) -> list[int]: lowerCAmelCase__ = 2 lowerCAmelCase__ = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(A ) if n > 1: factors.append(A ) return factors if __name__ == "__main__": import doctest doctest.testmod()
90
import unittest import numpy as np def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ = None , ) -> np.ndarray: UpperCamelCase_: str = np.shape(UpperCAmelCase__ ) UpperCamelCase_: str = np.shape(UpperCAmelCase__ ) UpperCamelCase_: List[Any] = np.shape(UpperCAmelCase__ ) if shape_a[0] != shape_b[0]: UpperCamelCase_: Any = ( 'Expected the same number of rows for A and B. ' F'''Instead found A of size {shape_a} and B of size {shape_b}''' ) raise ValueError(UpperCAmelCase__ ) if shape_b[1] != shape_c[1]: UpperCamelCase_: int = ( 'Expected the same number of columns for B and C. ' F'''Instead found B of size {shape_b} and C of size {shape_c}''' ) raise ValueError(UpperCAmelCase__ ) UpperCamelCase_: Dict = pseudo_inv if a_inv is None: try: UpperCamelCase_: Optional[Any] = np.linalg.inv(UpperCAmelCase__ ) except np.linalg.LinAlgError: raise ValueError( 'Input matrix A is not invertible. Cannot compute Schur complement.' ) return mat_c - mat_b.T @ a_inv @ mat_b class _lowerCAmelCase( unittest.TestCase ): """simple docstring""" def _a ( self ): UpperCamelCase_: Any = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) UpperCamelCase_: Dict = np.array([[0, 3], [3, 0], [2, 3]] ) UpperCamelCase_: Tuple = np.array([[2, 1], [6, 3]] ) UpperCamelCase_: Tuple = schur_complement(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) UpperCamelCase_: Optional[Any] = np.block([[a, b], [b.T, c]] ) UpperCamelCase_: List[str] = np.linalg.det(_lowerCamelCase ) UpperCamelCase_: List[str] = np.linalg.det(_lowerCamelCase ) UpperCamelCase_: Dict = np.linalg.det(_lowerCamelCase ) self.assertAlmostEqual(_lowerCamelCase , det_a * det_s ) def _a ( self ): UpperCamelCase_: int = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) UpperCamelCase_: List[str] = np.array([[0, 3], [3, 0], [2, 3]] ) UpperCamelCase_: List[str] = np.array([[2, 1], [6, 3]] ) with self.assertRaises(_lowerCamelCase ): schur_complement(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def _a ( self ): UpperCamelCase_: List[Any] = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) UpperCamelCase_: str = np.array([[0, 3], [3, 0], [2, 3]] ) UpperCamelCase_: List[Any] = np.array([[2, 1, 3], [6, 3, 5]] ) with self.assertRaises(_lowerCamelCase ): schur_complement(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) if __name__ == "__main__": import doctest doctest.testmod() unittest.main()
57
0
"""simple docstring""" import argparse import gdown import numpy as np import torch from huggingface_hub import hf_hub_download from transformers import ( CLIPTokenizer, CLIPTokenizerFast, VideoMAEImageProcessor, XCLIPConfig, XCLIPModel, XCLIPProcessor, XCLIPTextConfig, XCLIPVisionConfig, ) def _snake_case ( snake_case__ : Optional[Any] , snake_case__ : str ): A = XCLIPTextConfig() # derive patch size from model name A = model_name.find('patch' ) A = int(model_name[start_idx + len('patch' ) : start_idx + len('patch' ) + 2] ) A = XCLIPVisionConfig(patch_size=snake_case__ , num_frames=snake_case__ ) if "large" in model_name: A = 768 A = 3072 A = 12 A = 1024 A = 4096 A = 16 A = 24 A = 768 A = 3072 if model_name == "xclip-large-patch14-16-frames": A = 336 A = XCLIPConfig.from_text_vision_configs(snake_case__ , snake_case__ ) if "large" in model_name: A = 768 return config def _snake_case ( snake_case__ : Optional[Any] ): # text encoder if name == "token_embedding.weight": A = name.replace('token_embedding.weight' , 'text_model.embeddings.token_embedding.weight' ) if name == "positional_embedding": A = name.replace('positional_embedding' , 'text_model.embeddings.position_embedding.weight' ) if "ln_1" in name: A = name.replace('ln_1' , 'layer_norm1' ) if "ln_2" in name: A = name.replace('ln_2' , 'layer_norm2' ) if "c_fc" in name: A = name.replace('c_fc' , 'fc1' ) if "c_proj" in name: A = name.replace('c_proj' , 'fc2' ) if name.startswith('transformer.resblocks' ): A = name.replace('transformer.resblocks' , 'text_model.encoder.layers' ) if "attn.out_proj" in name and "message" not in name: A = name.replace('attn.out_proj' , 'self_attn.out_proj' ) if "ln_final" in name: A = name.replace('ln_final' , 'text_model.final_layer_norm' ) # visual encoder if name == "visual.class_embedding": A = name.replace('visual.class_embedding' , 'vision_model.embeddings.class_embedding' ) if name == "visual.positional_embedding": A = name.replace('visual.positional_embedding' , 'vision_model.embeddings.position_embedding.weight' ) if name.startswith('visual.transformer.resblocks' ): A = name.replace('visual.transformer.resblocks' , 'vision_model.encoder.layers' ) if "visual.conv1" in name: A = name.replace('visual.conv1' , 'vision_model.embeddings.patch_embedding' ) if "visual.ln_pre" in name: A = name.replace('visual.ln_pre' , 'vision_model.pre_layernorm' ) if "visual.ln_post" in name: A = name.replace('visual.ln_post' , 'vision_model.post_layernorm' ) if "visual.proj" in name: A = name.replace('visual.proj' , 'visual_projection.weight' ) if "text_projection" in name: A = name.replace('text_projection' , 'text_projection.weight' ) # things on top if "prompts_visual_proj" in name: A = name.replace('prompts_visual_proj' , 'prompts_visual_projection' ) if "prompts_visual_ln" in name: A = name.replace('prompts_visual_ln' , 'prompts_visual_layernorm' ) # mit if name == "mit.positional_embedding": A = name.replace('positional' , 'position' ) if name.startswith('mit.resblocks' ): A = name.replace('mit.resblocks' , 'mit.encoder.layers' ) # prompts generator if name.startswith('prompts_generator.norm' ): A = name.replace('prompts_generator.norm' , 'prompts_generator.layernorm' ) return name def _snake_case ( snake_case__ : Dict , snake_case__ : str ): for key in orig_state_dict.copy().keys(): A = orig_state_dict.pop(snake_case__ ) if "attn.in_proj" in key: A = key.split('.' ) if key.startswith('visual' ): A = key_split[3] A = config.vision_config.hidden_size if "message_attn" in key: if "weight" in key: A = val[ :dim, : ] A = val[ dim : dim * 2, : ] A = val[ -dim:, : ] else: A = val[ :dim ] A = val[ dim : dim * 2 ] A = val[ -dim: ] else: if "weight" in key: A = val[ :dim, : ] A = val[ dim : dim * 2, : ] A = val[ -dim:, : ] else: A = val[:dim] A = val[ dim : dim * 2 ] A = val[-dim:] elif key.startswith('mit' ): A = key_split[2] A = config.vision_config.mit_hidden_size if "weight" in key: A = val[:dim, :] A = val[dim : dim * 2, :] A = val[-dim:, :] else: A = val[:dim] A = val[dim : dim * 2] A = val[-dim:] else: A = key_split[2] A = config.text_config.hidden_size if "weight" in key: A = val[:dim, :] A = val[ dim : dim * 2, : ] A = val[-dim:, :] else: A = val[:dim] A = val[ dim : dim * 2 ] A = val[-dim:] else: A = rename_key(snake_case__ ) if new_key_name in ["visual_projection.weight", "text_projection.weight"]: A = val.T A = val return orig_state_dict def _snake_case ( snake_case__ : Union[str, Any] ): if num_frames == 8: A = 'eating_spaghetti_8_frames.npy' elif num_frames == 16: A = 'eating_spaghetti.npy' elif num_frames == 32: A = 'eating_spaghetti_32_frames.npy' A = hf_hub_download( repo_id='hf-internal-testing/spaghetti-video' , filename=snake_case__ , repo_type='dataset' , ) A = np.load(snake_case__ ) return list(snake_case__ ) def _snake_case ( snake_case__ : Dict , snake_case__ : List[str]=None , snake_case__ : Tuple=False ): A = { # fully supervised kinetics-400 checkpoints 'xclip-base-patch32': 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_32_8.pth', 'xclip-base-patch32-16-frames': ( 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_32_16.pth' ), 'xclip-base-patch16': 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_16_8.pth', 'xclip-base-patch16-16-frames': ( 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_16_16.pth' ), 'xclip-large-patch14': 'https://drive.google.com/u/0/uc?id=1NUOImq0o5DlQTST17iIP3vG7DgmHQuCx&amp;export=download&amp;confirm=t&amp;uuid=b26caedc-88e2-473e-830a-9d158b653cdb', 'xclip-large-patch14-16-frames': 'https://drive.google.com/u/0/uc?id=1FOYgnJc097OJ4lGwtRCCydQyVPJEOH7d&amp;export=download&amp;confirm=t&amp;uuid=538fa810-e671-4050-b385-9a623f89804f', # fully supervised kinetics-600 checkpoints 'xclip-base-patch16-kinetics-600': ( 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k600_16_8.pth' ), 'xclip-base-patch16-kinetics-600-16-frames': ( 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k600_16_16.pth' ), 'xclip-large-patch14-kinetics-600': 'https://drive.google.com/u/0/uc?id=1FV8C1INuM91sLAN4ImjzePLIlpMSihwV&amp;export=download&amp;confirm=t&amp;uuid=141d4977-4a65-44ae-864f-4b0c19f838be', # few shot 'xclip-base-patch16-hmdb-2-shot': ( 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_2.pth' ), 'xclip-base-patch16-hmdb-4-shot': ( 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_4.pth' ), 'xclip-base-patch16-hmdb-8-shot': ( 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_8.pth' ), 'xclip-base-patch16-hmdb-16-shot': ( 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_16.pth' ), 'xclip-base-patch16-ucf-2-shot': ( 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_2.pth' ), 'xclip-base-patch16-ucf-4-shot': ( 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_4.pth' ), 'xclip-base-patch16-ucf-8-shot': ( 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_8.pth' ), 'xclip-base-patch16-ucf-16-shot': ( 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_16.pth' ), # zero shot 'xclip-base-patch16-zero-shot': 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/zero.pth', } A = model_to_url[model_name] A = 8 if "16-frames" in model_name: A = 16 elif "shot" in model_name: A = 32 A = get_xclip_config(snake_case__ , snake_case__ ) A = XCLIPModel(snake_case__ ) model.eval() if "drive" in checkpoint_url: A = 'pytorch_model.bin' gdown.cached_download(snake_case__ , snake_case__ , quiet=snake_case__ ) A = torch.load(snake_case__ , map_location='cpu' )['model'] else: A = torch.hub.load_state_dict_from_url(snake_case__ )['model'] A = convert_state_dict(snake_case__ , snake_case__ ) A = XCLIPModel(snake_case__ ) A , A = model.load_state_dict(snake_case__ , strict=snake_case__ ) assert missing_keys == ["text_model.embeddings.position_ids", "vision_model.embeddings.position_ids"] model.eval() A = 336 if model_name == 'xclip-large-patch14-16-frames' else 224 A = VideoMAEImageProcessor(size=snake_case__ ) A = CLIPTokenizer.from_pretrained('openai/clip-vit-base-patch32' ) A = CLIPTokenizerFast.from_pretrained('openai/clip-vit-base-patch32' ) A = XCLIPProcessor(image_processor=snake_case__ , tokenizer=snake_case__ ) A = prepare_video(snake_case__ ) A = processor( text=['playing sports', 'eating spaghetti', 'go shopping'] , videos=snake_case__ , return_tensors='pt' , padding=snake_case__ ) print('Shape of pixel values:' , inputs.pixel_values.shape ) with torch.no_grad(): A = model(**snake_case__ ) # Verify outputs A = outputs.logits_per_video A = logits_per_video.softmax(dim=1 ) print('Probs:' , snake_case__ ) # kinetics-400 if model_name == "xclip-base-patch32": A = torch.tensor([[0.0019, 0.9951, 0.0030]] ) elif model_name == "xclip-base-patch32-16-frames": A = torch.tensor([[7.09_99e-04, 9.98_83e-01, 4.55_80e-04]] ) elif model_name == "xclip-base-patch16": A = torch.tensor([[0.0083, 0.9681, 0.0236]] ) elif model_name == "xclip-base-patch16-16-frames": A = torch.tensor([[7.69_37e-04, 9.97_28e-01, 1.94_73e-03]] ) elif model_name == "xclip-large-patch14": A = torch.tensor([[0.0062, 0.9864, 0.0075]] ) elif model_name == "xclip-large-patch14-16-frames": A = torch.tensor([[3.38_77e-04, 9.99_37e-01, 2.88_88e-04]] ) # kinetics-600 elif model_name == "xclip-base-patch16-kinetics-600": A = torch.tensor([[0.0555, 0.8914, 0.0531]] ) elif model_name == "xclip-base-patch16-kinetics-600-16-frames": A = torch.tensor([[3.85_54e-04, 9.99_29e-01, 3.27_54e-04]] ) elif model_name == "xclip-large-patch14-kinetics-600": A = torch.tensor([[0.0036, 0.9920, 0.0045]] ) # few shot elif model_name == "xclip-base-patch16-hmdb-2-shot": A = torch.tensor([[7.18_90e-06, 9.99_94e-01, 5.65_59e-05]] ) elif model_name == "xclip-base-patch16-hmdb-4-shot": A = torch.tensor([[1.03_20e-05, 9.99_93e-01, 6.24_35e-05]] ) elif model_name == "xclip-base-patch16-hmdb-8-shot": A = torch.tensor([[4.13_77e-06, 9.99_90e-01, 9.83_86e-05]] ) elif model_name == "xclip-base-patch16-hmdb-16-shot": A = torch.tensor([[4.13_47e-05, 9.99_62e-01, 3.34_11e-04]] ) elif model_name == "xclip-base-patch16-ucf-2-shot": A = torch.tensor([[8.58_57e-05, 9.99_28e-01, 6.32_91e-04]] ) elif model_name == "xclip-base-patch16-ucf-4-shot": A = torch.tensor([[8.58_57e-05, 9.99_28e-01, 6.32_91e-04]] ) elif model_name == "xclip-base-patch16-ucf-8-shot": A = torch.tensor([[0.0027, 0.9904, 0.0070]] ) elif model_name == "xclip-base-patch16-ucf-16-shot": A = torch.tensor([[9.82_19e-04, 9.95_93e-01, 3.08_63e-03]] ) # zero shot elif model_name == "xclip-base-patch16-zero-shot": A = torch.tensor([[3.50_82e-04, 9.97_85e-01, 1.79_66e-03]] ) else: raise ValueError(F'Model name {model_name} not supported' ) assert torch.allclose(snake_case__ , snake_case__ , atol=1e-3 ) print('Looks ok!' ) if pytorch_dump_folder_path is not None: print(F'Saving model {model_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(snake_case__ ) if push_to_hub: print('Pushing model, processor and slow tokenizer files to the hub...' ) model.push_to_hub(snake_case__ , organization='nielsr' ) processor.push_to_hub(snake_case__ , organization='nielsr' ) slow_tokenizer.push_to_hub(snake_case__ , organization='nielsr' ) if __name__ == "__main__": _lowercase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default='''xclip-base-patch32''', type=str, help='''Name of the model.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) parser.add_argument( '''--push_to_hub''', action='''store_true''', help='''Whether or not to push the converted model to the 🤗 hub.''' ) _lowercase = parser.parse_args() convert_xclip_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
91
import argparse import json import os from collections import OrderedDict import torch from transformers import LukeConfig, LukeForMaskedLM, MLukeTokenizer, XLMRobertaTokenizer from transformers.tokenization_utils_base import AddedToken @torch.no_grad() def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) -> int: # Load configuration defined in the metadata file with open(UpperCAmelCase__ ) as metadata_file: UpperCamelCase_: Tuple = json.load(UpperCAmelCase__ ) UpperCamelCase_: List[str] = LukeConfig(use_entity_aware_attention=UpperCAmelCase__ , **metadata['model_config'] ) # Load in the weights from the checkpoint_path UpperCamelCase_: Optional[int] = torch.load(UpperCAmelCase__ , map_location='cpu' )['module'] # Load the entity vocab file UpperCamelCase_: Any = load_original_entity_vocab(UpperCAmelCase__ ) # add an entry for [MASK2] UpperCamelCase_: List[str] = max(entity_vocab.values() ) + 1 config.entity_vocab_size += 1 UpperCamelCase_: Union[str, Any] = XLMRobertaTokenizer.from_pretrained(metadata['model_config']['bert_model_name'] ) # Add special tokens to the token vocabulary for downstream tasks UpperCamelCase_: Any = AddedToken('<ent>' , lstrip=UpperCAmelCase__ , rstrip=UpperCAmelCase__ ) UpperCamelCase_: Optional[Any] = AddedToken('<ent2>' , lstrip=UpperCAmelCase__ , rstrip=UpperCAmelCase__ ) 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(UpperCAmelCase__ ) with open(os.path.join(UpperCAmelCase__ , 'tokenizer_config.json' ) , 'r' ) as f: UpperCamelCase_: Union[str, Any] = json.load(UpperCAmelCase__ ) UpperCamelCase_: str = 'MLukeTokenizer' with open(os.path.join(UpperCAmelCase__ , 'tokenizer_config.json' ) , 'w' ) as f: json.dump(UpperCAmelCase__ , UpperCAmelCase__ ) with open(os.path.join(UpperCAmelCase__ , MLukeTokenizer.vocab_files_names['entity_vocab_file'] ) , 'w' ) as f: json.dump(UpperCAmelCase__ , UpperCAmelCase__ ) UpperCamelCase_: Optional[Any] = MLukeTokenizer.from_pretrained(UpperCAmelCase__ ) # Initialize the embeddings of the special tokens UpperCamelCase_: Any = tokenizer.convert_tokens_to_ids(['@'] )[0] UpperCamelCase_: List[str] = tokenizer.convert_tokens_to_ids(['#'] )[0] UpperCamelCase_: Tuple = state_dict['embeddings.word_embeddings.weight'] UpperCamelCase_: int = word_emb[ent_init_index].unsqueeze(0 ) UpperCamelCase_: Any = word_emb[enta_init_index].unsqueeze(0 ) UpperCamelCase_: str = torch.cat([word_emb, ent_emb, enta_emb] ) # add special tokens for 'entity_predictions.bias' for bias_name in ["lm_head.decoder.bias", "lm_head.bias"]: UpperCamelCase_: Union[str, Any] = state_dict[bias_name] UpperCamelCase_: Tuple = decoder_bias[ent_init_index].unsqueeze(0 ) UpperCamelCase_: Any = decoder_bias[enta_init_index].unsqueeze(0 ) UpperCamelCase_: Optional[Any] = torch.cat([decoder_bias, ent_decoder_bias, enta_decoder_bias] ) # 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_: List[Any] = F'''encoder.layer.{layer_index}.attention.self.''' UpperCamelCase_: str = state_dict[prefix + matrix_name] UpperCamelCase_: Dict = state_dict[prefix + matrix_name] UpperCamelCase_: Dict = state_dict[prefix + matrix_name] # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks UpperCamelCase_: List[str] = state_dict['entity_embeddings.entity_embeddings.weight'] UpperCamelCase_: int = entity_emb[entity_vocab['[MASK]']].unsqueeze(0 ) UpperCamelCase_: Tuple = torch.cat([entity_emb, entity_mask_emb] ) # add [MASK2] for 'entity_predictions.bias' UpperCamelCase_: Optional[Any] = state_dict['entity_predictions.bias'] UpperCamelCase_: List[str] = entity_prediction_bias[entity_vocab['[MASK]']].unsqueeze(0 ) UpperCamelCase_: List[Any] = torch.cat([entity_prediction_bias, entity_mask_bias] ) UpperCamelCase_: List[Any] = LukeForMaskedLM(config=UpperCAmelCase__ ).eval() state_dict.pop('entity_predictions.decoder.weight' ) state_dict.pop('lm_head.decoder.weight' ) state_dict.pop('lm_head.decoder.bias' ) UpperCamelCase_: Optional[Any] = OrderedDict() for key, value in state_dict.items(): if not (key.startswith('lm_head' ) or key.startswith('entity_predictions' )): UpperCamelCase_: Union[str, Any] = state_dict[key] else: UpperCamelCase_: Dict = state_dict[key] UpperCamelCase_ ,UpperCamelCase_: Optional[int] = model.load_state_dict(UpperCAmelCase__ , strict=UpperCAmelCase__ ) if set(UpperCAmelCase__ ) != {"luke.embeddings.position_ids"}: raise ValueError(F'''Unexpected unexpected_keys: {unexpected_keys}''' ) if set(UpperCAmelCase__ ) != { "lm_head.decoder.weight", "lm_head.decoder.bias", "entity_predictions.decoder.weight", }: raise ValueError(F'''Unexpected missing_keys: {missing_keys}''' ) model.tie_weights() assert (model.luke.embeddings.word_embeddings.weight == model.lm_head.decoder.weight).all() assert (model.luke.entity_embeddings.entity_embeddings.weight == model.entity_predictions.decoder.weight).all() # Check outputs UpperCamelCase_: Optional[int] = MLukeTokenizer.from_pretrained(UpperCAmelCase__ , task='entity_classification' ) UpperCamelCase_: Tuple = 'ISO 639-3 uses the code fas for the dialects spoken across Iran and アフガニスタン (Afghanistan).' UpperCamelCase_: Optional[int] = (0, 9) UpperCamelCase_: Union[str, Any] = tokenizer(UpperCAmelCase__ , entity_spans=[span] , return_tensors='pt' ) UpperCamelCase_: str = model(**UpperCAmelCase__ ) # Verify word hidden states if model_size == "large": raise NotImplementedError else: # base UpperCamelCase_: int = torch.Size((1, 3_3, 7_6_8) ) UpperCamelCase_: Tuple = torch.tensor([[0.0892, 0.0596, -0.2819], [0.0134, 0.1199, 0.0573], [-0.0169, 0.0927, 0.0644]] ) 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] , UpperCAmelCase__ , atol=1E-4 ): raise ValueError # Verify entity hidden states if model_size == "large": raise NotImplementedError else: # base UpperCamelCase_: Dict = torch.Size((1, 1, 7_6_8) ) UpperCamelCase_: Tuple = torch.tensor([[-0.1482, 0.0609, 0.0322]] ) 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] , UpperCAmelCase__ , atol=1E-4 ): raise ValueError # Verify masked word/entity prediction UpperCamelCase_: str = MLukeTokenizer.from_pretrained(UpperCAmelCase__ ) UpperCamelCase_: int = 'Tokyo is the capital of <mask>.' UpperCamelCase_: Dict = (2_4, 3_0) UpperCamelCase_: int = tokenizer(UpperCAmelCase__ , entity_spans=[span] , return_tensors='pt' ) UpperCamelCase_: Dict = model(**UpperCAmelCase__ ) UpperCamelCase_: Optional[int] = encoding['input_ids'][0].tolist() UpperCamelCase_: List[Any] = input_ids.index(tokenizer.convert_tokens_to_ids('<mask>' ) ) UpperCamelCase_: Any = outputs.logits[0][mask_position_id].argmax(dim=-1 ) assert "Japan" == tokenizer.decode(UpperCAmelCase__ ) UpperCamelCase_: Union[str, Any] = outputs.entity_logits[0][0].argmax().item() UpperCamelCase_: Optional[Any] = [ entity for entity, entity_id in tokenizer.entity_vocab.items() if entity_id == predicted_entity_id ] assert [e for e in multilingual_predicted_entities if e.startswith('en:' )][0] == "en:Japan" # Finally, save our PyTorch model and tokenizer print('Saving PyTorch model to {}'.format(UpperCAmelCase__ ) ) model.save_pretrained(UpperCAmelCase__ ) def snake_case (UpperCAmelCase__ ) -> int: UpperCamelCase_: Optional[Any] = ['[MASK]', '[PAD]', '[UNK]'] UpperCamelCase_: Any = [json.loads(UpperCAmelCase__ ) for line in open(UpperCAmelCase__ )] UpperCamelCase_: Tuple = {} for entry in data: UpperCamelCase_: Optional[int] = entry['id'] for entity_name, language in entry["entities"]: if entity_name in SPECIAL_TOKENS: UpperCamelCase_: Union[str, Any] = entity_id break UpperCamelCase_: Dict = F'''{language}:{entity_name}''' UpperCamelCase_: Optional[int] = entity_id return new_mapping if __name__ == "__main__": A_ : Tuple = 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_ : List[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, )
57
0
'''simple docstring''' import numpy as np import datasets UpperCamelCase_ = """ Compute the Mahalanobis Distance Mahalonobis distance is the distance between a point and a distribution. And not between two distinct points. It is effectively a multivariate equivalent of the Euclidean distance. It was introduced by Prof. P. C. Mahalanobis in 1936 and has been used in various statistical applications ever since [source: https://www.machinelearningplus.com/statistics/mahalanobis-distance/] """ UpperCamelCase_ = """\ @article{de2000mahalanobis, title={The mahalanobis distance}, author={De Maesschalck, Roy and Jouan-Rimbaud, Delphine and Massart, D{\'e}sir{\'e} L}, journal={Chemometrics and intelligent laboratory systems}, volume={50}, number={1}, pages={1--18}, year={2000}, publisher={Elsevier} } """ UpperCamelCase_ = """ Args: X: List of datapoints to be compared with the `reference_distribution`. reference_distribution: List of datapoints from the reference distribution we want to compare to. Returns: mahalanobis: The Mahalonobis distance for each datapoint in `X`. Examples: >>> mahalanobis_metric = datasets.load_metric(\"mahalanobis\") >>> results = mahalanobis_metric.compute(reference_distribution=[[0, 1], [1, 0]], X=[[0, 1]]) >>> print(results) {'mahalanobis': array([0.5])} """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __SCREAMING_SNAKE_CASE ( datasets.Metric ): def lowerCamelCase_ ( self : Any ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''X''': datasets.Sequence(datasets.Value('''float''' , id='''sequence''' ) , id='''X''' ), } ) , ) def lowerCamelCase_ ( self : str , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : str ): '''simple docstring''' # convert to numpy arrays lowercase : Optional[Any] =np.array(UpperCAmelCase__ ) lowercase : List[str] =np.array(UpperCAmelCase__ ) # Assert that arrays are 2D if len(X.shape ) != 2: raise ValueError('''Expected `X` to be a 2D vector''' ) if len(reference_distribution.shape ) != 2: raise ValueError('''Expected `reference_distribution` to be a 2D vector''' ) if reference_distribution.shape[0] < 2: raise ValueError( '''Expected `reference_distribution` to be a 2D vector with more than one element in the first dimension''' ) # Get mahalanobis distance for each prediction lowercase : Tuple =X - np.mean(UpperCAmelCase__ ) lowercase : int =np.cov(reference_distribution.T ) try: lowercase : Dict =np.linalg.inv(UpperCAmelCase__ ) except np.linalg.LinAlgError: lowercase : Optional[Any] =np.linalg.pinv(UpperCAmelCase__ ) lowercase : int =np.dot(UpperCAmelCase__ , UpperCAmelCase__ ) lowercase : Any =np.dot(UpperCAmelCase__ , X_minus_mu.T ).diagonal() return {"mahalanobis": mahal_dist}
92
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A_ : Optional[Any] = logging.get_logger(__name__) A_ : Optional[Any] = { 'distilbert-base-uncased': 'https://huggingface.co/distilbert-base-uncased/resolve/main/config.json', 'distilbert-base-uncased-distilled-squad': ( 'https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/config.json' ), 'distilbert-base-cased': 'https://huggingface.co/distilbert-base-cased/resolve/main/config.json', 'distilbert-base-cased-distilled-squad': ( 'https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/config.json' ), 'distilbert-base-german-cased': 'https://huggingface.co/distilbert-base-german-cased/resolve/main/config.json', 'distilbert-base-multilingual-cased': ( 'https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/config.json' ), 'distilbert-base-uncased-finetuned-sst-2-english': ( 'https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-english/resolve/main/config.json' ), } class _lowerCAmelCase( UpperCAmelCase_ ): """simple docstring""" a : Dict ='''distilbert''' a : List[str] ={ '''hidden_size''': '''dim''', '''num_attention_heads''': '''n_heads''', '''num_hidden_layers''': '''n_layers''', } def __init__( self , _lowerCamelCase=3_0_5_2_2 , _lowerCamelCase=5_1_2 , _lowerCamelCase=False , _lowerCamelCase=6 , _lowerCamelCase=1_2 , _lowerCamelCase=7_6_8 , _lowerCamelCase=4 * 7_6_8 , _lowerCamelCase=0.1 , _lowerCamelCase=0.1 , _lowerCamelCase="gelu" , _lowerCamelCase=0.0_2 , _lowerCamelCase=0.1 , _lowerCamelCase=0.2 , _lowerCamelCase=0 , **_lowerCamelCase , ): UpperCamelCase_: Tuple = vocab_size UpperCamelCase_: str = max_position_embeddings UpperCamelCase_: Optional[int] = sinusoidal_pos_embds UpperCamelCase_: Union[str, Any] = n_layers UpperCamelCase_: Optional[int] = n_heads UpperCamelCase_: int = dim UpperCamelCase_: Tuple = hidden_dim UpperCamelCase_: Any = dropout UpperCamelCase_: Optional[Any] = attention_dropout UpperCamelCase_: List[str] = activation UpperCamelCase_: Optional[Any] = initializer_range UpperCamelCase_: Optional[Any] = qa_dropout UpperCamelCase_: List[str] = seq_classif_dropout super().__init__(**_lowerCamelCase , pad_token_id=_lowerCamelCase ) class _lowerCAmelCase( UpperCAmelCase_ ): """simple docstring""" @property def _a ( self ): if self.task == "multiple-choice": UpperCamelCase_: Any = {0: 'batch', 1: 'choice', 2: 'sequence'} else: UpperCamelCase_: List[Any] = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
57
0
"""simple docstring""" import json import os import unittest from transformers import DebertaTokenizer, DebertaTokenizerFast from transformers.models.deberta.tokenization_deberta import VOCAB_FILES_NAMES from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class _lowerCAmelCase ( a , unittest.TestCase ): """simple docstring""" __magic_name__ :Optional[Any] = DebertaTokenizer __magic_name__ :str = True __magic_name__ :Dict = DebertaTokenizerFast def snake_case ( self ): '''simple docstring''' super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt lowerCAmelCase__ :Dict = [ 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', '\u0120', '\u0120l', '\u0120n', '\u0120lo', '\u0120low', 'er', '\u0120lowest', '\u0120newer', '\u0120wider', '[UNK]', ] lowerCAmelCase__ :Union[str, Any] = dict(zip(__UpperCAmelCase , range(len(__UpperCAmelCase ) ) ) ) lowerCAmelCase__ :Dict = ['#version: 0.2', '\u0120 l', '\u0120l o', '\u0120lo w', 'e r', ''] lowerCAmelCase__ :int = {'unk_token': '[UNK]'} lowerCAmelCase__ :List[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) lowerCAmelCase__ :Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(__UpperCAmelCase ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(__UpperCAmelCase ) ) def snake_case ( self , **__UpperCAmelCase ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **__UpperCAmelCase ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = 'lower newer' lowerCAmelCase__ :List[str] = 'lower newer' return input_text, output_text def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Dict = self.get_tokenizer() lowerCAmelCase__ :List[Any] = 'lower newer' lowerCAmelCase__ :Optional[int] = ['l', 'o', 'w', 'er', '\u0120', 'n', 'e', 'w', 'er'] lowerCAmelCase__ :Tuple = tokenizer.tokenize(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ :Any = tokens + [tokenizer.unk_token] lowerCAmelCase__ :str = [0, 1, 2, 1_5, 1_0, 9, 3, 2, 1_5, 1_9] self.assertListEqual(tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = self.get_tokenizer() lowerCAmelCase__ :Optional[int] = tokenizer('Hello' , 'World' ) lowerCAmelCase__ :List[Any] = [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1] self.assertListEqual(tokd['token_type_ids'] , __UpperCAmelCase ) @slow def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Any = self.tokenizer_class.from_pretrained('microsoft/deberta-base' ) lowerCAmelCase__ :Optional[Any] = tokenizer.encode('sequence builders' , add_special_tokens=__UpperCAmelCase ) lowerCAmelCase__ :str = tokenizer.encode('multi-sequence build' , add_special_tokens=__UpperCAmelCase ) lowerCAmelCase__ :List[Any] = tokenizer.encode( 'sequence builders' , add_special_tokens=__UpperCAmelCase , add_prefix_space=__UpperCAmelCase ) lowerCAmelCase__ :Any = tokenizer.encode( 'sequence builders' , 'multi-sequence build' , add_special_tokens=__UpperCAmelCase , add_prefix_space=__UpperCAmelCase ) lowerCAmelCase__ :Optional[int] = tokenizer.build_inputs_with_special_tokens(__UpperCAmelCase ) lowerCAmelCase__ :str = tokenizer.build_inputs_with_special_tokens(__UpperCAmelCase , __UpperCAmelCase ) assert encoded_sentence == encoded_text_from_decode assert encoded_pair == encoded_pair_from_decode @slow def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Any = [self.tokenizer_class] if self.test_rust_tokenizer: tokenizer_classes.append(self.rust_tokenizer_class ) for tokenizer_class in tokenizer_classes: lowerCAmelCase__ :Tuple = tokenizer_class.from_pretrained('microsoft/deberta-base' ) lowerCAmelCase__ :Optional[int] = [ 'ALBERT: A Lite BERT for Self-supervised Learning of Language Representations', 'ALBERT incorporates two parameter reduction techniques', 'The first one is a factorized embedding parameterization. By decomposing the large vocabulary' ' embedding matrix into two small matrices, we separate the size of the hidden layers from the size of' ' vocabulary embedding.', ] lowerCAmelCase__ :Optional[int] = tokenizer(__UpperCAmelCase , padding=__UpperCAmelCase ) lowerCAmelCase__ :Tuple = [tokenizer.decode(__UpperCAmelCase , skip_special_tokens=__UpperCAmelCase ) for seq in encoding['input_ids']] # fmt: off lowerCAmelCase__ :Tuple = { 'input_ids': [ [1, 2_1_1_8, 1_1_1_2_6, 5_6_5, 3_5, 8_3, 2_5_1_9_1, 1_6_3, 1_8_8_5_4, 1_3, 1_2_1_5_6, 1_2, 1_6_1_0_1, 2_5_3_7_6, 1_3_8_0_7, 9, 2_2_2_0_5, 2_7_8_9_3, 1_6_3_5, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 2_1_1_8, 1_1_1_2_6, 5_6_5, 2_4_5_3_6, 8_0, 4_3_7_9_7, 4_8_7_8, 7_3_7_3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1_3_3, 7_8, 6_5, 1_6, 1_0, 3_7_2_4, 1_5_3_8, 3_3_1_8_3, 1_1_3_0_3, 4_3_7_9_7, 1_9_3_8, 4, 8_7_0, 2_4_1_6_5, 2_9_1_0_5, 5, 7_3_9, 3_2_6_4_4, 3_3_1_8_3, 1_1_3_0_3, 3_6_1_7_3, 8_8, 8_0, 6_5_0, 7_8_2_1, 4_5_9_4_0, 6, 5_2, 2_5_5_9, 5, 1_8_3_6, 9, 5, 7_3_9_7, 1_3_1_7_1, 3_1, 5, 1_8_3_6, 9, 3_2_6_4_4, 3_3_1_8_3, 1_1_3_0_3, 4, 2] ], 'token_type_ids': [ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ], 'attention_mask': [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] ] } # fmt: on lowerCAmelCase__ :List[Any] = [ 'ALBERT: A Lite BERT for Self-supervised Learning of Language Representations', 'ALBERT incorporates two parameter reduction techniques', 'The first one is a factorized embedding parameterization. By decomposing the large vocabulary' ' embedding matrix into two small matrices, we separate the size of the hidden layers from the size of' ' vocabulary embedding.', ] self.assertDictEqual(encoding.data , __UpperCAmelCase ) for expected, decoded in zip(__UpperCAmelCase , __UpperCAmelCase ): self.assertEqual(__UpperCAmelCase , __UpperCAmelCase )
93
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A_ : int = { 'configuration_lilt': ['LILT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LiltConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : Any = [ 'LILT_PRETRAINED_MODEL_ARCHIVE_LIST', 'LiltForQuestionAnswering', 'LiltForSequenceClassification', 'LiltForTokenClassification', 'LiltModel', 'LiltPreTrainedModel', ] if TYPE_CHECKING: from .configuration_lilt import LILT_PRETRAINED_CONFIG_ARCHIVE_MAP, LiltConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_lilt import ( LILT_PRETRAINED_MODEL_ARCHIVE_LIST, LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, LiltPreTrainedModel, ) else: import sys A_ : Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
57
0
'''simple docstring''' from scipy.stats import pearsonr, spearmanr from sklearn.metrics import fa_score, matthews_corrcoef import datasets SCREAMING_SNAKE_CASE = '\\n@inproceedings{wang2019glue,\n title={{GLUE}: A Multi-Task Benchmark and Analysis Platform for Natural Language Understanding},\n author={Wang, Alex and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R.},\n note={In the Proceedings of ICLR.},\n year={2019}\n}\n' SCREAMING_SNAKE_CASE = '\\nGLUE, the General Language Understanding Evaluation benchmark\n(https://gluebenchmark.com/) is a collection of resources for training,\nevaluating, and analyzing natural language understanding systems.\n' SCREAMING_SNAKE_CASE = '\nCompute GLUE evaluation metric associated to each GLUE dataset.\nArgs:\n predictions: list of predictions to score.\n Each translation should be tokenized into a list of tokens.\n references: list of lists of references for each translation.\n Each reference should be tokenized into a list of tokens.\nReturns: depending on the GLUE subset, one or several of:\n "accuracy": Accuracy\n "f1": F1 score\n "pearson": Pearson Correlation\n "spearmanr": Spearman Correlation\n "matthews_correlation": Matthew Correlation\nExamples:\n\n >>> glue_metric = datasets.load_metric(\'glue\', \'sst2\') # \'sst2\' or any of ["mnli", "mnli_mismatched", "mnli_matched", "qnli", "rte", "wnli", "hans"]\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0}\n\n >>> glue_metric = datasets.load_metric(\'glue\', \'mrpc\') # \'mrpc\' or \'qqp\'\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0, \'f1\': 1.0}\n\n >>> glue_metric = datasets.load_metric(\'glue\', \'stsb\')\n >>> references = [0., 1., 2., 3., 4., 5.]\n >>> predictions = [0., 1., 2., 3., 4., 5.]\n >>> results = glue_metric.compute(predictions=predictions, references=references)\n >>> print({"pearson": round(results["pearson"], 2), "spearmanr": round(results["spearmanr"], 2)})\n {\'pearson\': 1.0, \'spearmanr\': 1.0}\n\n >>> glue_metric = datasets.load_metric(\'glue\', \'cola\')\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'matthews_correlation\': 1.0}\n' def lowercase_ ( __A : List[Any] , __A : List[Any] ) -> int: """simple docstring""" return float((preds == labels).mean() ) def lowercase_ ( __A : Any , __A : Union[str, Any] ) -> int: """simple docstring""" lowercase : int =simple_accuracy(__A , __A ) lowercase : Optional[int] =float(fa_score(y_true=__A , y_pred=__A ) ) return { "accuracy": acc, "f1": fa, } def lowercase_ ( __A : Any , __A : List[str] ) -> str: """simple docstring""" lowercase : Any =float(pearsonr(__A , __A )[0] ) lowercase : Optional[int] =float(spearmanr(__A , __A )[0] ) return { "pearson": pearson_corr, "spearmanr": spearman_corr, } @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCAmelCase_ ( datasets.Metric ): """simple docstring""" def A__ ( self : List[Any] ) -> Tuple: '''simple docstring''' if self.config_name not in [ "sst2", "mnli", "mnli_mismatched", "mnli_matched", "cola", "stsb", "mrpc", "qqp", "qnli", "rte", "wnli", "hans", ]: raise KeyError( '''You should supply a configuration name selected in ''' '''["sst2", "mnli", "mnli_mismatched", "mnli_matched", ''' '''"cola", "stsb", "mrpc", "qqp", "qnli", "rte", "wnli", "hans"]''' ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''int64''' if self.config_name != '''stsb''' else '''float32''' ), '''references''': datasets.Value('''int64''' if self.config_name != '''stsb''' else '''float32''' ), } ) , codebase_urls=[] , reference_urls=[] , format='''numpy''' , ) def A__ ( self : Any , UpperCAmelCase : Dict , UpperCAmelCase : Union[str, Any] ) -> Optional[int]: '''simple docstring''' if self.config_name == "cola": return {"matthews_correlation": matthews_corrcoef(UpperCAmelCase , UpperCAmelCase )} elif self.config_name == "stsb": return pearson_and_spearman(UpperCAmelCase , UpperCAmelCase ) elif self.config_name in ["mrpc", "qqp"]: return acc_and_fa(UpperCAmelCase , UpperCAmelCase ) elif self.config_name in ["sst2", "mnli", "mnli_mismatched", "mnli_matched", "qnli", "rte", "wnli", "hans"]: return {"accuracy": simple_accuracy(UpperCAmelCase , UpperCAmelCase )} else: raise KeyError( '''You should supply a configuration name selected in ''' '''["sst2", "mnli", "mnli_mismatched", "mnli_matched", ''' '''"cola", "stsb", "mrpc", "qqp", "qnli", "rte", "wnli", "hans"]''' )
94
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available A_ : List[str] = { 'configuration_roc_bert': ['ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'RoCBertConfig'], 'tokenization_roc_bert': ['RoCBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: pass try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : Union[str, Any] = [ 'ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'RoCBertForCausalLM', 'RoCBertForMaskedLM', 'RoCBertForMultipleChoice', 'RoCBertForPreTraining', 'RoCBertForQuestionAnswering', 'RoCBertForSequenceClassification', 'RoCBertForTokenClassification', 'RoCBertLayer', 'RoCBertModel', 'RoCBertPreTrainedModel', 'load_tf_weights_in_roc_bert', ] if TYPE_CHECKING: from .configuration_roc_bert import ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RoCBertConfig from .tokenization_roc_bert import RoCBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: raise OptionalDependencyNotAvailable() try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roc_bert import ( ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, RoCBertForCausalLM, RoCBertForMaskedLM, RoCBertForMultipleChoice, RoCBertForPreTraining, RoCBertForQuestionAnswering, RoCBertForSequenceClassification, RoCBertForTokenClassification, RoCBertLayer, RoCBertModel, RoCBertPreTrainedModel, load_tf_weights_in_roc_bert, ) else: import sys A_ : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
57
0
"""simple docstring""" import unittest import numpy as np from diffusers import OnnxStableDiffusionInpaintPipelineLegacy from diffusers.utils.testing_utils import ( is_onnx_available, load_image, load_numpy, nightly, require_onnxruntime, require_torch_gpu, ) if is_onnx_available(): import onnxruntime as ort @nightly @require_onnxruntime @require_torch_gpu class UpperCamelCase_ (unittest.TestCase ): @property def _SCREAMING_SNAKE_CASE ( self : int ) -> Any: return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def _SCREAMING_SNAKE_CASE ( self : Any ) -> Union[str, Any]: UpperCAmelCase_ : Optional[int] = ort.SessionOptions() UpperCAmelCase_ : int = False return options def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[int]: UpperCAmelCase_ : 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[int] = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/in_paint/red_cat_sitting_on_a_park_bench_onnx.npy" ) # using the PNDM scheduler by default UpperCAmelCase_ : Tuple = OnnxStableDiffusionInpaintPipelineLegacy.from_pretrained( "CompVis/stable-diffusion-v1-4" , revision="onnx" , safety_checker=lowerCAmelCase_ , feature_extractor=lowerCAmelCase_ , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) UpperCAmelCase_ : int = "A red cat sitting on a park bench" UpperCAmelCase_ : Any = np.random.RandomState(0 ) UpperCAmelCase_ : Optional[Any] = pipe( prompt=lowerCAmelCase_ , image=lowerCAmelCase_ , mask_image=lowerCAmelCase_ , strength=0.7_5 , guidance_scale=7.5 , num_inference_steps=15 , generator=lowerCAmelCase_ , output_type="np" , ) UpperCAmelCase_ : List[str] = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 1e-2
95
from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import BaseOutput, is_torch_available, is_transformers_available @dataclass class _lowerCAmelCase( UpperCAmelCase_ ): """simple docstring""" a : Union[List[PIL.Image.Image], np.ndarray] a : Optional[List[bool]] if is_transformers_available() and is_torch_available(): from .pipeline_semantic_stable_diffusion import SemanticStableDiffusionPipeline
57
0
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import PaddingStrategy, logging from .tokenization_realm import RealmTokenizer __lowerCamelCase = logging.get_logger(__name__) __lowerCamelCase = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} __lowerCamelCase = { 'vocab_file': { 'google/realm-cc-news-pretrained-embedder': ( 'https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/vocab.txt' ), 'google/realm-cc-news-pretrained-encoder': ( 'https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/vocab.txt' ), 'google/realm-cc-news-pretrained-scorer': ( 'https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/vocab.txt' ), 'google/realm-cc-news-pretrained-openqa': ( 'https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/vocab.txt' ), 'google/realm-orqa-nq-openqa': 'https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/vocab.txt', 'google/realm-orqa-nq-reader': 'https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/vocab.txt', 'google/realm-orqa-wq-openqa': 'https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/vocab.txt', 'google/realm-orqa-wq-reader': 'https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/vocab.txt', }, 'tokenizer_file': { 'google/realm-cc-news-pretrained-embedder': ( 'https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/tokenizer.jsont' ), 'google/realm-cc-news-pretrained-encoder': ( 'https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/tokenizer.json' ), 'google/realm-cc-news-pretrained-scorer': ( 'https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/tokenizer.json' ), 'google/realm-cc-news-pretrained-openqa': ( 'https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/tokenizer.json' ), 'google/realm-orqa-nq-openqa': ( 'https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/tokenizer.json' ), 'google/realm-orqa-nq-reader': ( 'https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/tokenizer.json' ), 'google/realm-orqa-wq-openqa': ( 'https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/tokenizer.json' ), 'google/realm-orqa-wq-reader': ( 'https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/tokenizer.json' ), }, } __lowerCamelCase = { 'google/realm-cc-news-pretrained-embedder': 5_12, 'google/realm-cc-news-pretrained-encoder': 5_12, 'google/realm-cc-news-pretrained-scorer': 5_12, 'google/realm-cc-news-pretrained-openqa': 5_12, 'google/realm-orqa-nq-openqa': 5_12, 'google/realm-orqa-nq-reader': 5_12, 'google/realm-orqa-wq-openqa': 5_12, 'google/realm-orqa-wq-reader': 5_12, } __lowerCamelCase = { 'google/realm-cc-news-pretrained-embedder': {'do_lower_case': True}, 'google/realm-cc-news-pretrained-encoder': {'do_lower_case': True}, 'google/realm-cc-news-pretrained-scorer': {'do_lower_case': True}, 'google/realm-cc-news-pretrained-openqa': {'do_lower_case': True}, 'google/realm-orqa-nq-openqa': {'do_lower_case': True}, 'google/realm-orqa-nq-reader': {'do_lower_case': True}, 'google/realm-orqa-wq-openqa': {'do_lower_case': True}, 'google/realm-orqa-wq-reader': {'do_lower_case': True}, } class __A ( SCREAMING_SNAKE_CASE_ ): UpperCAmelCase__ = VOCAB_FILES_NAMES UpperCAmelCase__ = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase__ = PRETRAINED_INIT_CONFIGURATION UpperCAmelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase__ = RealmTokenizer def __init__( self : Optional[Any] , __snake_case : Optional[int]=None , __snake_case : str=None , __snake_case : Dict=True , __snake_case : Tuple="[UNK]" , __snake_case : Any="[SEP]" , __snake_case : Tuple="[PAD]" , __snake_case : str="[CLS]" , __snake_case : Optional[int]="[MASK]" , __snake_case : str=True , __snake_case : Optional[int]=None , **__snake_case : Union[str, Any] , ) -> List[Any]: super().__init__( __snake_case , tokenizer_file=__snake_case , do_lower_case=__snake_case , unk_token=__snake_case , sep_token=__snake_case , pad_token=__snake_case , cls_token=__snake_case , mask_token=__snake_case , tokenize_chinese_chars=__snake_case , strip_accents=__snake_case , **__snake_case , ) __magic_name__: List[str] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""" , __snake_case ) != do_lower_case or normalizer_state.get("""strip_accents""" , __snake_case ) != strip_accents or normalizer_state.get("""handle_chinese_chars""" , __snake_case ) != tokenize_chinese_chars ): __magic_name__: Dict = getattr(__snake_case , normalizer_state.pop("""type""" ) ) __magic_name__: Optional[Any] = do_lower_case __magic_name__: Optional[int] = strip_accents __magic_name__: Union[str, Any] = tokenize_chinese_chars __magic_name__: Any = normalizer_class(**__snake_case ) __magic_name__: List[Any] = do_lower_case def lowerCamelCase__ ( self : str , __snake_case : int , **__snake_case : Union[str, Any] ) -> Union[str, Any]: __magic_name__: Any = PaddingStrategy.MAX_LENGTH __magic_name__: Union[str, Any] = text __magic_name__: int = kwargs.pop("""text_pair""" , __snake_case ) __magic_name__: Optional[Any] = kwargs.pop("""return_tensors""" , __snake_case ) __magic_name__: str = { """input_ids""": [], """attention_mask""": [], """token_type_ids""": [], } for idx, candidate_text in enumerate(__snake_case ): if batch_text_pair is not None: __magic_name__: Dict = batch_text_pair[idx] else: __magic_name__: Optional[Any] = None __magic_name__: Dict = super().__call__(__snake_case , __snake_case , return_tensors=__snake_case , **__snake_case ) __magic_name__: Dict = encoded_candidates.get("""input_ids""" ) __magic_name__: List[Any] = encoded_candidates.get("""attention_mask""" ) __magic_name__: int = encoded_candidates.get("""token_type_ids""" ) if encoded_input_ids is not None: output_data["input_ids"].append(__snake_case ) if encoded_attention_mask is not None: output_data["attention_mask"].append(__snake_case ) if encoded_token_type_ids is not None: output_data["token_type_ids"].append(__snake_case ) __magic_name__: str = {key: item for key, item in output_data.items() if len(__snake_case ) != 0} return BatchEncoding(__snake_case , tensor_type=__snake_case ) def lowerCamelCase__ ( self : Optional[Any] , __snake_case : Dict , __snake_case : List[Any]=None ) -> str: __magic_name__: List[Any] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def lowerCamelCase__ ( self : str , __snake_case : List[int] , __snake_case : Optional[List[int]] = None ) -> List[int]: __magic_name__: str = [self.sep_token_id] __magic_name__: Optional[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 lowerCamelCase__ ( self : str , __snake_case : str , __snake_case : Optional[str] = None ) -> Tuple[str]: __magic_name__: Optional[Any] = self._tokenizer.model.save(__snake_case , name=__snake_case ) return tuple(__snake_case )
96
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConfig, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaForCTC, WavaVecaForPreTraining, WavaVecaProcessor, logging, ) from transformers.models.wavaveca.modeling_wavaveca import WavaVecaForSequenceClassification logging.set_verbosity_info() A_ : Tuple = logging.get_logger(__name__) A_ : Optional[int] = { 'post_extract_proj': 'feature_projection.projection', 'encoder.pos_conv.0': 'encoder.pos_conv_embed.conv', 'self_attn.k_proj': 'encoder.layers.*.attention.k_proj', 'self_attn.v_proj': 'encoder.layers.*.attention.v_proj', 'self_attn.q_proj': 'encoder.layers.*.attention.q_proj', 'self_attn.out_proj': 'encoder.layers.*.attention.out_proj', 'self_attn_layer_norm': 'encoder.layers.*.layer_norm', 'fc1': 'encoder.layers.*.feed_forward.intermediate_dense', 'fc2': 'encoder.layers.*.feed_forward.output_dense', 'final_layer_norm': 'encoder.layers.*.final_layer_norm', 'encoder.layer_norm': 'encoder.layer_norm', 'adapter_layer': 'encoder.layers.*.adapter_layer', 'w2v_model.layer_norm': 'feature_projection.layer_norm', 'quantizer.weight_proj': 'quantizer.weight_proj', 'quantizer.vars': 'quantizer.codevectors', 'project_q': 'project_q', 'final_proj': 'project_hid', 'w2v_encoder.proj': 'lm_head', 'mask_emb': 'masked_spec_embed', 'pooling_layer.linear': 'projector', 'pooling_layer.projection': 'classifier', } A_ : int = [ 'lm_head', 'quantizer.weight_proj', 'quantizer.codevectors', 'project_q', 'project_hid', 'projector', 'classifier', ] def snake_case (UpperCAmelCase__ ) -> str: UpperCamelCase_: Tuple = {} with open(UpperCAmelCase__ , 'r' ) as file: for line_number, line in enumerate(UpperCAmelCase__ ): UpperCamelCase_: List[Any] = line.strip() if line: UpperCamelCase_: List[Any] = line.split() UpperCamelCase_: Optional[Any] = line_number UpperCamelCase_: Any = words[0] UpperCamelCase_: List[Any] = value return result def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) -> List[str]: for attribute in key.split('.' ): UpperCamelCase_: str = getattr(UpperCAmelCase__ , UpperCAmelCase__ ) UpperCamelCase_: str = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(UpperCAmelCase__ ): UpperCamelCase_: Any = PARAM_MAPPING[full_name.split('.' )[-1]] UpperCamelCase_: Dict = 'param' if weight_type is not None and weight_type != "param": UpperCamelCase_: Optional[Any] = getattr(UpperCAmelCase__ , UpperCAmelCase__ ).shape elif weight_type is not None and weight_type == "param": UpperCamelCase_: Optional[Any] = hf_pointer for attribute in hf_param_name.split('.' ): UpperCamelCase_: str = getattr(UpperCAmelCase__ , UpperCAmelCase__ ) UpperCamelCase_: Tuple = shape_pointer.shape # let's reduce dimension UpperCamelCase_: int = value[0] else: UpperCamelCase_: Union[str, Any] = hf_pointer.shape if hf_shape != value.shape: raise ValueError( F'''Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be''' F''' {value.shape} for {full_name}''' ) if weight_type == "weight": UpperCamelCase_: Optional[int] = value elif weight_type == "weight_g": UpperCamelCase_: Any = value elif weight_type == "weight_v": UpperCamelCase_: Union[str, Any] = value elif weight_type == "bias": UpperCamelCase_: Union[str, Any] = value elif weight_type == "param": for attribute in hf_param_name.split('.' ): UpperCamelCase_: Dict = getattr(UpperCAmelCase__ , UpperCAmelCase__ ) UpperCamelCase_: Optional[Any] = value else: UpperCamelCase_: int = value logger.info(F'''{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.''' ) def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) -> Any: UpperCamelCase_: Union[str, Any] = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(UpperCAmelCase__ ): UpperCamelCase_: Dict = PARAM_MAPPING[full_name.split('.' )[-1]] UpperCamelCase_: List[Any] = 'param' if weight_type is not None and weight_type != "param": UpperCamelCase_: List[Any] = '.'.join([key, weight_type] ) elif weight_type is not None and weight_type == "param": UpperCamelCase_: Any = '.'.join([key, hf_param_name] ) else: UpperCamelCase_: Union[str, Any] = key UpperCamelCase_: Any = value if 'lm_head' in full_key else value[0] A_ : str = { 'W_a': 'linear_1.weight', 'W_b': 'linear_2.weight', 'b_a': 'linear_1.bias', 'b_b': 'linear_2.bias', 'ln_W': 'norm.weight', 'ln_b': 'norm.bias', } def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__=None , UpperCAmelCase__=None ) -> Any: UpperCamelCase_: Optional[int] = False for key, mapped_key in MAPPING.items(): UpperCamelCase_: Tuple = 'wav2vec2.' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]: UpperCamelCase_: Optional[Any] = True if "*" in mapped_key: UpperCamelCase_: Optional[int] = name.split(UpperCAmelCase__ )[0].split('.' )[-2] UpperCamelCase_: Any = mapped_key.replace('*' , UpperCAmelCase__ ) if "weight_g" in name: UpperCamelCase_: Union[str, Any] = 'weight_g' elif "weight_v" in name: UpperCamelCase_: Dict = 'weight_v' elif "bias" in name: UpperCamelCase_: int = 'bias' elif "weight" in name: # TODO: don't match quantizer.weight_proj UpperCamelCase_: str = 'weight' else: UpperCamelCase_: Union[str, Any] = None if hf_dict is not None: rename_dict(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) else: set_recursively(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) return is_used return is_used def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) -> List[str]: UpperCamelCase_: List[Any] = [] UpperCamelCase_: Dict = fairseq_model.state_dict() UpperCamelCase_: Optional[Any] = hf_model.wavaveca.feature_extractor for name, value in fairseq_dict.items(): UpperCamelCase_: Union[str, Any] = False if "conv_layers" in name: load_conv_layer( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , hf_model.config.feat_extract_norm == 'group' , ) UpperCamelCase_: List[Any] = True else: UpperCamelCase_: Tuple = load_wavaveca_layer(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) if not is_used: unused_weights.append(UpperCAmelCase__ ) logger.warning(F'''Unused weights: {unused_weights}''' ) def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) -> Any: UpperCamelCase_: Any = full_name.split('conv_layers.' )[-1] UpperCamelCase_: int = name.split('.' ) UpperCamelCase_: int = int(items[0] ) UpperCamelCase_: Union[str, Any] = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.''' ) UpperCamelCase_: Union[str, Any] = value logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.''' ) UpperCamelCase_: int = value logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.''' ) UpperCamelCase_: Union[str, Any] = value logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.''' ) UpperCamelCase_: List[Any] = value logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) else: unused_weights.append(UpperCAmelCase__ ) @torch.no_grad() def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__=None , UpperCAmelCase__=None , UpperCAmelCase__=True , UpperCAmelCase__=False ) -> Dict: if config_path is not None: UpperCamelCase_: Tuple = WavaVecaConfig.from_pretrained(UpperCAmelCase__ ) else: UpperCamelCase_: List[str] = WavaVecaConfig() if is_seq_class: UpperCamelCase_: int = read_txt_into_dict(UpperCAmelCase__ ) UpperCamelCase_: Tuple = idalabel UpperCamelCase_: str = WavaVecaForSequenceClassification(UpperCAmelCase__ ) UpperCamelCase_: Optional[int] = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6_0_0_0 , padding_value=0 , do_normalize=UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , ) feature_extractor.save_pretrained(UpperCAmelCase__ ) elif is_finetuned: if dict_path: UpperCamelCase_: List[Any] = Dictionary.load(UpperCAmelCase__ ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq UpperCamelCase_: Dict = target_dict.pad_index UpperCamelCase_: Tuple = target_dict.bos_index UpperCamelCase_: Optional[Any] = target_dict.eos_index UpperCamelCase_: Union[str, Any] = len(target_dict.symbols ) UpperCamelCase_: int = os.path.join(UpperCAmelCase__ , 'vocab.json' ) if not os.path.isdir(UpperCAmelCase__ ): logger.error('--pytorch_dump_folder_path ({}) should be a directory'.format(UpperCAmelCase__ ) ) return os.makedirs(UpperCAmelCase__ , exist_ok=UpperCAmelCase__ ) UpperCamelCase_: str = target_dict.indices # fairseq has the <pad> and <s> switched UpperCamelCase_: List[str] = 0 UpperCamelCase_: List[Any] = 1 with open(UpperCAmelCase__ , 'w' , encoding='utf-8' ) as vocab_handle: json.dump(UpperCAmelCase__ , UpperCAmelCase__ ) UpperCamelCase_: Union[str, Any] = WavaVecaCTCTokenizer( UpperCAmelCase__ , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token='|' , do_lower_case=UpperCAmelCase__ , ) UpperCamelCase_: Any = True if config.feat_extract_norm == 'layer' else False UpperCamelCase_: Tuple = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6_0_0_0 , padding_value=0 , do_normalize=UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , ) UpperCamelCase_: Dict = WavaVecaProcessor(feature_extractor=UpperCAmelCase__ , tokenizer=UpperCAmelCase__ ) processor.save_pretrained(UpperCAmelCase__ ) UpperCamelCase_: Any = WavaVecaForCTC(UpperCAmelCase__ ) else: UpperCamelCase_: Any = WavaVecaForPreTraining(UpperCAmelCase__ ) if is_finetuned or is_seq_class: UpperCamelCase_ ,UpperCamelCase_ ,UpperCamelCase_: Dict = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] )} ) else: UpperCamelCase_: List[str] = argparse.Namespace(task='audio_pretraining' ) UpperCamelCase_: Any = fairseq.tasks.setup_task(UpperCAmelCase__ ) UpperCamelCase_ ,UpperCamelCase_ ,UpperCamelCase_: Union[str, Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=UpperCAmelCase__ ) UpperCamelCase_: str = model[0].eval() recursively_load_weights(UpperCAmelCase__ , UpperCAmelCase__ , not is_finetuned ) hf_wavavec.save_pretrained(UpperCAmelCase__ ) if __name__ == "__main__": A_ : str = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint') parser.add_argument('--dict_path', default=None, type=str, help='Path to dict of fine-tuned model') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') parser.add_argument( '--not_finetuned', action='store_true', help='Whether the model to convert is a fine-tuned model or not' ) parser.add_argument( '--is_seq_class', action='store_true', help='Whether the model to convert is a fine-tuned sequence classification model or not', ) A_ : int = parser.parse_args() A_ : str = not args.not_finetuned and not args.is_seq_class convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, is_finetuned, args.is_seq_class, )
57
0
def a ( snake_case__: list ): '''simple docstring''' lowercase_ = len(snake_case__ ) for _ in range(snake_case__ ): for i in range(_ % 2 , arr_size - 1 , 2 ): if arr[i + 1] < arr[i]: lowercase_ , lowercase_ = arr[i + 1], arr[i] return arr if __name__ == "__main__": __a = list(range(1_0, 0, -1)) print(f"Original: {arr}. Sorted: {odd_even_transposition(arr)}")
97
import inspect import os import unittest import torch import accelerate from accelerate import debug_launcher from accelerate.test_utils import ( execute_subprocess_async, require_cpu, require_huggingface_suite, require_multi_gpu, require_single_gpu, ) from accelerate.utils import patch_environment @require_huggingface_suite class _lowerCAmelCase( unittest.TestCase ): """simple docstring""" def _a ( self ): UpperCamelCase_: Optional[int] = inspect.getfile(accelerate.test_utils ) UpperCamelCase_: Dict = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ['scripts', 'external_deps', 'test_metrics.py'] ) from accelerate.test_utils.scripts.external_deps import test_metrics # noqa: F401 UpperCamelCase_: Tuple = test_metrics @require_cpu def _a ( self ): debug_launcher(self.test_metrics.main , num_processes=1 ) @require_cpu def _a ( self ): debug_launcher(self.test_metrics.main ) @require_single_gpu def _a ( self ): self.test_metrics.main() @require_multi_gpu def _a ( self ): print(f'''Found {torch.cuda.device_count()} devices.''' ) UpperCamelCase_: List[Any] = ['torchrun', f'''--nproc_per_node={torch.cuda.device_count()}''', self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(_lowerCamelCase , env=os.environ.copy() )
57
0
'''simple docstring''' import random def a__ ( lowercase : list, lowercase : Union[str, Any] ) -> tuple: """simple docstring""" _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = [], [], [] for element in data: if element < pivot: less.append(lowercase ) elif element > pivot: greater.append(lowercase ) else: equal.append(lowercase ) return less, equal, greater def a__ ( lowercase : list, lowercase : int ) -> Optional[int]: """simple docstring""" if index >= len(lowercase ) or index < 0: return None _UpperCamelCase = items[random.randint(0, len(lowercase ) - 1 )] _UpperCamelCase = 0 _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = _partition(lowercase, lowercase ) _UpperCamelCase = len(lowercase ) _UpperCamelCase = len(lowercase ) # index is the pivot if m <= index < m + count: return pivot # must be in smaller elif m > index: return quick_select(lowercase, lowercase ) # must be in larger else: return quick_select(lowercase, index - (m + count) )
98
import math class _lowerCAmelCase: """simple docstring""" def _a ( self , _lowerCamelCase , _lowerCamelCase ): UpperCamelCase_: int = 0.0 UpperCamelCase_: Tuple = 0.0 for i in range(len(_lowerCamelCase ) ): da += math.pow((sample[i] - weights[0][i]) , 2 ) da += math.pow((sample[i] - weights[1][i]) , 2 ) return 0 if da > da else 1 return 0 def _a ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): for i in range(len(_lowerCamelCase ) ): weights[j][i] += alpha * (sample[i] - weights[j][i]) return weights def snake_case () -> None: # Training Examples ( m, n ) UpperCamelCase_: List[str] = [[1, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 1, 1]] # weight initialization ( n, C ) UpperCamelCase_: List[Any] = [[0.2, 0.6, 0.5, 0.9], [0.8, 0.4, 0.7, 0.3]] # training UpperCamelCase_: Dict = SelfOrganizingMap() UpperCamelCase_: List[Any] = 3 UpperCamelCase_: List[str] = 0.5 for _ in range(UpperCAmelCase__ ): for j in range(len(UpperCAmelCase__ ) ): # training sample UpperCamelCase_: int = training_samples[j] # Compute the winning vector UpperCamelCase_: Tuple = self_organizing_map.get_winner(UpperCAmelCase__ , UpperCAmelCase__ ) # Update the winning vector UpperCamelCase_: Union[str, Any] = self_organizing_map.update(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) # classify test sample UpperCamelCase_: Dict = [0, 0, 0, 1] UpperCamelCase_: Union[str, Any] = self_organizing_map.get_winner(UpperCAmelCase__ , UpperCAmelCase__ ) # results print(F'''Clusters that the test sample belongs to : {winner}''' ) print(F'''Weights that have been trained : {weights}''' ) # running the main() function if __name__ == "__main__": main()
57
0
from __future__ import annotations from typing import Any class __UpperCAmelCase : """simple docstring""" def __init__( self , __A , __A , __A = 0 ): __a , __a = row, column __a = [[default_value for c in range(__A )] for r in range(__A )] def __str__( self ): __a = f'''Matrix consist of {self.row} rows and {self.column} columns\n''' # Make string identifier __a = 0 for row_vector in self.array: for obj in row_vector: __a = max(__A , len(str(__A ) ) ) __a = f'''%{max_element_length}s''' # Make string and return def single_line(__A ) -> str: nonlocal string_format_identifier __a = """[""" line += ", ".join(string_format_identifier % (obj,) for obj in row_vector ) line += "]" return line s += "\n".join(single_line(__A ) for row_vector in self.array ) return s def __repr__( self ): return str(self ) def snake_case_ ( self , __A ): if not (isinstance(__A , (list, tuple) ) and len(__A ) == 2): return False elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column): return False else: return True def __getitem__( self , __A ): assert self.validate_indicies(__A ) return self.array[loc[0]][loc[1]] def __setitem__( self , __A , __A ): assert self.validate_indicies(__A ) __a = value def __add__( self , __A ): assert isinstance(__A , __A ) assert self.row == another.row and self.column == another.column # Add __a = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): __a = self[r, c] + another[r, c] return result def __neg__( self ): __a = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): __a = -self[r, c] return result def __sub__( self , __A ): return self + (-another) def __mul__( self , __A ): if isinstance(__A , (int, float) ): # Scalar multiplication __a = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): __a = self[r, c] * another return result elif isinstance(__A , __A ): # Matrix multiplication assert self.column == another.row __a = Matrix(self.row , another.column ) for r in range(self.row ): for c in range(another.column ): for i in range(self.column ): result[r, c] += self[r, i] * another[i, c] return result else: __a = f'''Unsupported type given for another ({type(__A )})''' raise TypeError(__A ) def snake_case_ ( self ): __a = Matrix(self.column , self.row ) for r in range(self.row ): for c in range(self.column ): __a = self[r, c] return result def snake_case_ ( self , __A , __A ): assert isinstance(__A , __A ) and isinstance(__A , __A ) assert self.row == self.column == u.row == v.row # u, v should be column vector assert u.column == v.column == 1 # u, v should be column vector # Calculate __a = v.transpose() __a = (v_t * self * u)[0, 0] + 1 if numerator_factor == 0: return None # It's not invertable return self - ((self * u) * (v_t * self) * (1.0 / numerator_factor)) # Testing if __name__ == "__main__": def a (): # a^(-1) __a = Matrix(3 , 3 , 0 ) for i in range(3 ): __a = 1 print(f'''a^(-1) is {ainv}''' ) # u, v __a = Matrix(3 , 1 , 0 ) __a , __a , __a = 1, 2, -3 __a = Matrix(3 , 1 , 0 ) __a , __a , __a = 4, -2, 5 print(f'''u is {u}''' ) print(f'''v is {v}''' ) print(f'''uv^T is {u * v.transpose()}''' ) # Sherman Morrison print(f'''(a + uv^T)^(-1) is {ainv.sherman_morrison(lowerCAmelCase__ , lowerCAmelCase__ )}''' ) def a (): import doctest doctest.testmod() testa()
99
from collections import namedtuple A_ : Tuple = namedtuple('from_to', 'from_ to') A_ : int = { 'cubicmeter': from_to(1, 1), 'litre': from_to(0.001, 1000), 'kilolitre': from_to(1, 1), 'gallon': from_to(0.00454, 264.172), 'cubicyard': from_to(0.76455, 1.30795), 'cubicfoot': from_to(0.028, 35.3147), 'cup': from_to(0.000236588, 4226.75), } def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) -> float: if from_type not in METRIC_CONVERSION: raise ValueError( F'''Invalid \'from_type\' value: {from_type!r} Supported values are:\n''' + ', '.join(UpperCAmelCase__ ) ) if to_type not in METRIC_CONVERSION: raise ValueError( F'''Invalid \'to_type\' value: {to_type!r}. Supported values are:\n''' + ', '.join(UpperCAmelCase__ ) ) return value * METRIC_CONVERSION[from_type].from_ * METRIC_CONVERSION[to_type].to if __name__ == "__main__": import doctest doctest.testmod()
57
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 _A : Dict = logging.get_logger(__name__) _A : List[str] = { """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 __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ : List[str] = """codegen""" lowerCamelCase__ : int = { """max_position_embeddings""": """n_positions""", """hidden_size""": """n_embd""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self , A_=5_04_00 , A_=20_48 , A_=20_48 , A_=40_96 , A_=28 , A_=16 , A_=64 , A_=None , A_="gelu_new" , A_=0.0 , A_=0.0 , A_=0.0 , A_=1E-5 , A_=0.02 , A_=True , A_=5_02_56 , A_=5_02_56 , A_=False , **A_ , ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = vocab_size SCREAMING_SNAKE_CASE__ = n_ctx SCREAMING_SNAKE_CASE__ = n_positions SCREAMING_SNAKE_CASE__ = n_embd SCREAMING_SNAKE_CASE__ = n_layer SCREAMING_SNAKE_CASE__ = n_head SCREAMING_SNAKE_CASE__ = n_inner SCREAMING_SNAKE_CASE__ = rotary_dim SCREAMING_SNAKE_CASE__ = activation_function SCREAMING_SNAKE_CASE__ = resid_pdrop SCREAMING_SNAKE_CASE__ = embd_pdrop SCREAMING_SNAKE_CASE__ = attn_pdrop SCREAMING_SNAKE_CASE__ = layer_norm_epsilon SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = use_cache SCREAMING_SNAKE_CASE__ = bos_token_id SCREAMING_SNAKE_CASE__ = eos_token_id super().__init__( bos_token_id=A_ , eos_token_id=A_ , tie_word_embeddings=A_ , **A_ ) class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , A_ , A_ = "default" , A_ = None , A_ = False , ): '''simple docstring''' super().__init__(A_ , task=A_ , patching_specs=A_ , use_past=A_ ) if not getattr(self._config , '''pad_token_id''' , A_ ): # TODO: how to do that better? SCREAMING_SNAKE_CASE__ = 0 @property def lowercase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = OrderedDict({'''input_ids''': {0: '''batch''', 1: '''sequence'''}} ) if self.use_past: self.fill_with_past_key_values_(A_ , direction='''inputs''' ) SCREAMING_SNAKE_CASE__ = {0: '''batch''', 1: '''past_sequence + sequence'''} else: SCREAMING_SNAKE_CASE__ = {0: '''batch''', 1: '''sequence'''} return common_inputs @property def lowercase_ ( self ): '''simple docstring''' return self._config.n_layer @property def lowercase_ ( self ): '''simple docstring''' return self._config.n_head def lowercase_ ( self , A_ , A_ = -1 , A_ = -1 , A_ = False , A_ = None , ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = super(A_ , self ).generate_dummy_inputs( A_ , batch_size=A_ , seq_length=A_ , is_pair=A_ , framework=A_ ) # We need to order the input in the way they appears in the forward() SCREAMING_SNAKE_CASE__ = 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 SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = common_inputs['''input_ids'''].shape # Not using the same length for past_key_values SCREAMING_SNAKE_CASE__ = seqlen + 2 SCREAMING_SNAKE_CASE__ = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) SCREAMING_SNAKE_CASE__ = [ (torch.zeros(A_ ), torch.zeros(A_ )) for _ in range(self.num_layers ) ] SCREAMING_SNAKE_CASE__ = common_inputs['''attention_mask'''] if self.use_past: SCREAMING_SNAKE_CASE__ = ordered_inputs['''attention_mask'''].dtype SCREAMING_SNAKE_CASE__ = torch.cat( [ordered_inputs['''attention_mask'''], torch.ones(A_ , A_ , dtype=A_ )] , dim=1 ) return ordered_inputs @property def lowercase_ ( self ): '''simple docstring''' return 13
100
import warnings from ...utils import logging from .image_processing_clip import CLIPImageProcessor A_ : int = logging.get_logger(__name__) class _lowerCAmelCase( UpperCAmelCase_ ): """simple docstring""" def __init__( self , *_lowerCamelCase , **_lowerCamelCase ): warnings.warn( 'The class CLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use CLIPImageProcessor instead.' , _lowerCamelCase , ) super().__init__(*_lowerCamelCase , **_lowerCamelCase )
57
0