code
stringlengths
81
54k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
"""simple docstring""" __SCREAMING_SNAKE_CASE : Dict = range(2, 20 + 1) __SCREAMING_SNAKE_CASE : int = [10**k for k in range(ks[-1] + 1)] __SCREAMING_SNAKE_CASE : Union[str, Any] = {} def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[int]: snake_case_ = sum(a_i[j] for j in range(a_ , len(a_ ) ) ) snake_case_ = sum(a_i[j] * base[j] for j in range(min(len(a_ ) , a_ ) ) ) snake_case_ = 0, 0 snake_case_ = n - i snake_case_ = memo.get(a_ ) if sub_memo is not None: snake_case_ = sub_memo.get(a_ ) if jumps is not None and len(a_ ) > 0: # find and make the largest jump without going over snake_case_ = -1 for _k in range(len(a_ ) - 1 , -1 , -1 ): if jumps[_k][2] <= k and jumps[_k][1] <= max_dn: snake_case_ = _k break if max_jump >= 0: snake_case_ = jumps[max_jump] # since the difference between jumps is cached, add c snake_case_ = diff + c for j in range(min(a_ , len(a_ ) ) ): snake_case_ = divmod(a_ , 10 ) if new_c > 0: add(a_ , a_ , a_ ) else: snake_case_ = [] else: snake_case_ = {c: []} snake_case_ = sub_memo if dn >= max_dn or c + diff >= base[k]: return diff, dn if k > ks[0]: while True: # keep doing smaller jumps snake_case_ = next_term(a_ , k - 1 , i + dn , a_ ) diff += _diff dn += terms_jumped if dn >= max_dn or c + diff >= base[k]: break else: # would be too small a jump, just compute sequential terms instead snake_case_ = compute(a_ , a_ , i + dn , a_ ) diff += _diff dn += terms_jumped snake_case_ = sub_memo[c] # keep jumps sorted by # of terms skipped snake_case_ = 0 while j < len(a_ ): if jumps[j][1] > dn: break j += 1 # cache the jump for this value digitsum(b) and c sub_memo[c].insert(a_ , (diff, dn, k) ) return (diff, dn) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: if i >= n: return 0, i if k > len(a_ ): a_i.extend([0 for _ in range(k - len(a_ ) )] ) # note: a_i -> b * 10^k + c # ds_b -> digitsum(b) # ds_c -> digitsum(c) snake_case_ = i snake_case_ = 0, 0, 0 for j in range(len(a_ ) ): if j >= k: ds_b += a_i[j] else: ds_c += a_i[j] while i < n: i += 1 snake_case_ = ds_c + ds_b diff += addend snake_case_ = 0 for j in range(a_ ): snake_case_ = a_i[j] + addend snake_case_ = divmod(a_ , 10 ) ds_c += a_i[j] if addend > 0: break if addend > 0: add(a_ , a_ , a_ ) return diff, i - start_i def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[str]: for j in range(a_ , len(a_ ) ): snake_case_ = digits[j] + addend if s >= 10: snake_case_ = divmod(a_ , 10 ) snake_case_ = addend // 10 + quotient else: snake_case_ = s snake_case_ = addend // 10 if addend == 0: break while addend > 0: snake_case_ = divmod(a_ , 10 ) digits.append(a_ ) def _a ( _SCREAMING_SNAKE_CASE = 10**15 ) -> int: snake_case_ = [1] snake_case_ = 1 snake_case_ = 0 while True: snake_case_ = next_term(a_ , 20 , i + dn , a_ ) dn += terms_jumped if dn == n - i: break snake_case_ = 0 for j in range(len(a_ ) ): a_n += digits[j] * 10**j return a_n if __name__ == "__main__": print(f"""{solution() = }""")
712
"""simple docstring""" import json import os import tempfile import unittest import numpy as np from datasets import load_dataset 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 if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ImageGPTImageProcessor class __A (unittest.TestCase): '''simple docstring''' def __init__( self : int , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Tuple=7 , UpperCAmelCase_ : Dict=3 , UpperCAmelCase_ : Tuple=18 , UpperCAmelCase_ : Optional[Any]=30 , UpperCAmelCase_ : str=400 , UpperCAmelCase_ : int=True , UpperCAmelCase_ : Optional[int]=None , UpperCAmelCase_ : Optional[Any]=True , ) ->Optional[Any]: """simple docstring""" snake_case_ = size if size is not None else {"""height""": 18, """width""": 18} snake_case_ = parent snake_case_ = batch_size snake_case_ = num_channels snake_case_ = image_size snake_case_ = min_resolution snake_case_ = max_resolution snake_case_ = do_resize snake_case_ = size snake_case_ = do_normalize def lowerCAmelCase ( self : List[str] ) ->Optional[Any]: """simple docstring""" return { # here we create 2 clusters for the sake of simplicity "clusters": np.asarray( [ [0.8_866_443_634_033_203, 0.6_618_829_369_544_983, 0.3_891_746_401_786_804], [-0.6_042_559_146_881_104, -0.02_295_008_860_528_469, 0.5_423_797_369_003_296], ] ), "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, } @require_torch @require_vision class __A (snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: List[Any] = ImageGPTImageProcessor if is_vision_available() else None def lowerCAmelCase ( self : Optional[int] ) ->Optional[int]: """simple docstring""" snake_case_ = ImageGPTImageProcessingTester(self ) @property def lowerCAmelCase ( self : Tuple ) ->List[Any]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(UpperCAmelCase_ , """clusters""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """do_resize""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """size""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """do_normalize""" ) ) def lowerCAmelCase ( self : Optional[int] ) ->Optional[Any]: """simple docstring""" snake_case_ = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""height""": 18, """width""": 18} ) snake_case_ = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {"""height""": 42, """width""": 42} ) def lowerCAmelCase ( self : Any ) ->List[Any]: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) snake_case_ = json.loads(image_processor.to_json_string() ) for key, value in self.image_processor_dict.items(): if key == "clusters": self.assertTrue(np.array_equal(UpperCAmelCase_ , obj[key] ) ) else: self.assertEqual(obj[key] , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] ) ->Dict: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: snake_case_ = os.path.join(UpperCAmelCase_ , """image_processor.json""" ) image_processor_first.to_json_file(UpperCAmelCase_ ) snake_case_ = self.image_processing_class.from_json_file(UpperCAmelCase_ ).to_dict() snake_case_ = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(UpperCAmelCase_ , image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->List[Any]: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: image_processor_first.save_pretrained(UpperCAmelCase_ ) snake_case_ = self.image_processing_class.from_pretrained(UpperCAmelCase_ ).to_dict() snake_case_ = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(UpperCAmelCase_ , image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] , UpperCAmelCase_ ) @unittest.skip("""ImageGPT requires clusters at initialization""" ) def lowerCAmelCase ( self : List[Any] ) ->Tuple: """simple docstring""" pass def _a ( ) -> str: snake_case_ = load_dataset("""hf-internal-testing/fixtures_image_utils""" , split="""test""" ) snake_case_ = Image.open(dataset[4]["""file"""] ) snake_case_ = Image.open(dataset[5]["""file"""] ) snake_case_ = [imagea, imagea] return images @require_vision @require_torch class __A (unittest.TestCase): '''simple docstring''' @slow def lowerCAmelCase ( self : Tuple ) ->List[str]: """simple docstring""" snake_case_ = ImageGPTImageProcessor.from_pretrained("""openai/imagegpt-small""" ) snake_case_ = prepare_images() # test non-batched snake_case_ = image_processing(images[0] , return_tensors="""pt""" ) self.assertIsInstance(encoding.input_ids , torch.LongTensor ) self.assertEqual(encoding.input_ids.shape , (1, 1_024) ) snake_case_ = [306, 191, 191] self.assertEqual(encoding.input_ids[0, :3].tolist() , UpperCAmelCase_ ) # test batched snake_case_ = image_processing(UpperCAmelCase_ , return_tensors="""pt""" ) self.assertIsInstance(encoding.input_ids , torch.LongTensor ) self.assertEqual(encoding.input_ids.shape , (2, 1_024) ) snake_case_ = [303, 13, 13] self.assertEqual(encoding.input_ids[1, -3:].tolist() , UpperCAmelCase_ )
2
0
from ...configuration_utils import PretrainedConfig from ...utils import logging __SCREAMING_SNAKE_CASE : List[str] = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Dict = { 'google/canine-s': 'https://huggingface.co/google/canine-s/resolve/main/config.json', # See all CANINE models at https://huggingface.co/models?filter=canine } class __A (_a): '''simple docstring''' __lowercase: int = """canine""" def __init__( self : Union[str, Any] , UpperCAmelCase_ : int=768 , UpperCAmelCase_ : Optional[Any]=12 , UpperCAmelCase_ : Dict=12 , UpperCAmelCase_ : Any=3_072 , UpperCAmelCase_ : Tuple="gelu" , UpperCAmelCase_ : int=0.1 , UpperCAmelCase_ : Dict=0.1 , UpperCAmelCase_ : List[Any]=16_384 , UpperCAmelCase_ : Optional[int]=16 , UpperCAmelCase_ : str=0.02 , UpperCAmelCase_ : str=1E-12 , UpperCAmelCase_ : Union[str, Any]=0 , UpperCAmelCase_ : Dict=0XE000 , UpperCAmelCase_ : Optional[int]=0XE001 , UpperCAmelCase_ : Tuple=4 , UpperCAmelCase_ : str=4 , UpperCAmelCase_ : List[Any]=8 , UpperCAmelCase_ : Any=16_384 , UpperCAmelCase_ : List[Any]=128 , **UpperCAmelCase_ : int , ) ->Any: """simple docstring""" super().__init__(pad_token_id=_A , bos_token_id=_A , eos_token_id=_A , **_A ) snake_case_ = max_position_embeddings snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = initializer_range snake_case_ = type_vocab_size snake_case_ = layer_norm_eps # Character config: snake_case_ = downsampling_rate snake_case_ = upsampling_kernel_size snake_case_ = num_hash_functions snake_case_ = num_hash_buckets snake_case_ = local_transformer_stride
713
"""simple docstring""" import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, ) from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST class __A : '''simple docstring''' def __init__( self : Optional[int] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[Any]=13 , UpperCAmelCase_ : Optional[int]=7 , UpperCAmelCase_ : List[str]=True , UpperCAmelCase_ : int=True , UpperCAmelCase_ : List[Any]=True , UpperCAmelCase_ : Optional[int]=True , UpperCAmelCase_ : List[str]=99 , UpperCAmelCase_ : Dict=24 , UpperCAmelCase_ : List[str]=2 , UpperCAmelCase_ : Optional[Any]=6 , UpperCAmelCase_ : int=37 , UpperCAmelCase_ : Optional[Any]="gelu" , UpperCAmelCase_ : Optional[Any]=0.1 , UpperCAmelCase_ : List[Any]=0.1 , UpperCAmelCase_ : Any=512 , UpperCAmelCase_ : str=16 , UpperCAmelCase_ : List[str]=2 , UpperCAmelCase_ : Optional[int]=0.02 , UpperCAmelCase_ : Tuple=3 , UpperCAmelCase_ : Union[str, Any]=None , UpperCAmelCase_ : Any=1_000 , ) ->Tuple: """simple docstring""" snake_case_ = parent snake_case_ = batch_size snake_case_ = seq_length snake_case_ = is_training snake_case_ = use_input_mask snake_case_ = use_token_type_ids snake_case_ = use_labels snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = max_position_embeddings snake_case_ = type_vocab_size snake_case_ = type_sequence_label_size snake_case_ = initializer_range snake_case_ = num_labels snake_case_ = scope snake_case_ = range_bbox def lowerCAmelCase ( self : Tuple ) ->int: """simple docstring""" snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case_ = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox ) # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: snake_case_ = bbox[i, j, 3] snake_case_ = bbox[i, j, 1] snake_case_ = t if bbox[i, j, 2] < bbox[i, j, 0]: snake_case_ = bbox[i, j, 2] snake_case_ = bbox[i, j, 0] snake_case_ = t snake_case_ = None if self.use_input_mask: snake_case_ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) snake_case_ = None if self.use_token_type_ids: snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) snake_case_ = None snake_case_ = None if self.use_labels: snake_case_ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) snake_case_ = self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def lowerCAmelCase ( self : int ) ->Optional[int]: """simple docstring""" return LiltConfig( 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 , ) def lowerCAmelCase ( self : Any , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Any , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[int] , ) ->str: """simple docstring""" snake_case_ = LiltModel(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ , bbox=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ ) snake_case_ = model(UpperCAmelCase_ , bbox=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ ) snake_case_ = model(UpperCAmelCase_ , bbox=UpperCAmelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def lowerCAmelCase ( self : int , UpperCAmelCase_ : str , UpperCAmelCase_ : Any , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : str , UpperCAmelCase_ : List[Any] , ) ->Dict: """simple docstring""" snake_case_ = self.num_labels snake_case_ = LiltForTokenClassification(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model( UpperCAmelCase_ , bbox=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowerCAmelCase ( self : Any , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : str , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : int , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : List[str] , ) ->Dict: """simple docstring""" snake_case_ = LiltForQuestionAnswering(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model( UpperCAmelCase_ , bbox=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , start_positions=UpperCAmelCase_ , end_positions=UpperCAmelCase_ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def lowerCAmelCase ( self : int ) ->Optional[int]: """simple docstring""" snake_case_ = self.prepare_config_and_inputs() ( ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ) = config_and_inputs snake_case_ = { """input_ids""": input_ids, """bbox""": bbox, """token_type_ids""": token_type_ids, """attention_mask""": input_mask, } return config, inputs_dict @require_torch class __A (snake_case__ , snake_case__ , snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Optional[int] = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) __lowercase: Optional[Any] = ( { """feature-extraction""": LiltModel, """question-answering""": LiltForQuestionAnswering, """text-classification""": LiltForSequenceClassification, """token-classification""": LiltForTokenClassification, """zero-shot""": LiltForSequenceClassification, } if is_torch_available() else {} ) __lowercase: Union[str, Any] = False __lowercase: List[str] = False def lowerCAmelCase ( self : str , UpperCAmelCase_ : int , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[int] ) ->Optional[int]: """simple docstring""" return True def lowerCAmelCase ( self : Dict ) ->Union[str, Any]: """simple docstring""" snake_case_ = LiltModelTester(self ) snake_case_ = ConfigTester(self , config_class=UpperCAmelCase_ , hidden_size=37 ) def lowerCAmelCase ( self : str ) ->List[Any]: """simple docstring""" self.config_tester.run_common_tests() def lowerCAmelCase ( self : List[str] ) ->int: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] ) ->List[str]: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: snake_case_ = type self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def lowerCAmelCase ( self : List[Any] ) ->Dict: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->Dict: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*UpperCAmelCase_ ) @slow def lowerCAmelCase ( self : Union[str, Any] ) ->Optional[int]: """simple docstring""" for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ = LiltModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) @require_torch @slow class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : Optional[int] ) ->Dict: """simple docstring""" snake_case_ = LiltModel.from_pretrained("""SCUT-DLVCLab/lilt-roberta-en-base""" ).to(UpperCAmelCase_ ) snake_case_ = torch.tensor([[1, 2]] , device=UpperCAmelCase_ ) snake_case_ = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=UpperCAmelCase_ ) # forward pass with torch.no_grad(): snake_case_ = model(input_ids=UpperCAmelCase_ , bbox=UpperCAmelCase_ ) snake_case_ = torch.Size([1, 2, 768] ) snake_case_ = torch.tensor( [[-0.0_653, 0.0_950, -0.0_061], [-0.0_545, 0.0_926, -0.0_324]] , device=UpperCAmelCase_ , ) self.assertTrue(outputs.last_hidden_state.shape , UpperCAmelCase_ ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , UpperCAmelCase_ , atol=1E-3 ) )
2
0
"""simple docstring""" import random import torch from huggingface_hub import HfApi from diffusers import UNetaDModel __SCREAMING_SNAKE_CASE : int = HfApi() __SCREAMING_SNAKE_CASE : Any = {} # fmt: off __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([ -0.7515, -1.6883, 0.2420, 0.0300, 0.6347, 1.3433, -1.1743, -3.7467, 1.2342, -2.2485, 0.4636, 0.8076, -0.7991, 0.3969, 0.8498, 0.9189, -1.8887, -3.3522, 0.7639, 0.2040, 0.6271, -2.7148, -1.6316, 3.0839, 0.3186, 0.2721, -0.9759, -1.2461, 2.6257, 1.3557 ]) __SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([ -2.3639, -2.5344, 0.0054, -0.6674, 1.5990, 1.0158, 0.3124, -2.1436, 1.8795, -2.5429, -0.1566, -0.3973, 1.2490, 2.6447, 1.2283, -0.5208, -2.8154, -3.5119, 2.3838, 1.2033, 1.7201, -2.1256, -1.4576, 2.7948, 2.4204, -0.9752, -1.2546, 0.8027, 3.2758, 3.1365 ]) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([ -0.6531, -0.6891, -0.3172, -0.5375, -0.9140, -0.5367, -0.1175, -0.7869, -0.3808, -0.4513, -0.2098, -0.0083, 0.3183, 0.5140, 0.2247, -0.1304, -0.1302, -0.2802, -0.2084, -0.2025, -0.4967, -0.4873, -0.0861, 0.6925, 0.0250, 0.1290, -0.1543, 0.6316, 1.0460, 1.4943 ]) __SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([ 0.0911, 0.1107, 0.0182, 0.0435, -0.0805, -0.0608, 0.0381, 0.2172, -0.0280, 0.1327, -0.0299, -0.0255, -0.0050, -0.1170, -0.1046, 0.0309, 0.1367, 0.1728, -0.0533, -0.0748, -0.0534, 0.1624, 0.0384, -0.1805, -0.0707, 0.0642, 0.0220, -0.0134, -0.1333, -0.1505 ]) __SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([ 0.1321, 0.1337, 0.0440, 0.0622, -0.0591, -0.0370, 0.0503, 0.2133, -0.0177, 0.1415, -0.0116, -0.0112, 0.0044, -0.0980, -0.0789, 0.0395, 0.1502, 0.1785, -0.0488, -0.0514, -0.0404, 0.1539, 0.0454, -0.1559, -0.0665, 0.0659, 0.0383, -0.0005, -0.1266, -0.1386 ]) __SCREAMING_SNAKE_CASE : Tuple = torch.tensor([ 0.1154, 0.1218, 0.0307, 0.0526, -0.0711, -0.0541, 0.0366, 0.2078, -0.0267, 0.1317, -0.0226, -0.0193, -0.0014, -0.1055, -0.0902, 0.0330, 0.1391, 0.1709, -0.0562, -0.0693, -0.0560, 0.1482, 0.0381, -0.1683, -0.0681, 0.0661, 0.0331, -0.0046, -0.1268, -0.1431 ]) __SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor([ 0.1192, 0.1240, 0.0414, 0.0606, -0.0557, -0.0412, 0.0430, 0.2042, -0.0200, 0.1385, -0.0115, -0.0132, 0.0017, -0.0965, -0.0802, 0.0398, 0.1433, 0.1747, -0.0458, -0.0533, -0.0407, 0.1545, 0.0419, -0.1574, -0.0645, 0.0626, 0.0341, -0.0010, -0.1199, -0.1390 ]) __SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([ 0.1075, 0.1074, 0.0205, 0.0431, -0.0774, -0.0607, 0.0298, 0.2042, -0.0320, 0.1267, -0.0281, -0.0250, -0.0064, -0.1091, -0.0946, 0.0290, 0.1328, 0.1650, -0.0580, -0.0738, -0.0586, 0.1440, 0.0337, -0.1746, -0.0712, 0.0605, 0.0250, -0.0099, -0.1316, -0.1473 ]) __SCREAMING_SNAKE_CASE : Dict = torch.tensor([ -1.4572, -2.0481, -0.0414, -0.6005, 1.4136, 0.5848, 0.4028, -2.7330, 1.2212, -2.1228, 0.2155, 0.4039, 0.7662, 2.0535, 0.7477, -0.3243, -2.1758, -2.7648, 1.6947, 0.7026, 1.2338, -1.6078, -0.8682, 2.2810, 1.8574, -0.5718, -0.5586, -0.0186, 2.3415, 2.1251]) __SCREAMING_SNAKE_CASE : Tuple = torch.tensor([ -1.3690, -1.9720, -0.4090, -0.6966, 1.4660, 0.9938, -0.1385, -2.7324, 0.7736, -1.8917, 0.2923, 0.4293, 0.1693, 1.4112, 1.1887, -0.3181, -2.2160, -2.6381, 1.3170, 0.8163, 0.9240, -1.6544, -0.6099, 2.5259, 1.6430, -0.9090, -0.9392, -0.0126, 2.4268, 2.3266 ]) __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([ -1.3525, -1.9628, -0.3956, -0.6860, 1.4664, 1.0014, -0.1259, -2.7212, 0.7772, -1.8811, 0.2996, 0.4388, 0.1704, 1.4029, 1.1701, -0.3027, -2.2053, -2.6287, 1.3350, 0.8131, 0.9274, -1.6292, -0.6098, 2.5131, 1.6505, -0.8958, -0.9298, -0.0151, 2.4257, 2.3355 ]) __SCREAMING_SNAKE_CASE : int = torch.tensor([ -2.0585, -2.7897, -0.2850, -0.8940, 1.9052, 0.5702, 0.6345, -3.8959, 1.5932, -3.2319, 0.1974, 0.0287, 1.7566, 2.6543, 0.8387, -0.5351, -3.2736, -4.3375, 2.9029, 1.6390, 1.4640, -2.1701, -1.9013, 2.9341, 3.4981, -0.6255, -1.1644, -0.1591, 3.7097, 3.2066 ]) __SCREAMING_SNAKE_CASE : Any = torch.tensor([ -2.3139, -2.5594, -0.0197, -0.6785, 1.7001, 1.1606, 0.3075, -2.1740, 1.8071, -2.5630, -0.0926, -0.3811, 1.2116, 2.6246, 1.2731, -0.5398, -2.8153, -3.6140, 2.3893, 1.3262, 1.6258, -2.1856, -1.3267, 2.8395, 2.3779, -1.0623, -1.2468, 0.8959, 3.3367, 3.2243 ]) __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([ -2.0628, -2.7667, -0.2089, -0.8263, 2.0539, 0.5992, 0.6495, -3.8336, 1.6025, -3.2817, 0.1721, -0.0633, 1.7516, 2.7039, 0.8100, -0.5908, -3.2113, -4.4343, 2.9257, 1.3632, 1.5562, -2.1489, -1.9894, 3.0560, 3.3396, -0.7328, -1.0417, 0.0383, 3.7093, 3.2343 ]) __SCREAMING_SNAKE_CASE : Dict = torch.tensor([ -1.4574, -2.0569, -0.0473, -0.6117, 1.4018, 0.5769, 0.4129, -2.7344, 1.2241, -2.1397, 0.2000, 0.3937, 0.7616, 2.0453, 0.7324, -0.3391, -2.1746, -2.7744, 1.6963, 0.6921, 1.2187, -1.6172, -0.8877, 2.2439, 1.8471, -0.5839, -0.5605, -0.0464, 2.3250, 2.1219 ]) # fmt: on __SCREAMING_SNAKE_CASE : Any = api.list_models(filter='diffusers') for mod in models: if "google" in mod.author or mod.modelId == "CompVis/ldm-celebahq-256": __SCREAMING_SNAKE_CASE : str = '/home/patrick/google_checkpoints/' + mod.modelId.split('/')[-1] print(f"""Started running {mod.modelId}!!!""") if mod.modelId.startswith('CompVis'): __SCREAMING_SNAKE_CASE : str = UNetaDModel.from_pretrained(local_checkpoint, subfolder='unet') else: __SCREAMING_SNAKE_CASE : Optional[Any] = UNetaDModel.from_pretrained(local_checkpoint) torch.manual_seed(0) random.seed(0) __SCREAMING_SNAKE_CASE : Any = torch.randn(1, model.config.in_channels, model.config.sample_size, model.config.sample_size) __SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor([10] * noise.shape[0]) with torch.no_grad(): __SCREAMING_SNAKE_CASE : int = model(noise, time_step).sample assert torch.allclose( logits[0, 0, 0, :30], results['_'.join('_'.join(mod.modelId.split('/')).split('-'))], atol=1E-3 ) print(f"""{mod.modelId} has passed successfully!!!""")
714
"""simple docstring""" from __future__ import annotations def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> list[int]: snake_case_ = 0 snake_case_ = len(_SCREAMING_SNAKE_CASE ) - 1 while i < j: if nums[i] + nums[j] == target: return [i, j] elif nums[i] + nums[j] < target: snake_case_ = i + 1 else: snake_case_ = j - 1 return [] if __name__ == "__main__": import doctest doctest.testmod() print(f"""{two_pointer([2, 7, 11, 15], 9) = }""")
2
0
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE ) -> Optional[int]: snake_case_ = [0] * len(_UpperCamelCase ) snake_case_ = [] snake_case_ = [1] * len(_UpperCamelCase ) for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(_UpperCamelCase ) ): if indegree[i] == 0: queue.append(_UpperCamelCase ) while queue: snake_case_ = queue.pop(0 ) for x in graph[vertex]: indegree[x] -= 1 if long_dist[vertex] + 1 > long_dist[x]: snake_case_ = long_dist[vertex] + 1 if indegree[x] == 0: queue.append(_UpperCamelCase ) print(max(_UpperCamelCase ) ) # Adjacency list of Graph __SCREAMING_SNAKE_CASE : List[Any] = {0: [2, 3, 4], 1: [2, 7], 2: [5], 3: [5, 7], 4: [7], 5: [6], 6: [7], 7: []} longest_distance(graph)
715
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __SCREAMING_SNAKE_CASE : Optional[Any] = { 'configuration_biogpt': ['BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BioGptConfig'], 'tokenization_biogpt': ['BioGptTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : Optional[Any] = [ 'BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST', 'BioGptForCausalLM', 'BioGptForTokenClassification', 'BioGptForSequenceClassification', 'BioGptModel', 'BioGptPreTrainedModel', ] if TYPE_CHECKING: from .configuration_biogpt import BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, BioGptConfig from .tokenization_biogpt import BioGptTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_biogpt import ( BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptPreTrainedModel, ) else: import sys __SCREAMING_SNAKE_CASE : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
2
0
"""simple docstring""" from collections import OrderedDict from typing import TYPE_CHECKING, Any, List, Mapping, Optional from packaging import version if TYPE_CHECKING: from ... import PreTrainedTokenizer, TensorType from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import is_torch_available, logging __SCREAMING_SNAKE_CASE : List[Any] = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : List[Any] = { """bigscience/bloom""": """https://huggingface.co/bigscience/bloom/resolve/main/config.json""", """bigscience/bloom-560m""": """https://huggingface.co/bigscience/bloom-560m/blob/main/config.json""", """bigscience/bloom-1b1""": """https://huggingface.co/bigscience/bloom-1b1/blob/main/config.json""", """bigscience/bloom-1b7""": """https://huggingface.co/bigscience/bloom-1b7/blob/main/config.json""", """bigscience/bloom-3b""": """https://huggingface.co/bigscience/bloom-3b/blob/main/config.json""", """bigscience/bloom-7b1""": """https://huggingface.co/bigscience/bloom-7b1/blob/main/config.json""", } class __A (__UpperCAmelCase): '''simple docstring''' __lowercase: str = """bloom""" __lowercase: List[Any] = ["""past_key_values"""] __lowercase: List[str] = { """num_hidden_layers""": """n_layer""", """num_attention_heads""": """n_head""", } def __init__( self : Dict , UpperCAmelCase_ : Union[str, Any]=250_880 , UpperCAmelCase_ : int=64 , UpperCAmelCase_ : Tuple=2 , UpperCAmelCase_ : Optional[Any]=8 , UpperCAmelCase_ : Optional[Any]=1E-5 , UpperCAmelCase_ : Any=0.02 , UpperCAmelCase_ : int=True , UpperCAmelCase_ : Optional[Any]=1 , UpperCAmelCase_ : str=2 , UpperCAmelCase_ : Optional[int]=False , UpperCAmelCase_ : int=0.0 , UpperCAmelCase_ : List[str]=0.0 , UpperCAmelCase_ : Optional[Any]=1 , UpperCAmelCase_ : str=False , **UpperCAmelCase_ : Tuple , ) ->Union[str, Any]: """simple docstring""" snake_case_ = vocab_size # Backward compatibility with n_embed kwarg snake_case_ = kwargs.pop("""n_embed""" , UpperCAmelCase_ ) snake_case_ = hidden_size if n_embed is None else n_embed snake_case_ = n_layer snake_case_ = n_head snake_case_ = layer_norm_epsilon snake_case_ = initializer_range snake_case_ = use_cache snake_case_ = pretraining_tp snake_case_ = apply_residual_connection_post_layernorm snake_case_ = hidden_dropout snake_case_ = attention_dropout snake_case_ = bos_token_id snake_case_ = eos_token_id snake_case_ = slow_but_exact super().__init__(bos_token_id=UpperCAmelCase_ , eos_token_id=UpperCAmelCase_ , **UpperCAmelCase_ ) class __A (__UpperCAmelCase): '''simple docstring''' __lowercase: List[str] = version.parse("""1.12""") def __init__( self : Any , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Any = "default" , UpperCAmelCase_ : Any = None , UpperCAmelCase_ : str = False , ) ->List[Any]: """simple docstring""" super().__init__(UpperCAmelCase_ , task=UpperCAmelCase_ , patching_specs=UpperCAmelCase_ , use_past=UpperCAmelCase_ ) if not getattr(self._config , """pad_token_id""" , UpperCAmelCase_ ): # TODO: how to do that better? snake_case_ = 0 @property def lowerCAmelCase ( self : Union[str, Any] ) ->Tuple: """simple docstring""" snake_case_ = OrderedDict({"""input_ids""": {0: """batch""", 1: """sequence"""}} ) if self.use_past: # BLOOM stores values on dynamic axis 2. For more details see: https://github.com/huggingface/transformers/pull/18344 self.fill_with_past_key_values_(UpperCAmelCase_ , direction="""inputs""" , inverted_values_shape=UpperCAmelCase_ ) snake_case_ = {0: """batch""", 1: """past_sequence + sequence"""} else: snake_case_ = {0: """batch""", 1: """sequence"""} return common_inputs @property def lowerCAmelCase ( self : Union[str, Any] ) ->Tuple: """simple docstring""" return self._config.n_layer @property def lowerCAmelCase ( self : Any ) ->Optional[int]: """simple docstring""" return self._config.n_head @property def lowerCAmelCase ( self : Union[str, Any] ) ->List[Any]: """simple docstring""" return 1E-3 def lowerCAmelCase ( self : Any , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[int] = -1 , UpperCAmelCase_ : Any = -1 , UpperCAmelCase_ : List[str] = False , UpperCAmelCase_ : Optional[int] = None , ) ->List[Any]: """simple docstring""" snake_case_ = super(UpperCAmelCase_ , self ).generate_dummy_inputs( UpperCAmelCase_ , batch_size=UpperCAmelCase_ , seq_length=UpperCAmelCase_ , is_pair=UpperCAmelCase_ , framework=UpperCAmelCase_ ) # We need to order the input in the way they appears in the forward() 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 snake_case_ , snake_case_ = common_inputs["""input_ids"""].shape # Not using the same length for past_key_values snake_case_ = seqlen + 2 snake_case_ = self._config.hidden_size // self.num_attention_heads snake_case_ = ( batch * self.num_attention_heads, head_dim, past_key_values_length, ) snake_case_ = ( batch * self.num_attention_heads, past_key_values_length, head_dim, ) snake_case_ = [ (torch.zeros(UpperCAmelCase_ ), torch.zeros(UpperCAmelCase_ )) for _ in range(self.num_layers ) ] snake_case_ = common_inputs["""attention_mask"""] if self.use_past: snake_case_ = ordered_inputs["""attention_mask"""].dtype snake_case_ = torch.cat( [ordered_inputs["""attention_mask"""], torch.ones(UpperCAmelCase_ , UpperCAmelCase_ , dtype=UpperCAmelCase_ )] , dim=1 ) return ordered_inputs @property def lowerCAmelCase ( self : Optional[Any] ) ->Optional[int]: """simple docstring""" return 13
716
"""simple docstring""" __SCREAMING_SNAKE_CASE : str = 'Input must be a string of 8 numbers plus letter' __SCREAMING_SNAKE_CASE : Dict = 'TRWAGMYFPDXBNJZSQVHLCKE' def _a ( _SCREAMING_SNAKE_CASE ) -> bool: if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): snake_case_ = f"""Expected string as input, found {type(_SCREAMING_SNAKE_CASE ).__name__}""" raise TypeError(_SCREAMING_SNAKE_CASE ) snake_case_ = spanish_id.replace("""-""" , """""" ).upper() if len(_SCREAMING_SNAKE_CASE ) != 9: raise ValueError(_SCREAMING_SNAKE_CASE ) try: snake_case_ = int(spanish_id_clean[0:8] ) snake_case_ = spanish_id_clean[8] except ValueError as ex: raise ValueError(_SCREAMING_SNAKE_CASE ) from ex if letter.isdigit(): raise ValueError(_SCREAMING_SNAKE_CASE ) return letter == LOOKUP_LETTERS[number % 23] if __name__ == "__main__": import doctest doctest.testmod()
2
0
"""simple docstring""" from typing import List from ...configuration_utils import PretrainedConfig from ...utils import logging __SCREAMING_SNAKE_CASE : Dict = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Tuple = { "snap-research/efficientformer-l1-300": ( "https://huggingface.co/snap-research/efficientformer-l1-300/resolve/main/config.json" ), } class __A (__lowerCAmelCase): '''simple docstring''' __lowercase: str = "efficientformer" def __init__( self : Any , UpperCAmelCase_ : List[int] = [3, 2, 6, 4] , UpperCAmelCase_ : List[int] = [48, 96, 224, 448] , UpperCAmelCase_ : List[bool] = [True, True, True, True] , UpperCAmelCase_ : int = 448 , UpperCAmelCase_ : int = 32 , UpperCAmelCase_ : int = 4 , UpperCAmelCase_ : int = 7 , UpperCAmelCase_ : int = 5 , UpperCAmelCase_ : int = 8 , UpperCAmelCase_ : int = 4 , UpperCAmelCase_ : float = 0.0 , UpperCAmelCase_ : int = 16 , UpperCAmelCase_ : int = 3 , UpperCAmelCase_ : int = 3 , UpperCAmelCase_ : int = 3 , UpperCAmelCase_ : int = 2 , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : float = 0.0 , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : float = 1E-5 , UpperCAmelCase_ : str = "gelu" , UpperCAmelCase_ : float = 0.02 , UpperCAmelCase_ : float = 1E-12 , UpperCAmelCase_ : int = 224 , UpperCAmelCase_ : float = 1E-05 , **UpperCAmelCase_ : str , ) ->None: """simple docstring""" super().__init__(**lowerCamelCase__ ) snake_case_ = hidden_act snake_case_ = hidden_dropout_prob snake_case_ = hidden_sizes snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = initializer_range snake_case_ = layer_norm_eps snake_case_ = patch_size snake_case_ = num_channels snake_case_ = depths snake_case_ = mlp_expansion_ratio snake_case_ = downsamples snake_case_ = dim snake_case_ = key_dim snake_case_ = attention_ratio snake_case_ = resolution snake_case_ = pool_size snake_case_ = downsample_patch_size snake_case_ = downsample_stride snake_case_ = downsample_pad snake_case_ = drop_path_rate snake_case_ = num_metaad_blocks snake_case_ = distillation snake_case_ = use_layer_scale snake_case_ = layer_scale_init_value snake_case_ = image_size snake_case_ = batch_norm_eps
717
"""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 logging __SCREAMING_SNAKE_CASE : List[str] = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Optional[int] = {'vocab_file': 'spiece.model'} __SCREAMING_SNAKE_CASE : List[str] = { 'vocab_file': { 'albert-base-v1': 'https://huggingface.co/albert-base-v1/resolve/main/spiece.model', 'albert-large-v1': 'https://huggingface.co/albert-large-v1/resolve/main/spiece.model', 'albert-xlarge-v1': 'https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model', 'albert-xxlarge-v1': 'https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model', 'albert-base-v2': 'https://huggingface.co/albert-base-v2/resolve/main/spiece.model', 'albert-large-v2': 'https://huggingface.co/albert-large-v2/resolve/main/spiece.model', 'albert-xlarge-v2': 'https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model', 'albert-xxlarge-v2': 'https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model', } } __SCREAMING_SNAKE_CASE : List[str] = { 'albert-base-v1': 512, 'albert-large-v1': 512, 'albert-xlarge-v1': 512, 'albert-xxlarge-v1': 512, 'albert-base-v2': 512, 'albert-large-v2': 512, 'albert-xlarge-v2': 512, 'albert-xxlarge-v2': 512, } __SCREAMING_SNAKE_CASE : int = '▁' class __A (snake_case__): '''simple docstring''' __lowercase: Optional[Any] = VOCAB_FILES_NAMES __lowercase: Optional[int] = PRETRAINED_VOCAB_FILES_MAP __lowercase: Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : int , UpperCAmelCase_ : Any , UpperCAmelCase_ : Dict=True , UpperCAmelCase_ : Dict=True , UpperCAmelCase_ : List[str]=False , UpperCAmelCase_ : List[Any]="[CLS]" , UpperCAmelCase_ : Any="[SEP]" , UpperCAmelCase_ : str="<unk>" , UpperCAmelCase_ : str="[SEP]" , UpperCAmelCase_ : Optional[Any]="<pad>" , UpperCAmelCase_ : Optional[int]="[CLS]" , UpperCAmelCase_ : int="[MASK]" , UpperCAmelCase_ : Optional[Dict[str, Any]] = None , **UpperCAmelCase_ : Union[str, Any] , ) ->None: """simple docstring""" snake_case_ = ( AddedToken(UpperCAmelCase_ , lstrip=UpperCAmelCase_ , rstrip=UpperCAmelCase_ , normalized=UpperCAmelCase_ ) if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) else mask_token ) snake_case_ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=UpperCAmelCase_ , remove_space=UpperCAmelCase_ , keep_accents=UpperCAmelCase_ , bos_token=UpperCAmelCase_ , eos_token=UpperCAmelCase_ , unk_token=UpperCAmelCase_ , sep_token=UpperCAmelCase_ , pad_token=UpperCAmelCase_ , cls_token=UpperCAmelCase_ , mask_token=UpperCAmelCase_ , sp_model_kwargs=self.sp_model_kwargs , **UpperCAmelCase_ , ) snake_case_ = do_lower_case snake_case_ = remove_space snake_case_ = keep_accents snake_case_ = vocab_file snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(UpperCAmelCase_ ) @property def lowerCAmelCase ( self : List[Any] ) ->Dict: """simple docstring""" return len(self.sp_model ) def lowerCAmelCase ( self : str ) ->List[Any]: """simple docstring""" snake_case_ = {self.convert_ids_to_tokens(UpperCAmelCase_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Dict ) ->List[str]: """simple docstring""" snake_case_ = self.__dict__.copy() snake_case_ = None return state def __setstate__( self : Tuple , UpperCAmelCase_ : Optional[int] ) ->Optional[int]: """simple docstring""" snake_case_ = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): snake_case_ = {} snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : Any ) ->str: """simple docstring""" if self.remove_space: snake_case_ = """ """.join(inputs.strip().split() ) else: snake_case_ = inputs snake_case_ = outputs.replace("""``""" , """\"""" ).replace("""''""" , """\"""" ) if not self.keep_accents: snake_case_ = unicodedata.normalize("""NFKD""" , UpperCAmelCase_ ) snake_case_ = """""".join([c for c in outputs if not unicodedata.combining(UpperCAmelCase_ )] ) if self.do_lower_case: snake_case_ = outputs.lower() return outputs def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : str ) ->List[str]: """simple docstring""" snake_case_ = self.preprocess_text(UpperCAmelCase_ ) snake_case_ = self.sp_model.encode(UpperCAmelCase_ , out_type=UpperCAmelCase_ ) snake_case_ = [] for piece in pieces: if len(UpperCAmelCase_ ) > 1 and piece[-1] == str(""",""" ) and piece[-2].isdigit(): snake_case_ = self.sp_model.EncodeAsPieces(piece[:-1].replace(UpperCAmelCase_ , """""" ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: snake_case_ = cur_pieces[1:] else: snake_case_ = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(UpperCAmelCase_ ) else: new_pieces.append(UpperCAmelCase_ ) return new_pieces def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : Optional[int] ) ->Dict: """simple docstring""" return self.sp_model.PieceToId(UpperCAmelCase_ ) def lowerCAmelCase ( self : str , UpperCAmelCase_ : Union[str, Any] ) ->Optional[int]: """simple docstring""" return self.sp_model.IdToPiece(UpperCAmelCase_ ) def lowerCAmelCase ( self : str , UpperCAmelCase_ : Dict ) ->Any: """simple docstring""" snake_case_ = [] snake_case_ = """""" snake_case_ = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(UpperCAmelCase_ ) + token snake_case_ = True snake_case_ = [] else: current_sub_tokens.append(UpperCAmelCase_ ) snake_case_ = False out_string += self.sp_model.decode(UpperCAmelCase_ ) return out_string.strip() def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ) ->List[int]: """simple docstring""" snake_case_ = [self.sep_token_id] snake_case_ = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None , UpperCAmelCase_ : bool = False ) ->List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=UpperCAmelCase_ , token_ids_a=UpperCAmelCase_ , already_has_special_tokens=UpperCAmelCase_ ) if token_ids_a is not None: return [1] + ([0] * len(UpperCAmelCase_ )) + [1] + ([0] * len(UpperCAmelCase_ )) + [1] return [1] + ([0] * len(UpperCAmelCase_ )) + [1] def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ) ->List[int]: """simple docstring""" snake_case_ = [self.sep_token_id] snake_case_ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def lowerCAmelCase ( self : str , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None ) ->Tuple[str]: """simple docstring""" if not os.path.isdir(UpperCAmelCase_ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return snake_case_ = os.path.join( UpperCAmelCase_ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCAmelCase_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , UpperCAmelCase_ ) elif not os.path.isfile(self.vocab_file ): with open(UpperCAmelCase_ , """wb""" ) as fi: snake_case_ = self.sp_model.serialized_model_proto() fi.write(UpperCAmelCase_ ) return (out_vocab_file,)
2
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging __SCREAMING_SNAKE_CASE : List[Any] = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Optional[int] = { 'uclanlp/visualbert-vqa': 'https://huggingface.co/uclanlp/visualbert-vqa/resolve/main/config.json', 'uclanlp/visualbert-vqa-pre': 'https://huggingface.co/uclanlp/visualbert-vqa-pre/resolve/main/config.json', 'uclanlp/visualbert-vqa-coco-pre': ( 'https://huggingface.co/uclanlp/visualbert-vqa-coco-pre/resolve/main/config.json' ), 'uclanlp/visualbert-vcr': 'https://huggingface.co/uclanlp/visualbert-vcr/resolve/main/config.json', 'uclanlp/visualbert-vcr-pre': 'https://huggingface.co/uclanlp/visualbert-vcr-pre/resolve/main/config.json', 'uclanlp/visualbert-vcr-coco-pre': ( 'https://huggingface.co/uclanlp/visualbert-vcr-coco-pre/resolve/main/config.json' ), 'uclanlp/visualbert-nlvr2': 'https://huggingface.co/uclanlp/visualbert-nlvr2/resolve/main/config.json', 'uclanlp/visualbert-nlvr2-pre': 'https://huggingface.co/uclanlp/visualbert-nlvr2-pre/resolve/main/config.json', 'uclanlp/visualbert-nlvr2-coco-pre': ( 'https://huggingface.co/uclanlp/visualbert-nlvr2-coco-pre/resolve/main/config.json' ) # See all VisualBERT models at https://huggingface.co/models?filter=visual_bert } class __A (UpperCamelCase_): '''simple docstring''' __lowercase: List[str] = """visual_bert""" def __init__( self : Optional[Any] , UpperCAmelCase_ : Optional[Any]=30_522 , UpperCAmelCase_ : str=768 , UpperCAmelCase_ : Tuple=512 , UpperCAmelCase_ : Any=12 , UpperCAmelCase_ : int=12 , UpperCAmelCase_ : Dict=3_072 , UpperCAmelCase_ : Optional[int]="gelu" , UpperCAmelCase_ : int=0.1 , UpperCAmelCase_ : Tuple=0.1 , UpperCAmelCase_ : List[Any]=512 , UpperCAmelCase_ : List[Any]=2 , UpperCAmelCase_ : Any=0.02 , UpperCAmelCase_ : Optional[int]=1E-12 , UpperCAmelCase_ : Dict=False , UpperCAmelCase_ : Dict=True , UpperCAmelCase_ : Optional[int]=1 , UpperCAmelCase_ : Union[str, Any]=0 , UpperCAmelCase_ : Dict=2 , **UpperCAmelCase_ : Optional[Any] , ) ->List[str]: """simple docstring""" super().__init__(pad_token_id=UpperCAmelCase_ , bos_token_id=UpperCAmelCase_ , eos_token_id=UpperCAmelCase_ , **UpperCAmelCase_ ) snake_case_ = vocab_size snake_case_ = max_position_embeddings snake_case_ = hidden_size snake_case_ = visual_embedding_dim snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = initializer_range snake_case_ = type_vocab_size snake_case_ = layer_norm_eps snake_case_ = bypass_transformer snake_case_ = special_visual_initialize
718
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE ) -> list: # bit count represents no. of bits in the gray code if bit_count < 0: raise ValueError("""The given input must be positive""" ) # get the generated string sequence snake_case_ = gray_code_sequence_string(_SCREAMING_SNAKE_CASE ) # # convert them to integers for i in range(len(_SCREAMING_SNAKE_CASE ) ): snake_case_ = int(sequence[i] , 2 ) return sequence def _a ( _SCREAMING_SNAKE_CASE ) -> list: # The approach is a recursive one # Base case achieved when either n = 0 or n=1 if bit_count == 0: return ["0"] if bit_count == 1: return ["0", "1"] snake_case_ = 1 << bit_count # defines the length of the sequence # 1<< n is equivalent to 2^n # recursive answer will generate answer for n-1 bits snake_case_ = gray_code_sequence_string(bit_count - 1 ) snake_case_ = [] # append 0 to first half of the smaller sequence generated for i in range(seq_len // 2 ): snake_case_ = """0""" + smaller_sequence[i] sequence.append(_SCREAMING_SNAKE_CASE ) # append 1 to second half ... start from the end of the list for i in reversed(range(seq_len // 2 ) ): snake_case_ = """1""" + smaller_sequence[i] sequence.append(_SCREAMING_SNAKE_CASE ) return sequence if __name__ == "__main__": import doctest doctest.testmod()
2
0
from __future__ import annotations def _a ( _SCREAMING_SNAKE_CASE ) -> Optional[Any]: snake_case_ = len(UpperCamelCase__ ) // 2 # choose the middle 3 elements snake_case_ = lst[m - 1 : m + 2] # if middle element is peak if three[1] > three[0] and three[1] > three[2]: return three[1] # if increasing, recurse on right elif three[0] < three[2]: if len(lst[:m] ) == 2: m -= 1 return peak(lst[m:] ) # decreasing else: if len(lst[:m] ) == 2: m += 1 return peak(lst[:m] ) if __name__ == "__main__": import doctest doctest.testmod()
719
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __SCREAMING_SNAKE_CASE : Optional[Any] = { 'configuration_megatron_bert': ['MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MegatronBertConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : Tuple = [ 'MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'MegatronBertForCausalLM', 'MegatronBertForMaskedLM', 'MegatronBertForMultipleChoice', 'MegatronBertForNextSentencePrediction', 'MegatronBertForPreTraining', 'MegatronBertForQuestionAnswering', 'MegatronBertForSequenceClassification', 'MegatronBertForTokenClassification', 'MegatronBertModel', 'MegatronBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_megatron_bert import MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MegatronBertConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_megatron_bert import ( MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, MegatronBertPreTrainedModel, ) else: import sys __SCREAMING_SNAKE_CASE : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
2
0
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE ) -> list[list]: snake_case_ = current_set.copy() for row_index, row in enumerate(lowerCamelCase__ ): snake_case_ = row[0] for column_index, column in enumerate(lowerCamelCase__ ): if magnitude == 0: snake_case_ = column continue snake_case_ = column / magnitude # Subtract to cancel term snake_case_ = current_set[0] snake_case_ = [first_row] snake_case_ = current_set[1::] for row in current_set: snake_case_ = [] # If first term is 0, it is already in form we want, so we preserve it if row[0] == 0: final_set.append(lowerCamelCase__ ) continue for column_index in range(len(lowerCamelCase__ ) ): temp_row.append(first_row[column_index] - row[column_index] ) final_set.append(lowerCamelCase__ ) # Create next recursion iteration set if len(final_set[0] ) != 3: snake_case_ = final_set[0] snake_case_ = [] snake_case_ = [] for row in final_set[1::]: current_first_column.append(row[0] ) next_iteration.append(row[1::] ) snake_case_ = simplify(lowerCamelCase__ ) for i in range(len(lowerCamelCase__ ) ): resultant[i].insert(0 , current_first_column[i] ) resultant.insert(0 , lowerCamelCase__ ) snake_case_ = resultant return final_set def _a ( _SCREAMING_SNAKE_CASE ) -> list: if len(lowerCamelCase__ ) == 0: raise IndexError("""solve_simultaneous() requires n lists of length n+1""" ) snake_case_ = len(lowerCamelCase__ ) + 1 if any(len(lowerCamelCase__ ) != _length for item in equations ): raise IndexError("""solve_simultaneous() requires n lists of length n+1""" ) for row in equations: if any(not isinstance(lowerCamelCase__ , (int, float) ) for column in row ): raise ValueError("""solve_simultaneous() requires lists of integers""" ) if len(lowerCamelCase__ ) == 1: return [equations[0][-1] / equations[0][0]] snake_case_ = equations.copy() if any(0 in row for row in data_set ): snake_case_ = data_set.copy() snake_case_ = [] for row_index, row in enumerate(lowerCamelCase__ ): if 0 not in row: snake_case_ = data_set.pop(lowerCamelCase__ ) break if not full_row: raise ValueError("""solve_simultaneous() requires at least 1 full equation""" ) data_set.insert(0 , lowerCamelCase__ ) snake_case_ = data_set.copy() snake_case_ = simplify(lowerCamelCase__ ) snake_case_ = simplified[::-1] snake_case_ = [] for row in simplified: snake_case_ = row[-1] if not solutions: if row[-2] == 0: solutions.append(0 ) continue solutions.append(current_solution / row[-2] ) continue snake_case_ = row.copy()[: len(lowerCamelCase__ ) - 1 :] while temp_row[0] == 0: temp_row.pop(0 ) if len(lowerCamelCase__ ) == 0: solutions.append(0 ) continue snake_case_ = temp_row[1::] snake_case_ = temp_row[::-1] for column_index, column in enumerate(lowerCamelCase__ ): current_solution -= column * solutions[column_index] solutions.append(lowerCamelCase__ ) snake_case_ = [] for item in solutions: final.append(float(round(lowerCamelCase__ , 5 ) ) ) return final[::-1] if __name__ == "__main__": import doctest doctest.testmod() __SCREAMING_SNAKE_CASE : Any = [ [2, 1, 1, 1, 1, 4], [1, 2, 1, 1, 1, 5], [1, 1, 2, 1, 1, 6], [1, 1, 1, 2, 1, 7], [1, 1, 1, 1, 2, 8], ] print(solve_simultaneous(eq)) print(solve_simultaneous([[4, 2]]))
720
"""simple docstring""" import argparse import json import os from pathlib import Path import requests import torch from transformers import JukeboxConfig, JukeboxModel from transformers.utils import logging logging.set_verbosity_info() __SCREAMING_SNAKE_CASE : str = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Optional[int] = 'https://openaipublic.azureedge.net/jukebox/models/' __SCREAMING_SNAKE_CASE : List[Any] = { 'jukebox-1b-lyrics': [ '5b/vqvae.pth.tar', '5b/prior_level_0.pth.tar', '5b/prior_level_1.pth.tar', '1b_lyrics/prior_level_2.pth.tar', ], 'jukebox-5b-lyrics': [ '5b/vqvae.pth.tar', '5b/prior_level_0.pth.tar', '5b/prior_level_1.pth.tar', '5b_lyrics/prior_level_2.pth.tar', ], } def _a ( _SCREAMING_SNAKE_CASE ) -> int: if key.endswith(""".model.1.bias""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.1.bias""" , """.conv1d_1.bias""" ) elif key.endswith(""".model.1.weight""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.1.weight""" , """.conv1d_1.weight""" ) elif key.endswith(""".model.3.bias""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.3.bias""" , """.conv1d_2.bias""" ) elif key.endswith(""".model.3.weight""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.3.weight""" , """.conv1d_2.weight""" ) if "conditioner_blocks.0." in key: snake_case_ = key.replace("""conditioner_blocks.0""" , """conditioner_blocks""" ) if "prime_prior" in key: snake_case_ = key.replace("""prime_prior""" , """encoder""" ) if ".emb." in key and "total" not in key and "absolute" not in key and "relative" not in key: snake_case_ = key.replace(""".emb.""" , """.""" ) if key.endswith("""k""" ): # replace vqvae.X.k with vqvae.X.codebook return key.replace(""".k""" , """.codebook""" ) if "y_emb." in key: return key.replace("""y_emb.""" , """metadata_embedding.""" ) if "x_emb.emb." in key: snake_case_ = key.replace("""0.x_emb.emb""" , """embed_tokens""" ) if "prime_state_ln" in key: return key.replace("""prime_state_ln""" , """encoder.final_layer_norm""" ) if ".ln" in key: return key.replace(""".ln""" , """.layer_norm""" ) if "_ln" in key: return key.replace("""_ln""" , """_layer_norm""" ) if "prime_state_proj" in key: return key.replace("""prime_state_proj""" , """encoder.proj_in""" ) if "prime_x_out" in key: return key.replace("""prime_x_out""" , """encoder.lm_head""" ) if "prior.x_out" in key: return key.replace("""x_out""" , """fc_proj_out""" ) if "x_emb" in key: return key.replace("""x_emb""" , """embed_tokens""" ) return key def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: snake_case_ = {} import re snake_case_ = re.compile(r"""encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)""" ) snake_case_ = re.compile( r"""encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""encoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)""" ) snake_case_ = re.compile( r"""decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""decoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""conditioner_blocks.(\d*).cond.model.(\d*).(\d).(bias|weight)""" ) snake_case_ = re.compile( r"""conditioner_blocks.(\d*).cond.model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""conditioner_blocks.(\d*).cond.model.(\d*).(bias|weight)""" ) for original_key, value in state_dict.items(): # rename vqvae.encoder keys if re_encoder_block_conv_in.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_encoder_block_conv_in.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) snake_case_ = f"""encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.{groups[-1]}""" snake_case_ = re_encoder_block_conv_in.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_encoder_block_resnet.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_encoder_block_resnet.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) snake_case_ = {"""1""": 1, """3""": 2}[groups[-2]] snake_case_ = f"""encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.""" snake_case_ = f"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}""" snake_case_ = prefix + resnet_block snake_case_ = re_encoder_block_resnet.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_encoder_block_proj_out.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_encoder_block_proj_out.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = f"""encoders.{groups[0]}.level_blocks.{groups[1]}.proj_out.{groups[-1]}""" snake_case_ = re_encoder_block_proj_out.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # rename vqvae.decoder keys elif re_decoder_block_conv_out.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_decoder_block_conv_out.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) - 2 snake_case_ = f"""decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.{groups[-1]}""" snake_case_ = re_decoder_block_conv_out.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_decoder_block_resnet.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_decoder_block_resnet.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) - 2 snake_case_ = {"""1""": 1, """3""": 2}[groups[-2]] snake_case_ = f"""decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.""" snake_case_ = f"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}""" snake_case_ = prefix + resnet_block snake_case_ = re_decoder_block_resnet.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_decoder_block_proj_in.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_decoder_block_proj_in.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = f"""decoders.{groups[0]}.level_blocks.{groups[1]}.proj_in.{groups[-1]}""" snake_case_ = re_decoder_block_proj_in.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # rename prior cond.model to upsampler.upsample_block and resnet elif re_prior_cond_conv_out.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_prior_cond_conv_out.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[1] ) * 2 + int(groups[2] ) - 2 snake_case_ = f"""conditioner_blocks.upsampler.upsample_block.{block_index}.{groups[-1]}""" snake_case_ = re_prior_cond_conv_out.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_prior_cond_resnet.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_prior_cond_resnet.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[1] ) * 2 + int(groups[2] ) - 2 snake_case_ = {"""1""": 1, """3""": 2}[groups[-2]] snake_case_ = f"""conditioner_blocks.upsampler.upsample_block.{block_index}.""" snake_case_ = f"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}""" snake_case_ = prefix + resnet_block snake_case_ = re_prior_cond_resnet.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_prior_cond_proj_in.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_prior_cond_proj_in.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = f"""conditioner_blocks.upsampler.proj_in.{groups[-1]}""" snake_case_ = re_prior_cond_proj_in.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # keep original key else: snake_case_ = original_key snake_case_ = replace_key(_SCREAMING_SNAKE_CASE ) if f"""{key_prefix}.{key}""" not in model_state_dict or key is None: print(f"""failed converting {original_key} to {key}, does not match""" ) # handle missmatched shape elif value.shape != model_state_dict[f"""{key_prefix}.{key}"""].shape: snake_case_ = model_state_dict[f"""{key_prefix}.{key}"""] print(f"""{original_key}-> {key} : \nshape {val.shape} and { value.shape}, do not match""" ) snake_case_ = original_key snake_case_ = original_key snake_case_ = value return new_dict @torch.no_grad() def _a ( _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> Optional[int]: for file in MODEL_MAPPING[model_name]: if not os.path.isfile(f"""{pytorch_dump_folder_path}/{file.split("/" )[-1]}""" ): snake_case_ = requests.get(f"""{PREFIX}{file}""" , allow_redirects=_SCREAMING_SNAKE_CASE ) os.makedirs(f"""{pytorch_dump_folder_path}/""" , exist_ok=_SCREAMING_SNAKE_CASE ) open(f"""{pytorch_dump_folder_path}/{file.split("/" )[-1]}""" , """wb""" ).write(r.content ) snake_case_ = MODEL_MAPPING[model_name.split("""/""" )[-1]] snake_case_ = JukeboxConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) snake_case_ = JukeboxModel(_SCREAMING_SNAKE_CASE ) snake_case_ = [] snake_case_ = {} for i, dict_name in enumerate(_SCREAMING_SNAKE_CASE ): snake_case_ = torch.load(f"""{pytorch_dump_folder_path}/{dict_name.split("/" )[-1]}""" )["""model"""] snake_case_ = {} for k in old_dic.keys(): if k.endswith(""".b""" ): snake_case_ = old_dic[k] elif k.endswith(""".w""" ): snake_case_ = old_dic[k] elif "level_2" not in dict_name and "cond.model." in k: snake_case_ = old_dic[k] else: snake_case_ = old_dic[k] snake_case_ = """vqvae""" if i == 0 else f"""priors.{3 - i}""" snake_case_ = fix_jukebox_keys(_SCREAMING_SNAKE_CASE , model.state_dict() , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) weight_dict.append(_SCREAMING_SNAKE_CASE ) snake_case_ = weight_dict.pop(0 ) model.vqvae.load_state_dict(_SCREAMING_SNAKE_CASE ) for i in range(len(_SCREAMING_SNAKE_CASE ) ): model.priors[i].load_state_dict(weight_dict[2 - i] ) Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) with open(f"""{pytorch_dump_folder_path}/mapping.json""" , """w""" ) as txtfile: json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) print(f"""Saving model {model_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) return weight_dict if __name__ == "__main__": __SCREAMING_SNAKE_CASE : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='jukebox-5b-lyrics', type=str, help='Name of the model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default='jukebox-5b-lyrics-converted', type=str, help='Path to the output PyTorch model directory.', ) __SCREAMING_SNAKE_CASE : str = parser.parse_args() convert_openai_checkpoint(args.model_name, args.pytorch_dump_folder_path)
2
0
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, 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 numpy as np import tensorflow as tf from transformers import ( TF_FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST, FlaubertConfig, TFFlaubertForMultipleChoice, TFFlaubertForQuestionAnsweringSimple, TFFlaubertForSequenceClassification, TFFlaubertForTokenClassification, TFFlaubertModel, TFFlaubertWithLMHeadModel, ) class __A : '''simple docstring''' def __init__( self : Union[str, Any] , UpperCAmelCase_ : Any , ) ->List[Any]: """simple docstring""" snake_case_ = parent snake_case_ = 13 snake_case_ = 7 snake_case_ = True snake_case_ = True snake_case_ = True snake_case_ = True snake_case_ = True snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = 2 snake_case_ = 99 snake_case_ = 0 snake_case_ = 32 snake_case_ = 2 snake_case_ = 4 snake_case_ = 0.1 snake_case_ = 0.1 snake_case_ = 512 snake_case_ = 16 snake_case_ = 2 snake_case_ = 0.02 snake_case_ = 3 snake_case_ = 4 snake_case_ = """last""" snake_case_ = True snake_case_ = None snake_case_ = 0 def lowerCAmelCase ( self : int ) ->Tuple: """simple docstring""" snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case_ = random_attention_mask([self.batch_size, self.seq_length] , dtype=tf.floataa ) snake_case_ = None if self.use_input_lengths: snake_case_ = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length snake_case_ = None if self.use_token_type_ids: snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) snake_case_ = None snake_case_ = None snake_case_ = None if self.use_labels: snake_case_ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) snake_case_ = ids_tensor([self.batch_size] , 2 , dtype=tf.floataa ) snake_case_ = ids_tensor([self.batch_size] , self.num_choices ) snake_case_ = FlaubertConfig( vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , bos_token_id=self.bos_token_id , ) return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : int , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[int] , ) ->Optional[Any]: """simple docstring""" snake_case_ = TFFlaubertModel(config=_SCREAMING_SNAKE_CASE ) snake_case_ = {"""input_ids""": input_ids, """lengths""": input_lengths, """langs""": token_type_ids} snake_case_ = model(_SCREAMING_SNAKE_CASE ) snake_case_ = [input_ids, input_mask] snake_case_ = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : Any , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : str , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : int , ) ->Tuple: """simple docstring""" snake_case_ = TFFlaubertWithLMHeadModel(_SCREAMING_SNAKE_CASE ) snake_case_ = {"""input_ids""": input_ids, """lengths""": input_lengths, """langs""": token_type_ids} snake_case_ = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Dict , UpperCAmelCase_ : str , ) ->Tuple: """simple docstring""" snake_case_ = TFFlaubertForQuestionAnsweringSimple(_SCREAMING_SNAKE_CASE ) snake_case_ = {"""input_ids""": input_ids, """lengths""": input_lengths} snake_case_ = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[int] , ) ->Union[str, Any]: """simple docstring""" snake_case_ = TFFlaubertForSequenceClassification(_SCREAMING_SNAKE_CASE ) snake_case_ = {"""input_ids""": input_ids, """lengths""": input_lengths} snake_case_ = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def lowerCAmelCase ( self : Any , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : str , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : str , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : str , ) ->Tuple: """simple docstring""" snake_case_ = self.num_labels snake_case_ = TFFlaubertForTokenClassification(config=_SCREAMING_SNAKE_CASE ) snake_case_ = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} snake_case_ = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowerCAmelCase ( self : List[Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : int , UpperCAmelCase_ : Any , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict , ) ->Any: """simple docstring""" snake_case_ = self.num_choices snake_case_ = TFFlaubertForMultipleChoice(config=_SCREAMING_SNAKE_CASE ) snake_case_ = tf.tile(tf.expand_dims(_SCREAMING_SNAKE_CASE , 1 ) , (1, self.num_choices, 1) ) snake_case_ = tf.tile(tf.expand_dims(_SCREAMING_SNAKE_CASE , 1 ) , (1, self.num_choices, 1) ) snake_case_ = tf.tile(tf.expand_dims(_SCREAMING_SNAKE_CASE , 1 ) , (1, self.num_choices, 1) ) snake_case_ = { """input_ids""": multiple_choice_inputs_ids, """attention_mask""": multiple_choice_input_mask, """token_type_ids""": multiple_choice_token_type_ids, } snake_case_ = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def lowerCAmelCase ( self : int ) ->int: """simple docstring""" snake_case_ = self.prepare_config_and_inputs() ( ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ) = config_and_inputs snake_case_ = { """input_ids""": input_ids, """token_type_ids""": token_type_ids, """langs""": token_type_ids, """lengths""": input_lengths, } return config, inputs_dict @require_tf class __A (snake_case__ , snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: List[Any] = ( ( TFFlaubertModel, TFFlaubertWithLMHeadModel, TFFlaubertForSequenceClassification, TFFlaubertForQuestionAnsweringSimple, TFFlaubertForTokenClassification, TFFlaubertForMultipleChoice, ) if is_tf_available() else () ) __lowercase: Dict = ( (TFFlaubertWithLMHeadModel,) if is_tf_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable __lowercase: Union[str, Any] = ( { """feature-extraction""": TFFlaubertModel, """fill-mask""": TFFlaubertWithLMHeadModel, """question-answering""": TFFlaubertForQuestionAnsweringSimple, """text-classification""": TFFlaubertForSequenceClassification, """token-classification""": TFFlaubertForTokenClassification, """zero-shot""": TFFlaubertForSequenceClassification, } if is_tf_available() else {} ) __lowercase: Any = False __lowercase: Optional[Any] = False def lowerCAmelCase ( self : str , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : List[Any] ) ->Optional[int]: """simple docstring""" if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith("""Fast""" ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def lowerCAmelCase ( self : List[Any] ) ->Dict: """simple docstring""" snake_case_ = TFFlaubertModelTester(self ) snake_case_ = ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , emb_dim=37 ) def lowerCAmelCase ( self : Union[str, Any] ) ->Union[str, Any]: """simple docstring""" self.config_tester.run_common_tests() def lowerCAmelCase ( self : Optional[int] ) ->Optional[int]: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_model(*_SCREAMING_SNAKE_CASE ) def lowerCAmelCase ( self : List[Any] ) ->List[str]: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_lm_head(*_SCREAMING_SNAKE_CASE ) def lowerCAmelCase ( self : Tuple ) ->Optional[Any]: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_qa(*_SCREAMING_SNAKE_CASE ) def lowerCAmelCase ( self : Any ) ->Any: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_sequence_classif(*_SCREAMING_SNAKE_CASE ) def lowerCAmelCase ( self : List[Any] ) ->int: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_for_token_classification(*_SCREAMING_SNAKE_CASE ) def lowerCAmelCase ( self : List[str] ) ->str: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_for_multiple_choice(*_SCREAMING_SNAKE_CASE ) @slow def lowerCAmelCase ( self : List[Any] ) ->Optional[int]: """simple docstring""" for model_name in TF_FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ = TFFlaubertModel.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) @require_tf @require_sentencepiece @require_tokenizers class __A (unittest.TestCase): '''simple docstring''' @slow def lowerCAmelCase ( self : Union[str, Any] ) ->Any: """simple docstring""" snake_case_ = TFFlaubertModel.from_pretrained("""jplu/tf-flaubert-small-cased""" ) snake_case_ = tf.convert_to_tensor( [[0, 158, 735, 2_592, 1_424, 6_727, 82, 1]] , dtype=tf.intaa , ) # "J'aime flaubert !" snake_case_ = model(_SCREAMING_SNAKE_CASE )[0] snake_case_ = tf.TensorShape((1, 8, 512) ) self.assertEqual(output.shape , _SCREAMING_SNAKE_CASE ) # compare the actual values for a slice. snake_case_ = tf.convert_to_tensor( [ [ [-1.8_768_773, -1.566_555, 0.27_072_418], [-1.6_920_038, -0.5_873_505, 1.9_329_599], [-2.9_563_985, -1.6_993_835, 1.7_972_052], ] ] , dtype=tf.floataa , ) self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4 ) )
721
"""simple docstring""" # XXX: we want transformers master here - in the absense of conftest manipulating sys.path: # hack it in for now: import sys from pathlib import Path __SCREAMING_SNAKE_CASE : Union[str, Any] = Path(__file__).resolve().parents[3] / 'src' sys.path.insert(1, str(git_repo_path)) import dataclasses # noqa import io # noqa import itertools # noqa import json # noqa import os # noqa import unittest # noqa from copy import deepcopy # noqa from parameterized import parameterized # noqa from transformers import TrainingArguments, is_torch_available # noqa from transformers.deepspeed import is_deepspeed_available # noqa from transformers.file_utils import WEIGHTS_NAME # noqa from transformers.testing_utils import ( # noqa CaptureLogger, ExtendSysPath, TestCasePlus, execute_subprocess_async, get_gpu_count, mockenv_context, require_deepspeed, require_torch_gpu, require_torch_multi_gpu, slow, ) from transformers.trainer_utils import set_seed # noqa set_seed(42) __SCREAMING_SNAKE_CASE : Dict = {'base': 'patrickvonplaten/wav2vec2_tiny_random', 'robust': 'patrickvonplaten/wav2vec2_tiny_random_robust'} __SCREAMING_SNAKE_CASE : Dict = 'zero2' __SCREAMING_SNAKE_CASE : List[Any] = 'zero3' __SCREAMING_SNAKE_CASE : int = [ZEROa, ZEROa] def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: # customize the test name generator function as we want both params to appear in the sub-test # name, as by default it shows only the first param snake_case_ = parameterized.to_safe_name("""_""".join(str(_SCREAMING_SNAKE_CASE ) for x in param.args ) ) return f"""{func.__name__}_{param_based_name}""" # Cartesian-product of zero stages with models to test __SCREAMING_SNAKE_CASE : Dict = list(itertools.product(stages, models.keys())) @slow @require_deepspeed @require_torch_gpu class __A (snake_case__): '''simple docstring''' @parameterized.expand(UpperCAmelCase_ , name_func=UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Union[str, Any] ) ->Any: """simple docstring""" self.run_and_check( stage=UpperCAmelCase_ , model=UpperCAmelCase_ , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) @require_torch_multi_gpu @parameterized.expand(UpperCAmelCase_ , name_func=UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[Any] ) ->Optional[Any]: """simple docstring""" self.run_and_check( stage=UpperCAmelCase_ , model=UpperCAmelCase_ , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) @parameterized.expand(UpperCAmelCase_ , name_func=UpperCAmelCase_ ) def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[int] ) ->List[str]: """simple docstring""" self.run_and_check( stage=UpperCAmelCase_ , model=UpperCAmelCase_ , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) @require_torch_multi_gpu @parameterized.expand(UpperCAmelCase_ , name_func=UpperCAmelCase_ ) def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : str , UpperCAmelCase_ : List[Any] ) ->Optional[int]: """simple docstring""" self.run_and_check( stage=UpperCAmelCase_ , model=UpperCAmelCase_ , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : Union[str, Any] ) ->Optional[int]: """simple docstring""" pass def lowerCAmelCase ( self : Any , UpperCAmelCase_ : str , UpperCAmelCase_ : str , UpperCAmelCase_ : int = 10 , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : bool = True , ) ->List[str]: """simple docstring""" snake_case_ = models[model] snake_case_ = self.run_trainer( stage=UpperCAmelCase_ , model_name=UpperCAmelCase_ , eval_steps=UpperCAmelCase_ , num_train_epochs=1 , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) self.do_checks(UpperCAmelCase_ ) return output_dir def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : str , UpperCAmelCase_ : int = 10 , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : bool = True , ) ->List[str]: """simple docstring""" snake_case_ = self.get_auto_remove_tmp_dir("""./xxx""" , after=UpperCAmelCase_ ) snake_case_ = F""" --model_name_or_path {model_name} --dataset_name hf-internal-testing/librispeech_asr_dummy --dataset_config_name clean --train_split_name validation --validation_split_name validation --output_dir {output_dir} --num_train_epochs {str(UpperCAmelCase_ )} --per_device_train_batch_size 2 --per_device_eval_batch_size 2 --evaluation_strategy steps --learning_rate 5e-4 --warmup_steps 8 --orthography timit --preprocessing_num_workers 1 --group_by_length --freeze_feature_extractor --report_to none --save_steps 0 --eval_steps {eval_steps} --report_to none """.split() if fpaa: args.extend(["""--fp16"""] ) # currently ds_config_wav2vec2_zero.json requires "zero_optimization.find_unused_parameters": true, # hence the separate config files snake_case_ = F"""--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json""".split() snake_case_ = [F"""{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py"""] snake_case_ = self.get_launcher(UpperCAmelCase_ ) snake_case_ = launcher + script + args + ds_args # keep for quick debug # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die execute_subprocess_async(UpperCAmelCase_ , env=self.get_env() ) return output_dir def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : Any=False ) ->Tuple: """simple docstring""" snake_case_ = min(2 , get_gpu_count() ) if distributed else 1 return F"""deepspeed --num_nodes 1 --num_gpus {num_gpus}""".split()
2
0
"""simple docstring""" import argparse import glob import importlib.util import os import re import black from doc_builder.style_doc import style_docstrings_in_code # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py __SCREAMING_SNAKE_CASE : List[str] = 'src/diffusers' __SCREAMING_SNAKE_CASE : List[Any] = '.' # This is to make sure the diffusers module imported is the one in the repo. __SCREAMING_SNAKE_CASE : Any = importlib.util.spec_from_file_location( 'diffusers', os.path.join(DIFFUSERS_PATH, '__init__.py'), submodule_search_locations=[DIFFUSERS_PATH], ) __SCREAMING_SNAKE_CASE : Optional[Any] = spec.loader.load_module() def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[Any]: return line.startswith(_SCREAMING_SNAKE_CASE ) or len(_SCREAMING_SNAKE_CASE ) <= 1 or re.search(r"""^\s*\)(\s*->.*:|:)\s*$""" , _SCREAMING_SNAKE_CASE ) is not None def _a ( _SCREAMING_SNAKE_CASE ) -> Optional[int]: snake_case_ = object_name.split(""".""" ) snake_case_ = 0 # First let's find the module where our object lives. snake_case_ = parts[i] while i < len(_SCREAMING_SNAKE_CASE ) and not os.path.isfile(os.path.join(_SCREAMING_SNAKE_CASE , f"""{module}.py""" ) ): i += 1 if i < len(_SCREAMING_SNAKE_CASE ): snake_case_ = os.path.join(_SCREAMING_SNAKE_CASE , parts[i] ) if i >= len(_SCREAMING_SNAKE_CASE ): raise ValueError(f"""`object_name` should begin with the name of a module of diffusers but got {object_name}.""" ) with open(os.path.join(_SCREAMING_SNAKE_CASE , f"""{module}.py""" ) , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: snake_case_ = f.readlines() # Now let's find the class / func in the code! snake_case_ = """""" snake_case_ = 0 for name in parts[i + 1 :]: while ( line_index < len(_SCREAMING_SNAKE_CASE ) and re.search(rf"""^{indent}(class|def)\s+{name}(\(|\:)""" , lines[line_index] ) is None ): line_index += 1 indent += " " line_index += 1 if line_index >= len(_SCREAMING_SNAKE_CASE ): raise ValueError(f""" {object_name} does not match any function or class in {module}.""" ) # We found the beginning of the class / func, now let's find the end (when the indent diminishes). snake_case_ = line_index while line_index < len(_SCREAMING_SNAKE_CASE ) and _should_continue(lines[line_index] , _SCREAMING_SNAKE_CASE ): line_index += 1 # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 snake_case_ = lines[start_index:line_index] return "".join(_SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE : Any = re.compile(R'^(\s*)#\s*Copied from\s+diffusers\.(\S+\.\S+)\s*($|\S.*$)') __SCREAMING_SNAKE_CASE : Optional[Any] = re.compile(R'^\s*(\S+)->(\S+)(\s+.*|$)') __SCREAMING_SNAKE_CASE : Any = re.compile(R'<FILL\s+[^>]*>') def _a ( _SCREAMING_SNAKE_CASE ) -> Tuple: snake_case_ = code.split("""\n""" ) snake_case_ = 0 while idx < len(_SCREAMING_SNAKE_CASE ) and len(lines[idx] ) == 0: idx += 1 if idx < len(_SCREAMING_SNAKE_CASE ): return re.search(r"""^(\s*)\S""" , lines[idx] ).groups()[0] return "" def _a ( _SCREAMING_SNAKE_CASE ) -> int: snake_case_ = len(get_indent(_SCREAMING_SNAKE_CASE ) ) > 0 if has_indent: snake_case_ = f"""class Bla:\n{code}""" snake_case_ = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=119 , preview=_SCREAMING_SNAKE_CASE ) snake_case_ = black.format_str(_SCREAMING_SNAKE_CASE , mode=_SCREAMING_SNAKE_CASE ) snake_case_ , snake_case_ = style_docstrings_in_code(_SCREAMING_SNAKE_CASE ) return result[len("""class Bla:\n""" ) :] if has_indent else result def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) -> Optional[Any]: with open(_SCREAMING_SNAKE_CASE , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: snake_case_ = f.readlines() snake_case_ = [] snake_case_ = 0 # Not a for loop cause `lines` is going to change (if `overwrite=True`). while line_index < len(_SCREAMING_SNAKE_CASE ): snake_case_ = _re_copy_warning.search(lines[line_index] ) if search is None: line_index += 1 continue # There is some copied code here, let's retrieve the original. snake_case_ , snake_case_ , snake_case_ = search.groups() snake_case_ = find_code_in_diffusers(_SCREAMING_SNAKE_CASE ) snake_case_ = get_indent(_SCREAMING_SNAKE_CASE ) snake_case_ = line_index + 1 if indent == theoretical_indent else line_index + 2 snake_case_ = theoretical_indent snake_case_ = start_index # Loop to check the observed code, stop when indentation diminishes or if we see a End copy comment. snake_case_ = True while line_index < len(_SCREAMING_SNAKE_CASE ) and should_continue: line_index += 1 if line_index >= len(_SCREAMING_SNAKE_CASE ): break snake_case_ = lines[line_index] snake_case_ = _should_continue(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) and re.search(f"""^{indent}# End copy""" , _SCREAMING_SNAKE_CASE ) is None # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 snake_case_ = lines[start_index:line_index] snake_case_ = """""".join(_SCREAMING_SNAKE_CASE ) # Remove any nested `Copied from` comments to avoid circular copies snake_case_ = [line for line in theoretical_code.split("""\n""" ) if _re_copy_warning.search(_SCREAMING_SNAKE_CASE ) is None] snake_case_ = """\n""".join(_SCREAMING_SNAKE_CASE ) # Before comparing, use the `replace_pattern` on the original code. if len(_SCREAMING_SNAKE_CASE ) > 0: snake_case_ = replace_pattern.replace("""with""" , """""" ).split(""",""" ) snake_case_ = [_re_replace_pattern.search(_SCREAMING_SNAKE_CASE ) for p in patterns] for pattern in patterns: if pattern is None: continue snake_case_ , snake_case_ , snake_case_ = pattern.groups() snake_case_ = re.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if option.strip() == "all-casing": snake_case_ = re.sub(obja.lower() , obja.lower() , _SCREAMING_SNAKE_CASE ) snake_case_ = re.sub(obja.upper() , obja.upper() , _SCREAMING_SNAKE_CASE ) # Blackify after replacement. To be able to do that, we need the header (class or function definition) # from the previous line snake_case_ = blackify(lines[start_index - 1] + theoretical_code ) snake_case_ = theoretical_code[len(lines[start_index - 1] ) :] # Test for a diff and act accordingly. if observed_code != theoretical_code: diffs.append([object_name, start_index] ) if overwrite: snake_case_ = lines[:start_index] + [theoretical_code] + lines[line_index:] snake_case_ = start_index + 1 if overwrite and len(_SCREAMING_SNAKE_CASE ) > 0: # Warn the user a file has been modified. print(f"""Detected changes, rewriting {filename}.""" ) with open(_SCREAMING_SNAKE_CASE , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f: f.writelines(_SCREAMING_SNAKE_CASE ) return diffs def _a ( _SCREAMING_SNAKE_CASE = False ) -> str: snake_case_ = glob.glob(os.path.join(_SCREAMING_SNAKE_CASE , """**/*.py""" ) , recursive=_SCREAMING_SNAKE_CASE ) snake_case_ = [] for filename in all_files: snake_case_ = is_copy_consistent(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) diffs += [f"""- {filename}: copy does not match {d[0]} at line {d[1]}""" for d in new_diffs] if not overwrite and len(_SCREAMING_SNAKE_CASE ) > 0: snake_case_ = """\n""".join(_SCREAMING_SNAKE_CASE ) raise Exception( """Found the following copy inconsistencies:\n""" + diff + """\nRun `make fix-copies` or `python utils/check_copies.py --fix_and_overwrite` to fix them.""" ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : Optional[int] = argparse.ArgumentParser() parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.') __SCREAMING_SNAKE_CASE : List[str] = parser.parse_args() check_copies(args.fix_and_overwrite)
700
"""simple docstring""" import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, Features, Value from .base import TaskTemplate @dataclass(frozen=snake_case__) class __A (snake_case__): '''simple docstring''' __lowercase: str = field(default="""automatic-speech-recognition""" , metadata={"""include_in_asdict_even_if_is_default""": True}) __lowercase: ClassVar[Features] = Features({"""audio""": Audio()}) __lowercase: ClassVar[Features] = Features({"""transcription""": Value("""string""")}) __lowercase: str = "audio" __lowercase: str = "transcription" def lowerCAmelCase ( self : List[Any] , UpperCAmelCase_ : Any ) ->int: """simple docstring""" if self.audio_column not in features: raise ValueError(F"""Column {self.audio_column} is not present in features.""" ) if not isinstance(features[self.audio_column] , UpperCAmelCase_ ): raise ValueError(F"""Column {self.audio_column} is not an Audio type.""" ) snake_case_ = copy.deepcopy(self ) snake_case_ = self.input_schema.copy() snake_case_ = features[self.audio_column] snake_case_ = input_schema return task_template @property def lowerCAmelCase ( self : List[str] ) ->Dict[str, str]: """simple docstring""" return {self.audio_column: "audio", self.transcription_column: "transcription"}
2
0
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE = 100 ) -> int: snake_case_ = set() snake_case_ = 0 snake_case_ = n + 1 # maximum limit for a in range(2 , _SCREAMING_SNAKE_CASE ): for b in range(2 , _SCREAMING_SNAKE_CASE ): snake_case_ = a**b # calculates the current power collect_powers.add(_SCREAMING_SNAKE_CASE ) # adds the result to the set return len(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": print('''Number of terms ''', solution(int(str(input()).strip())))
701
"""simple docstring""" from functools import reduce __SCREAMING_SNAKE_CASE : Tuple = ( '73167176531330624919225119674426574742355349194934' '96983520312774506326239578318016984801869478851843' '85861560789112949495459501737958331952853208805511' '12540698747158523863050715693290963295227443043557' '66896648950445244523161731856403098711121722383113' '62229893423380308135336276614282806444486645238749' '30358907296290491560440772390713810515859307960866' '70172427121883998797908792274921901699720888093776' '65727333001053367881220235421809751254540594752243' '52584907711670556013604839586446706324415722155397' '53697817977846174064955149290862569321978468622482' '83972241375657056057490261407972968652414535100474' '82166370484403199890008895243450658541227588666881' '16427171479924442928230863465674813919123162824586' '17866458359124566529476545682848912883142607690042' '24219022671055626321111109370544217506941658960408' '07198403850962455444362981230987879927244284909188' '84580156166097919133875499200524063689912560717606' '05886116467109405077541002256983155200055935729725' '71636269561882670428252483600823257530420752963450' ) def _a ( _SCREAMING_SNAKE_CASE = N ) -> int: return max( # mypy cannot properly interpret reduce int(reduce(lambda _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : str(int(_SCREAMING_SNAKE_CASE ) * int(_SCREAMING_SNAKE_CASE ) ) , n[i : i + 13] ) ) for i in range(len(_SCREAMING_SNAKE_CASE ) - 12 ) ) if __name__ == "__main__": print(f"""{solution() = }""")
2
0
"""simple docstring""" __SCREAMING_SNAKE_CASE : Dict = [ 'VerificationMode', 'Version', 'disable_progress_bar', 'enable_progress_bar', 'is_progress_bar_enabled', 'experimental', ] from .info_utils import VerificationMode from .logging import disable_progress_bar, enable_progress_bar, is_progress_bar_enabled from .version import Version from .experimental import experimental
702
"""simple docstring""" from ....configuration_utils import PretrainedConfig from ....utils import logging __SCREAMING_SNAKE_CASE : str = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : str = { 'speechbrain/m-ctc-t-large': 'https://huggingface.co/speechbrain/m-ctc-t-large/resolve/main/config.json', # See all M-CTC-T models at https://huggingface.co/models?filter=mctct } class __A (snake_case__): '''simple docstring''' __lowercase: Any = """mctct""" def __init__( self : Dict , UpperCAmelCase_ : List[Any]=8_065 , UpperCAmelCase_ : Tuple=1_536 , UpperCAmelCase_ : Optional[Any]=36 , UpperCAmelCase_ : int=6_144 , UpperCAmelCase_ : Dict=4 , UpperCAmelCase_ : Any=384 , UpperCAmelCase_ : List[str]=920 , UpperCAmelCase_ : Any=1E-5 , UpperCAmelCase_ : Any=0.3 , UpperCAmelCase_ : Tuple="relu" , UpperCAmelCase_ : Union[str, Any]=0.02 , UpperCAmelCase_ : Dict=0.3 , UpperCAmelCase_ : str=0.3 , UpperCAmelCase_ : Any=1 , UpperCAmelCase_ : Any=0 , UpperCAmelCase_ : int=2 , UpperCAmelCase_ : str=1 , UpperCAmelCase_ : Tuple=0.3 , UpperCAmelCase_ : Optional[Any]=1 , UpperCAmelCase_ : Optional[Any]=(7,) , UpperCAmelCase_ : Optional[Any]=(3,) , UpperCAmelCase_ : List[str]=80 , UpperCAmelCase_ : Tuple=1 , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : List[str]="sum" , UpperCAmelCase_ : Union[str, Any]=False , **UpperCAmelCase_ : Any , ) ->Dict: """simple docstring""" super().__init__(**UpperCAmelCase_ , pad_token_id=UpperCAmelCase_ , bos_token_id=UpperCAmelCase_ , eos_token_id=UpperCAmelCase_ ) snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = intermediate_size snake_case_ = num_attention_heads snake_case_ = attention_head_dim snake_case_ = max_position_embeddings snake_case_ = layer_norm_eps snake_case_ = layerdrop snake_case_ = hidden_act snake_case_ = initializer_range snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = pad_token_id snake_case_ = bos_token_id snake_case_ = eos_token_id snake_case_ = conv_glu_dim snake_case_ = conv_dropout snake_case_ = num_conv_layers snake_case_ = input_feat_per_channel snake_case_ = input_channels snake_case_ = conv_channels snake_case_ = ctc_loss_reduction snake_case_ = ctc_zero_infinity # prevents config testing fail with exporting to json snake_case_ = list(UpperCAmelCase_ ) snake_case_ = list(UpperCAmelCase_ ) if len(self.conv_kernel ) != self.num_conv_layers: raise ValueError( """Configuration for convolutional module is incorrect. """ """It is required that `len(config.conv_kernel)` == `config.num_conv_layers` """ F"""but is `len(config.conv_kernel) = {len(self.conv_kernel )}`, """ F"""`config.num_conv_layers = {self.num_conv_layers}`.""" )
2
0
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE ) -> list: if any(not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) or x < 0 for x in sequence ): raise TypeError("""Sequence must be list of non-negative integers""" ) for _ in range(len(_SCREAMING_SNAKE_CASE ) ): for i, (rod_upper, rod_lower) in enumerate(zip(_SCREAMING_SNAKE_CASE , sequence[1:] ) ): if rod_upper > rod_lower: sequence[i] -= rod_upper - rod_lower sequence[i + 1] += rod_upper - rod_lower return sequence if __name__ == "__main__": assert bead_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5] assert bead_sort([7, 9, 4, 3, 5]) == [3, 4, 5, 7, 9]
703
"""simple docstring""" from math import factorial def _a ( _SCREAMING_SNAKE_CASE = 100 ) -> int: return sum(int(_SCREAMING_SNAKE_CASE ) for x in str(factorial(_SCREAMING_SNAKE_CASE ) ) ) if __name__ == "__main__": print(solution(int(input('Enter the Number: ').strip())))
2
0
"""simple docstring""" import argparse import torch from torch import nn from transformers import MBartConfig, MBartForConditionalGeneration def _a ( _SCREAMING_SNAKE_CASE ) -> str: '''simple docstring''' snake_case_ = [ """encoder.version""", """decoder.version""", """model.encoder.version""", """model.decoder.version""", """_float_tensor""", """decoder.output_projection.weight""", ] for k in ignore_keys: state_dict.pop(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: '''simple docstring''' snake_case_ , snake_case_ = emb.weight.shape snake_case_ = nn.Linear(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , bias=_SCREAMING_SNAKE_CASE ) snake_case_ = emb.weight.data return lin_layer def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE="facebook/mbart-large-en-ro" , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=False ) -> Tuple: '''simple docstring''' snake_case_ = torch.load(_SCREAMING_SNAKE_CASE , map_location="""cpu""" )["""model"""] remove_ignore_keys_(_SCREAMING_SNAKE_CASE ) snake_case_ = state_dict["""encoder.embed_tokens.weight"""].shape[0] snake_case_ = MBartConfig.from_pretrained(_SCREAMING_SNAKE_CASE , vocab_size=_SCREAMING_SNAKE_CASE ) if mbart_aa and finetuned: snake_case_ = """relu""" snake_case_ = state_dict["""decoder.embed_tokens.weight"""] snake_case_ = MBartForConditionalGeneration(_SCREAMING_SNAKE_CASE ) model.model.load_state_dict(_SCREAMING_SNAKE_CASE ) if finetuned: snake_case_ = make_linear_from_emb(model.model.shared ) return model if __name__ == "__main__": __SCREAMING_SNAKE_CASE : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( 'fairseq_path', type=str, help='bart.large, bart.large.cnn or a path to a model.pt on local filesystem.' ) parser.add_argument('pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument( '--hf_config', default='facebook/mbart-large-cc25', type=str, help='Which huggingface architecture to use: mbart-large', ) parser.add_argument('--mbart_50', action='store_true', help='whether the model is mMART-50 checkpoint') parser.add_argument('--finetuned', action='store_true', help='whether the model is a fine-tuned checkpoint') __SCREAMING_SNAKE_CASE : Dict = parser.parse_args() __SCREAMING_SNAKE_CASE : Any = convert_fairseq_mbart_checkpoint_from_disk( args.fairseq_path, hf_config_path=args.hf_config, finetuned=args.finetuned, mbart_aa=args.mbart_aa ) model.save_pretrained(args.pytorch_dump_folder_path)
704
"""simple docstring""" import unittest import torch from diffusers import VQModel from diffusers.utils import floats_tensor, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class __A (snake_case__ , snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: str = VQModel __lowercase: Union[str, Any] = """sample""" @property def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : List[str]=(32, 32) ) ->Tuple: """simple docstring""" snake_case_ = 4 snake_case_ = 3 snake_case_ = floats_tensor((batch_size, num_channels) + sizes ).to(UpperCAmelCase_ ) return {"sample": image} @property def lowerCAmelCase ( self : Tuple ) ->str: """simple docstring""" return (3, 32, 32) @property def lowerCAmelCase ( self : List[Any] ) ->Any: """simple docstring""" return (3, 32, 32) def lowerCAmelCase ( self : Optional[int] ) ->Dict: """simple docstring""" snake_case_ = { """block_out_channels""": [32, 64], """in_channels""": 3, """out_channels""": 3, """down_block_types""": ["""DownEncoderBlock2D""", """DownEncoderBlock2D"""], """up_block_types""": ["""UpDecoderBlock2D""", """UpDecoderBlock2D"""], """latent_channels""": 3, } snake_case_ = self.dummy_input return init_dict, inputs_dict def lowerCAmelCase ( self : List[str] ) ->Dict: """simple docstring""" pass def lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" pass def lowerCAmelCase ( self : Any ) ->Union[str, Any]: """simple docstring""" snake_case_ , snake_case_ = VQModel.from_pretrained("""fusing/vqgan-dummy""" , output_loading_info=UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) self.assertEqual(len(loading_info["""missing_keys"""] ) , 0 ) model.to(UpperCAmelCase_ ) snake_case_ = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def lowerCAmelCase ( self : Tuple ) ->Optional[Any]: """simple docstring""" snake_case_ = VQModel.from_pretrained("""fusing/vqgan-dummy""" ) model.to(UpperCAmelCase_ ).eval() torch.manual_seed(0 ) if torch.cuda.is_available(): torch.cuda.manual_seed_all(0 ) snake_case_ = torch.randn(1 , model.config.in_channels , model.config.sample_size , model.config.sample_size ) snake_case_ = image.to(UpperCAmelCase_ ) with torch.no_grad(): snake_case_ = model(UpperCAmelCase_ ).sample snake_case_ = output[0, -1, -3:, -3:].flatten().cpu() # fmt: off snake_case_ = torch.tensor([-0.0_153, -0.4_044, -0.1_880, -0.5_161, -0.2_418, -0.4_072, -0.1_612, -0.0_633, -0.0_143] ) # fmt: on self.assertTrue(torch.allclose(UpperCAmelCase_ , UpperCAmelCase_ , atol=1E-3 ) )
2
0
"""simple docstring""" from __future__ import annotations def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> set[str]: snake_case_ , snake_case_ = set(_SCREAMING_SNAKE_CASE ), [start] while stack: snake_case_ = stack.pop() explored.add(_SCREAMING_SNAKE_CASE ) # Differences from BFS: # 1) pop last element instead of first one # 2) add adjacent elements to stack without exploring them for adj in reversed(graph[v] ): if adj not in explored: stack.append(_SCREAMING_SNAKE_CASE ) return explored __SCREAMING_SNAKE_CASE : List[str] = { 'A': ['B', 'C', 'D'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F'], 'D': ['B', 'D'], 'E': ['B', 'F'], 'F': ['C', 'E', 'G'], 'G': ['F'], } if __name__ == "__main__": import doctest doctest.testmod() print(depth_first_search(G, 'A'))
705
"""simple docstring""" import gc import random import unittest import numpy as np import torch from diffusers import ( DDIMScheduler, KandinskyVaaControlnetPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) 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 from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class __A (snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Dict = KandinskyVaaControlnetPipeline __lowercase: str = ["""image_embeds""", """negative_image_embeds""", """hint"""] __lowercase: List[str] = ["""image_embeds""", """negative_image_embeds""", """hint"""] __lowercase: Union[str, Any] = [ """generator""", """height""", """width""", """latents""", """guidance_scale""", """num_inference_steps""", """return_dict""", """guidance_scale""", """num_images_per_prompt""", """output_type""", """return_dict""", ] __lowercase: Tuple = False @property def lowerCAmelCase ( self : Any ) ->Union[str, Any]: """simple docstring""" return 32 @property def lowerCAmelCase ( self : Optional[Any] ) ->Union[str, Any]: """simple docstring""" return 32 @property def lowerCAmelCase ( self : int ) ->List[str]: """simple docstring""" return self.time_input_dim @property def lowerCAmelCase ( self : Union[str, Any] ) ->Union[str, Any]: """simple docstring""" return self.time_input_dim * 4 @property def lowerCAmelCase ( self : Dict ) ->Optional[int]: """simple docstring""" return 100 @property def lowerCAmelCase ( self : str ) ->List[Any]: """simple docstring""" torch.manual_seed(0 ) snake_case_ = { """in_channels""": 8, # Out channels is double in channels because predicts mean and variance """out_channels""": 8, """addition_embed_type""": """image_hint""", """down_block_types""": ("""ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D"""), """up_block_types""": ("""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""), """mid_block_type""": """UNetMidBlock2DSimpleCrossAttn""", """block_out_channels""": (self.block_out_channels_a, self.block_out_channels_a * 2), """layers_per_block""": 1, """encoder_hid_dim""": self.text_embedder_hidden_size, """encoder_hid_dim_type""": """image_proj""", """cross_attention_dim""": self.cross_attention_dim, """attention_head_dim""": 4, """resnet_time_scale_shift""": """scale_shift""", """class_embed_type""": None, } snake_case_ = UNetaDConditionModel(**UpperCAmelCase_ ) return model @property def lowerCAmelCase ( self : Any ) ->Optional[Any]: """simple docstring""" return { "block_out_channels": [32, 32, 64, 64], "down_block_types": [ "DownEncoderBlock2D", "DownEncoderBlock2D", "DownEncoderBlock2D", "AttnDownEncoderBlock2D", ], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": ["AttnUpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"], "vq_embed_dim": 4, } @property def lowerCAmelCase ( self : Any ) ->int: """simple docstring""" torch.manual_seed(0 ) snake_case_ = VQModel(**self.dummy_movq_kwargs ) return model def lowerCAmelCase ( self : Dict ) ->str: """simple docstring""" snake_case_ = self.dummy_unet snake_case_ = self.dummy_movq snake_case_ = DDIMScheduler( num_train_timesteps=1_000 , beta_schedule="""linear""" , beta_start=0.00_085 , beta_end=0.012 , clip_sample=UpperCAmelCase_ , set_alpha_to_one=UpperCAmelCase_ , steps_offset=1 , prediction_type="""epsilon""" , thresholding=UpperCAmelCase_ , ) snake_case_ = { """unet""": unet, """scheduler""": scheduler, """movq""": movq, } return components def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[Any]=0 ) ->List[str]: """simple docstring""" snake_case_ = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(UpperCAmelCase_ ) ).to(UpperCAmelCase_ ) snake_case_ = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( UpperCAmelCase_ ) # create hint snake_case_ = floats_tensor((1, 3, 64, 64) , rng=random.Random(UpperCAmelCase_ ) ).to(UpperCAmelCase_ ) if str(UpperCAmelCase_ ).startswith("""mps""" ): snake_case_ = torch.manual_seed(UpperCAmelCase_ ) else: snake_case_ = torch.Generator(device=UpperCAmelCase_ ).manual_seed(UpperCAmelCase_ ) snake_case_ = { """image_embeds""": image_embeds, """negative_image_embeds""": negative_image_embeds, """hint""": hint, """generator""": generator, """height""": 64, """width""": 64, """guidance_scale""": 4.0, """num_inference_steps""": 2, """output_type""": """np""", } return inputs def lowerCAmelCase ( self : List[str] ) ->List[Any]: """simple docstring""" snake_case_ = """cpu""" snake_case_ = self.get_dummy_components() snake_case_ = self.pipeline_class(**UpperCAmelCase_ ) snake_case_ = pipe.to(UpperCAmelCase_ ) pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) snake_case_ = pipe(**self.get_dummy_inputs(UpperCAmelCase_ ) ) snake_case_ = output.images snake_case_ = pipe( **self.get_dummy_inputs(UpperCAmelCase_ ) , return_dict=UpperCAmelCase_ , )[0] snake_case_ = image[0, -3:, -3:, -1] snake_case_ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) snake_case_ = np.array( [0.6_959_826, 0.868_279, 0.7_558_092, 0.68_769_467, 0.85_805_804, 0.65_977_496, 0.44_885_302, 0.5_959_111, 0.4_251_595] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 ), F""" expected_slice {expected_slice}, but got {image_slice.flatten()}""" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 ), F""" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}""" @slow @require_torch_gpu class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : List[Any] ) ->Union[str, Any]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCAmelCase ( self : List[str] ) ->List[str]: """simple docstring""" snake_case_ = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinskyv22/kandinskyv22_controlnet_robotcat_fp16.npy""" ) snake_case_ = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinskyv22/hint_image_cat.png""" ) snake_case_ = torch.from_numpy(np.array(UpperCAmelCase_ ) ).float() / 255.0 snake_case_ = hint.permute(2 , 0 , 1 ).unsqueeze(0 ) snake_case_ = KandinskyVaaPriorPipeline.from_pretrained( """kandinsky-community/kandinsky-2-2-prior""" , torch_dtype=torch.floataa ) pipe_prior.to(UpperCAmelCase_ ) snake_case_ = KandinskyVaaControlnetPipeline.from_pretrained( """kandinsky-community/kandinsky-2-2-controlnet-depth""" , torch_dtype=torch.floataa ) snake_case_ = pipeline.to(UpperCAmelCase_ ) pipeline.set_progress_bar_config(disable=UpperCAmelCase_ ) snake_case_ = """A robot, 4k photo""" snake_case_ = torch.Generator(device="""cuda""" ).manual_seed(0 ) snake_case_ , snake_case_ = pipe_prior( UpperCAmelCase_ , generator=UpperCAmelCase_ , num_inference_steps=5 , negative_prompt="""""" , ).to_tuple() snake_case_ = torch.Generator(device="""cuda""" ).manual_seed(0 ) snake_case_ = pipeline( image_embeds=UpperCAmelCase_ , negative_image_embeds=UpperCAmelCase_ , hint=UpperCAmelCase_ , generator=UpperCAmelCase_ , num_inference_steps=100 , output_type="""np""" , ) snake_case_ = output.images[0] assert image.shape == (512, 512, 3) assert_mean_pixel_difference(UpperCAmelCase_ , UpperCAmelCase_ )
2
0
"""simple docstring""" class __A : '''simple docstring''' def __init__( self : Optional[Any] , UpperCAmelCase_ : list[int] ) ->None: """simple docstring""" snake_case_ = len(UpperCAmelCase_ ) snake_case_ = [0] * len_array if len_array > 0: snake_case_ = array[0] for i in range(1 , UpperCAmelCase_ ): snake_case_ = self.prefix_sum[i - 1] + array[i] def lowerCAmelCase ( self : int , UpperCAmelCase_ : int , UpperCAmelCase_ : int ) ->int: """simple docstring""" if start == 0: return self.prefix_sum[end] return self.prefix_sum[end] - self.prefix_sum[start - 1] def lowerCAmelCase ( self : Optional[Any] , UpperCAmelCase_ : int ) ->bool: """simple docstring""" snake_case_ = {0} for sum_item in self.prefix_sum: if sum_item - target_sum in sums: return True sums.add(UpperCAmelCase_ ) return False if __name__ == "__main__": import doctest doctest.testmod()
706
"""simple docstring""" from __future__ import annotations from collections import deque class __A : '''simple docstring''' def __init__( self : List[Any] , UpperCAmelCase_ : list[str] ) ->List[Any]: """simple docstring""" snake_case_ = [] self.adlist.append( {"""value""": """""", """next_states""": [], """fail_state""": 0, """output""": []} ) for keyword in keywords: self.add_keyword(UpperCAmelCase_ ) self.set_fail_transitions() def lowerCAmelCase ( self : int , UpperCAmelCase_ : int , UpperCAmelCase_ : str ) ->int | None: """simple docstring""" for state in self.adlist[current_state]["next_states"]: if char == self.adlist[state]["value"]: return state return None def lowerCAmelCase ( self : int , UpperCAmelCase_ : str ) ->None: """simple docstring""" snake_case_ = 0 for character in keyword: snake_case_ = self.find_next_state(UpperCAmelCase_ , UpperCAmelCase_ ) if next_state is None: self.adlist.append( { """value""": character, """next_states""": [], """fail_state""": 0, """output""": [], } ) self.adlist[current_state]["next_states"].append(len(self.adlist ) - 1 ) snake_case_ = len(self.adlist ) - 1 else: snake_case_ = next_state self.adlist[current_state]["output"].append(UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->None: """simple docstring""" snake_case_ = deque() for node in self.adlist[0]["next_states"]: q.append(UpperCAmelCase_ ) snake_case_ = 0 while q: snake_case_ = q.popleft() for child in self.adlist[r]["next_states"]: q.append(UpperCAmelCase_ ) snake_case_ = self.adlist[r]["""fail_state"""] while ( self.find_next_state(UpperCAmelCase_ , self.adlist[child]["""value"""] ) is None and state != 0 ): snake_case_ = self.adlist[state]["""fail_state"""] snake_case_ = self.find_next_state( UpperCAmelCase_ , self.adlist[child]["""value"""] ) if self.adlist[child]["fail_state"] is None: snake_case_ = 0 snake_case_ = ( self.adlist[child]["""output"""] + self.adlist[self.adlist[child]["""fail_state"""]]["""output"""] ) def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : str ) ->dict[str, list[int]]: """simple docstring""" snake_case_ = {} # returns a dict with keywords and list of its occurrences snake_case_ = 0 for i in range(len(UpperCAmelCase_ ) ): while ( self.find_next_state(UpperCAmelCase_ , string[i] ) is None and current_state != 0 ): snake_case_ = self.adlist[current_state]["""fail_state"""] snake_case_ = self.find_next_state(UpperCAmelCase_ , string[i] ) if next_state is None: snake_case_ = 0 else: snake_case_ = next_state for key in self.adlist[current_state]["output"]: if key not in result: snake_case_ = [] result[key].append(i - len(UpperCAmelCase_ ) + 1 ) return result if __name__ == "__main__": import doctest doctest.testmod()
2
0
"""simple docstring""" import pprint import requests __SCREAMING_SNAKE_CASE : Tuple = 'https://zenquotes.io/api' def _a ( ) -> list: return requests.get(API_ENDPOINT_URL + """/today""" ).json() def _a ( ) -> list: return requests.get(API_ENDPOINT_URL + """/random""" ).json() if __name__ == "__main__": __SCREAMING_SNAKE_CASE : Optional[int] = random_quotes() pprint.pprint(response)
707
"""simple docstring""" import inspect import unittest from transformers import ConvNextVaConfig from transformers.models.auto import get_values from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES 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 transformers import ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __A : '''simple docstring''' def __init__( self : Optional[int] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[int]=13 , UpperCAmelCase_ : str=32 , UpperCAmelCase_ : List[Any]=3 , UpperCAmelCase_ : Optional[Any]=4 , UpperCAmelCase_ : Dict=[10, 20, 30, 40] , UpperCAmelCase_ : List[Any]=[2, 2, 3, 2] , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : Any=37 , UpperCAmelCase_ : str="gelu" , UpperCAmelCase_ : Optional[int]=10 , UpperCAmelCase_ : Dict=0.02 , UpperCAmelCase_ : int=["stage2", "stage3", "stage4"] , UpperCAmelCase_ : Optional[int]=[2, 3, 4] , UpperCAmelCase_ : List[str]=None , ) ->Union[str, Any]: """simple docstring""" snake_case_ = parent snake_case_ = batch_size snake_case_ = image_size snake_case_ = num_channels snake_case_ = num_stages snake_case_ = hidden_sizes snake_case_ = depths snake_case_ = is_training snake_case_ = use_labels snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = num_labels snake_case_ = initializer_range snake_case_ = out_features snake_case_ = out_indices snake_case_ = scope def lowerCAmelCase ( self : List[str] ) ->str: """simple docstring""" snake_case_ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case_ = None if self.use_labels: snake_case_ = ids_tensor([self.batch_size] , self.num_labels ) snake_case_ = self.get_config() return config, pixel_values, labels def lowerCAmelCase ( self : Dict ) ->Optional[int]: """simple docstring""" return ConvNextVaConfig( num_channels=self.num_channels , hidden_sizes=self.hidden_sizes , depths=self.depths , num_stages=self.num_stages , hidden_act=self.hidden_act , is_decoder=UpperCAmelCase_ , initializer_range=self.initializer_range , out_features=self.out_features , out_indices=self.out_indices , num_labels=self.num_labels , ) def lowerCAmelCase ( self : List[Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Optional[Any] ) ->List[Any]: """simple docstring""" snake_case_ = ConvNextVaModel(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[Any] ) ->Any: """simple docstring""" snake_case_ = ConvNextVaForImageClassification(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCAmelCase ( self : Optional[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Union[str, Any] ) ->Tuple: """simple docstring""" snake_case_ = ConvNextVaBackbone(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ ) # verify hidden states self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:] ) # verify backbone works with out_features=None snake_case_ = None snake_case_ = ConvNextVaBackbone(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" snake_case_ = self.prepare_config_and_inputs() snake_case_ , snake_case_ , snake_case_ = config_and_inputs snake_case_ = {"""pixel_values""": pixel_values} return config, inputs_dict def lowerCAmelCase ( self : List[str] ) ->Union[str, Any]: """simple docstring""" snake_case_ = self.prepare_config_and_inputs() snake_case_ , snake_case_ , snake_case_ = config_and_inputs snake_case_ = {"""pixel_values""": pixel_values, """labels""": labels} return config, inputs_dict @require_torch class __A (snake_case__ , snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Optional[Any] = ( ( ConvNextVaModel, ConvNextVaForImageClassification, ConvNextVaBackbone, ) if is_torch_available() else () ) __lowercase: Union[str, Any] = ( {"""feature-extraction""": ConvNextVaModel, """image-classification""": ConvNextVaForImageClassification} if is_torch_available() else {} ) __lowercase: Union[str, Any] = False __lowercase: Optional[Any] = False __lowercase: Any = False __lowercase: Union[str, Any] = False __lowercase: Dict = False def lowerCAmelCase ( self : Union[str, Any] ) ->Tuple: """simple docstring""" snake_case_ = ConvNextVaModelTester(self ) snake_case_ = ConfigTester(self , config_class=UpperCAmelCase_ , has_text_modality=UpperCAmelCase_ , hidden_size=37 ) def lowerCAmelCase ( self : List[Any] ) ->Optional[Any]: """simple docstring""" 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 lowerCAmelCase ( self : str ) ->Optional[Any]: """simple docstring""" return @unittest.skip(reason="""ConvNextV2 does not use inputs_embeds""" ) def lowerCAmelCase ( self : Optional[int] ) ->Union[str, Any]: """simple docstring""" pass @unittest.skip(reason="""ConvNextV2 does not support input and output embeddings""" ) def lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" pass @unittest.skip(reason="""ConvNextV2 does not use feedforward chunking""" ) def lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" pass def lowerCAmelCase ( self : Dict ) ->Optional[int]: """simple docstring""" if not self.model_tester.is_training: return for model_class in self.all_model_classes: snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_with_labels() snake_case_ = True if model_class.__name__ in [ *get_values(UpperCAmelCase_ ), *get_values(UpperCAmelCase_ ), ]: continue snake_case_ = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.train() snake_case_ = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ , return_labels=UpperCAmelCase_ ) snake_case_ = model(**UpperCAmelCase_ ).loss loss.backward() def lowerCAmelCase ( self : Optional[int] ) ->Any: """simple docstring""" if not self.model_tester.is_training: return for model_class in self.all_model_classes: snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_with_labels() snake_case_ = False snake_case_ = True if ( model_class.__name__ in [*get_values(UpperCAmelCase_ ), *get_values(UpperCAmelCase_ )] or not model_class.supports_gradient_checkpointing ): continue snake_case_ = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.gradient_checkpointing_enable() model.train() snake_case_ = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ , return_labels=UpperCAmelCase_ ) snake_case_ = model(**UpperCAmelCase_ ).loss loss.backward() def lowerCAmelCase ( self : List[Any] ) ->Union[str, Any]: """simple docstring""" snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ = model_class(UpperCAmelCase_ ) snake_case_ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case_ = [*signature.parameters.keys()] snake_case_ = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] ) ->Union[str, Any]: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->Dict: """simple docstring""" def check_hidden_states_output(UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : str ): snake_case_ = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() with torch.no_grad(): snake_case_ = model(**self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) ) snake_case_ = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states snake_case_ = self.model_tester.num_stages self.assertEqual(len(UpperCAmelCase_ ) , expected_num_stages + 1 ) # ConvNextV2's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ = True check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] snake_case_ = True check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] ) ->Dict: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_ ) @slow def lowerCAmelCase ( self : Tuple ) ->str: """simple docstring""" for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ = ConvNextVaModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) def _a ( ) -> str: snake_case_ = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class __A (unittest.TestCase): '''simple docstring''' @cached_property def lowerCAmelCase ( self : Union[str, Any] ) ->Optional[int]: """simple docstring""" return AutoImageProcessor.from_pretrained("""facebook/convnextv2-tiny-1k-224""" ) if is_vision_available() else None @slow def lowerCAmelCase ( self : Tuple ) ->int: """simple docstring""" snake_case_ = ConvNextVaForImageClassification.from_pretrained("""facebook/convnextv2-tiny-1k-224""" ).to(UpperCAmelCase_ ) snake_case_ = self.default_image_processor snake_case_ = prepare_img() snake_case_ = preprocessor(images=UpperCAmelCase_ , return_tensors="""pt""" ).to(UpperCAmelCase_ ) # forward pass with torch.no_grad(): snake_case_ = model(**UpperCAmelCase_ ) # verify the logits snake_case_ = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape , UpperCAmelCase_ ) snake_case_ = torch.tensor([0.9_996, 0.1_966, -0.4_386] ).to(UpperCAmelCase_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCAmelCase_ , atol=1E-4 ) )
2
0
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_convbert import ConvBertTokenizer __SCREAMING_SNAKE_CASE : Any = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Tuple = {'vocab_file': 'vocab.txt'} __SCREAMING_SNAKE_CASE : Any = { 'vocab_file': { 'YituTech/conv-bert-base': 'https://huggingface.co/YituTech/conv-bert-base/resolve/main/vocab.txt', 'YituTech/conv-bert-medium-small': ( 'https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/vocab.txt' ), 'YituTech/conv-bert-small': 'https://huggingface.co/YituTech/conv-bert-small/resolve/main/vocab.txt', } } __SCREAMING_SNAKE_CASE : int = { 'YituTech/conv-bert-base': 512, 'YituTech/conv-bert-medium-small': 512, 'YituTech/conv-bert-small': 512, } __SCREAMING_SNAKE_CASE : int = { 'YituTech/conv-bert-base': {'do_lower_case': True}, 'YituTech/conv-bert-medium-small': {'do_lower_case': True}, 'YituTech/conv-bert-small': {'do_lower_case': True}, } class __A (snake_case__): '''simple docstring''' __lowercase: Tuple = VOCAB_FILES_NAMES __lowercase: int = PRETRAINED_VOCAB_FILES_MAP __lowercase: Dict = PRETRAINED_INIT_CONFIGURATION __lowercase: Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowercase: Dict = ConvBertTokenizer def __init__( self : Union[str, Any] , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : Dict=True , UpperCAmelCase_ : Dict="[UNK]" , UpperCAmelCase_ : Dict="[SEP]" , UpperCAmelCase_ : Tuple="[PAD]" , UpperCAmelCase_ : Dict="[CLS]" , UpperCAmelCase_ : Any="[MASK]" , UpperCAmelCase_ : int=True , UpperCAmelCase_ : Any=None , **UpperCAmelCase_ : Dict , ) ->Tuple: """simple docstring""" super().__init__( UpperCAmelCase_ , tokenizer_file=UpperCAmelCase_ , do_lower_case=UpperCAmelCase_ , unk_token=UpperCAmelCase_ , sep_token=UpperCAmelCase_ , pad_token=UpperCAmelCase_ , cls_token=UpperCAmelCase_ , mask_token=UpperCAmelCase_ , tokenize_chinese_chars=UpperCAmelCase_ , strip_accents=UpperCAmelCase_ , **UpperCAmelCase_ , ) snake_case_ = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""" , UpperCAmelCase_ ) != do_lower_case or normalizer_state.get("""strip_accents""" , UpperCAmelCase_ ) != strip_accents or normalizer_state.get("""handle_chinese_chars""" , UpperCAmelCase_ ) != tokenize_chinese_chars ): snake_case_ = getattr(UpperCAmelCase_ , normalizer_state.pop("""type""" ) ) snake_case_ = do_lower_case snake_case_ = strip_accents snake_case_ = tokenize_chinese_chars snake_case_ = normalizer_class(**UpperCAmelCase_ ) snake_case_ = do_lower_case def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : int=None ) ->List[Any]: """simple docstring""" snake_case_ = [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 : Optional[int] , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ) ->List[int]: """simple docstring""" snake_case_ = [self.sep_token_id] snake_case_ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def lowerCAmelCase ( self : str , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None ) ->Tuple[str]: """simple docstring""" snake_case_ = self._tokenizer.model.save(UpperCAmelCase_ , name=UpperCAmelCase_ ) return tuple(UpperCAmelCase_ )
708
"""simple docstring""" import argparse from pathlib import Path from typing import Dict, OrderedDict, Tuple import torch from audiocraft.models import MusicGen from transformers import ( AutoFeatureExtractor, AutoTokenizer, EncodecModel, MusicgenDecoderConfig, MusicgenForConditionalGeneration, MusicgenProcessor, TaEncoderModel, ) from transformers.models.musicgen.modeling_musicgen import MusicgenForCausalLM from transformers.utils import logging logging.set_verbosity_info() __SCREAMING_SNAKE_CASE : Union[str, Any] = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : int = ['model.decoder.embed_positions.weights'] def _a ( _SCREAMING_SNAKE_CASE ) -> str: if "emb" in name: snake_case_ = name.replace("""emb""" , """model.decoder.embed_tokens""" ) if "transformer" in name: snake_case_ = name.replace("""transformer""" , """model.decoder""" ) if "cross_attention" in name: snake_case_ = name.replace("""cross_attention""" , """encoder_attn""" ) if "linear1" in name: snake_case_ = name.replace("""linear1""" , """fc1""" ) if "linear2" in name: snake_case_ = name.replace("""linear2""" , """fc2""" ) if "norm1" in name: snake_case_ = name.replace("""norm1""" , """self_attn_layer_norm""" ) if "norm_cross" in name: snake_case_ = name.replace("""norm_cross""" , """encoder_attn_layer_norm""" ) if "norm2" in name: snake_case_ = name.replace("""norm2""" , """final_layer_norm""" ) if "out_norm" in name: snake_case_ = name.replace("""out_norm""" , """model.decoder.layer_norm""" ) if "linears" in name: snake_case_ = name.replace("""linears""" , """lm_heads""" ) if "condition_provider.conditioners.description.output_proj" in name: snake_case_ = name.replace("""condition_provider.conditioners.description.output_proj""" , """enc_to_dec_proj""" ) return name def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple[Dict, Dict]: snake_case_ = list(state_dict.keys() ) snake_case_ = {} for key in keys: snake_case_ = state_dict.pop(_SCREAMING_SNAKE_CASE ) snake_case_ = rename_keys(_SCREAMING_SNAKE_CASE ) if "in_proj_weight" in key: # split fused qkv proj snake_case_ = val[:hidden_size, :] snake_case_ = val[hidden_size : 2 * hidden_size, :] snake_case_ = val[-hidden_size:, :] elif "enc_to_dec_proj" in key: snake_case_ = val else: snake_case_ = val return state_dict, enc_dec_proj_state_dict def _a ( _SCREAMING_SNAKE_CASE ) -> MusicgenDecoderConfig: if checkpoint == "small": # default config values snake_case_ = 1_024 snake_case_ = 24 snake_case_ = 16 elif checkpoint == "medium": snake_case_ = 1_536 snake_case_ = 48 snake_case_ = 24 elif checkpoint == "large": snake_case_ = 2_048 snake_case_ = 48 snake_case_ = 32 else: raise ValueError(f"""Checkpoint should be one of `['small', 'medium', 'large']`, got {checkpoint}.""" ) snake_case_ = MusicgenDecoderConfig( hidden_size=_SCREAMING_SNAKE_CASE , ffn_dim=hidden_size * 4 , num_hidden_layers=_SCREAMING_SNAKE_CASE , num_attention_heads=_SCREAMING_SNAKE_CASE , ) return config @torch.no_grad() def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE="cpu" ) -> Tuple: snake_case_ = MusicGen.get_pretrained(_SCREAMING_SNAKE_CASE , device=_SCREAMING_SNAKE_CASE ) snake_case_ = decoder_config_from_checkpoint(_SCREAMING_SNAKE_CASE ) snake_case_ = fairseq_model.lm.state_dict() snake_case_ , snake_case_ = rename_state_dict( _SCREAMING_SNAKE_CASE , hidden_size=decoder_config.hidden_size ) snake_case_ = TaEncoderModel.from_pretrained("""t5-base""" ) snake_case_ = EncodecModel.from_pretrained("""facebook/encodec_32khz""" ) snake_case_ = MusicgenForCausalLM(_SCREAMING_SNAKE_CASE ).eval() # load all decoder weights - expect that we'll be missing embeddings and enc-dec projection snake_case_ , snake_case_ = decoder.load_state_dict(_SCREAMING_SNAKE_CASE , strict=_SCREAMING_SNAKE_CASE ) for key in missing_keys.copy(): if key.startswith(("""text_encoder""", """audio_encoder""") ) or key in EXPECTED_MISSING_KEYS: missing_keys.remove(_SCREAMING_SNAKE_CASE ) if len(_SCREAMING_SNAKE_CASE ) > 0: raise ValueError(f"""Missing key(s) in state_dict: {missing_keys}""" ) if len(_SCREAMING_SNAKE_CASE ) > 0: raise ValueError(f"""Unexpected key(s) in state_dict: {unexpected_keys}""" ) # init the composite model snake_case_ = MusicgenForConditionalGeneration(text_encoder=_SCREAMING_SNAKE_CASE , audio_encoder=_SCREAMING_SNAKE_CASE , decoder=_SCREAMING_SNAKE_CASE ) # load the pre-trained enc-dec projection (from the decoder state dict) model.enc_to_dec_proj.load_state_dict(_SCREAMING_SNAKE_CASE ) # check we can do a forward pass snake_case_ = torch.arange(0 , 8 , dtype=torch.long ).reshape(2 , -1 ) snake_case_ = input_ids.reshape(2 * 4 , -1 ) with torch.no_grad(): snake_case_ = model(input_ids=_SCREAMING_SNAKE_CASE , decoder_input_ids=_SCREAMING_SNAKE_CASE ).logits if logits.shape != (8, 1, 2_048): raise ValueError("""Incorrect shape for logits""" ) # now construct the processor snake_case_ = AutoTokenizer.from_pretrained("""t5-base""" ) snake_case_ = AutoFeatureExtractor.from_pretrained("""facebook/encodec_32khz""" , padding_side="""left""" ) snake_case_ = MusicgenProcessor(feature_extractor=_SCREAMING_SNAKE_CASE , tokenizer=_SCREAMING_SNAKE_CASE ) # set the appropriate bos/pad token ids snake_case_ = 2_048 snake_case_ = 2_048 # set other default generation config params snake_case_ = int(30 * audio_encoder.config.frame_rate ) snake_case_ = True snake_case_ = 3.0 if pytorch_dump_folder is not None: Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) logger.info(f"""Saving model {checkpoint} to {pytorch_dump_folder}""" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) processor.save_pretrained(_SCREAMING_SNAKE_CASE ) if repo_id: logger.info(f"""Pushing model {checkpoint} to {repo_id}""" ) model.push_to_hub(_SCREAMING_SNAKE_CASE ) processor.push_to_hub(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( '--checkpoint', default='small', type=str, help='Checkpoint size of the MusicGen model you\'d like to convert. Can be one of: `[\'small\', \'medium\', \'large\']`.', ) parser.add_argument( '--pytorch_dump_folder', required=True, default=None, type=str, help='Path to the output PyTorch model directory.', ) parser.add_argument( '--push_to_hub', default=None, type=str, help='Where to upload the converted model on the 🤗 hub.' ) parser.add_argument( '--device', default='cpu', type=str, help='Torch device to run the conversion, either cpu or cuda.' ) __SCREAMING_SNAKE_CASE : int = parser.parse_args() convert_musicgen_checkpoint(args.checkpoint, args.pytorch_dump_folder, args.push_to_hub)
2
0
"""simple docstring""" import warnings from .state import AcceleratorState, GradientState warnings.filterwarnings('ignore', category=UserWarning, module='torch.optim.lr_scheduler') class __A : '''simple docstring''' def __init__( self : Union[str, Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : bool = False ) ->Dict: """simple docstring""" snake_case_ = scheduler snake_case_ = optimizers if isinstance(UpperCAmelCase_ , (list, tuple) ) else [optimizers] snake_case_ = split_batches snake_case_ = step_with_optimizer snake_case_ = GradientState() def lowerCAmelCase ( self : Dict , *UpperCAmelCase_ : List[str] , **UpperCAmelCase_ : Dict ) ->Union[str, Any]: """simple docstring""" if not self.step_with_optimizer: # No link between scheduler and optimizer -> just step self.scheduler.step(*UpperCAmelCase_ , **UpperCAmelCase_ ) return # Otherwise, first make sure the optimizer was stepped. if not self.gradient_state.sync_gradients: if self.gradient_state.adjust_scheduler: self.scheduler._step_count += 1 return for opt in self.optimizers: if opt.step_was_skipped: return if self.split_batches: # Split batches -> the training dataloader batch size is not changed so one step per training step self.scheduler.step(*UpperCAmelCase_ , **UpperCAmelCase_ ) else: # Otherwise the training dataloader batch size was multiplied by `num_processes`, so we need to do # num_processes steps per training step snake_case_ = AcceleratorState().num_processes for _ in range(UpperCAmelCase_ ): # Special case when using OneCycle and `drop_last` was not used if hasattr(self.scheduler , """total_steps""" ): if self.scheduler._step_count <= self.scheduler.total_steps: self.scheduler.step(*UpperCAmelCase_ , **UpperCAmelCase_ ) else: self.scheduler.step(*UpperCAmelCase_ , **UpperCAmelCase_ ) def lowerCAmelCase ( self : Tuple ) ->Optional[int]: """simple docstring""" return self.scheduler.get_last_lr() def lowerCAmelCase ( self : Dict ) ->Optional[Any]: """simple docstring""" return self.scheduler.state_dict() def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : Optional[int] ) ->Any: """simple docstring""" self.scheduler.load_state_dict(UpperCAmelCase_ ) def lowerCAmelCase ( self : List[str] ) ->List[str]: """simple docstring""" return self.scheduler.get_lr() def lowerCAmelCase ( self : str , *UpperCAmelCase_ : List[str] , **UpperCAmelCase_ : Optional[int] ) ->Any: """simple docstring""" return self.scheduler.print_lr(*UpperCAmelCase_ , **UpperCAmelCase_ )
709
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> int: if index == number_of_items: return 0 snake_case_ = 0 snake_case_ = 0 snake_case_ = knapsack(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , index + 1 ) if weights[index] <= max_weight: snake_case_ = values[index] + knapsack( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , max_weight - weights[index] , index + 1 ) return max(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": import doctest doctest.testmod()
2
0
"""simple docstring""" from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __SCREAMING_SNAKE_CASE : Optional[Any] = {'configuration_mra': ['MRA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MraConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : List[Any] = [ 'MRA_PRETRAINED_MODEL_ARCHIVE_LIST', 'MraForMaskedLM', 'MraForMultipleChoice', 'MraForQuestionAnswering', 'MraForSequenceClassification', 'MraForTokenClassification', 'MraLayer', 'MraModel', 'MraPreTrainedModel', ] if TYPE_CHECKING: from .configuration_mra import MRA_PRETRAINED_CONFIG_ARCHIVE_MAP, MraConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mra import ( MRA_PRETRAINED_MODEL_ARCHIVE_LIST, MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, MraLayer, MraModel, MraPreTrainedModel, ) else: import sys __SCREAMING_SNAKE_CASE : Optional[int] = _LazyModule(__name__, globals()['__file__'], _import_structure)
710
"""simple docstring""" from math import factorial def _a ( _SCREAMING_SNAKE_CASE = 20 ) -> int: snake_case_ = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1, # 2, 3,... snake_case_ = n // 2 return int(factorial(_SCREAMING_SNAKE_CASE ) / (factorial(_SCREAMING_SNAKE_CASE ) * factorial(n - k )) ) if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution(20)) else: try: __SCREAMING_SNAKE_CASE : Optional[int] = int(sys.argv[1]) print(solution(n)) except ValueError: print('Invalid entry - please enter a number.')
2
0
"""simple docstring""" import re import tempfile from pathlib import Path import pytest import yaml from datasets.utils.readme import ReadMe # @pytest.fixture # def example_yaml_structure(): __SCREAMING_SNAKE_CASE : Tuple = yaml.safe_load( '\\nname: ""\nallow_empty: false\nallow_empty_text: true\nsubsections:\n - name: "Dataset Card for X" # First-level markdown heading\n allow_empty: false\n allow_empty_text: true\n subsections:\n - name: "Table of Contents"\n allow_empty: false\n allow_empty_text: false\n subsections: null\n - name: "Dataset Description"\n allow_empty: false\n allow_empty_text: false\n subsections:\n - name: "Dataset Summary"\n allow_empty: false\n allow_empty_text: false\n subsections: null\n - name: "Supported Tasks and Leaderboards"\n allow_empty: true\n allow_empty_text: true\n subsections: null\n - name: Languages\n allow_empty: false\n allow_empty_text: true\n subsections: null\n' ) __SCREAMING_SNAKE_CASE : Any = { 'name': 'root', 'text': '', 'is_empty_text': True, 'subsections': [ { 'name': 'Dataset Card for My Dataset', 'text': '', 'is_empty_text': True, 'subsections': [ {'name': 'Table of Contents', 'text': 'Some text here.', 'is_empty_text': False, 'subsections': []}, { 'name': 'Dataset Description', 'text': 'Some text here.', 'is_empty_text': False, 'subsections': [ { 'name': 'Dataset Summary', 'text': 'Some text here.', 'is_empty_text': False, 'subsections': [], }, { 'name': 'Supported Tasks and Leaderboards', 'text': '', 'is_empty_text': True, 'subsections': [], }, {'name': 'Languages', 'text': 'Language Text', 'is_empty_text': False, 'subsections': []}, ], }, ], } ], } __SCREAMING_SNAKE_CASE : Any = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' __SCREAMING_SNAKE_CASE : Dict = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n#### Extra Ignored Subsection\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' __SCREAMING_SNAKE_CASE : List[str] = { 'name': 'root', 'text': '', 'is_empty_text': True, 'subsections': [ { 'name': 'Dataset Card for My Dataset', 'text': '', 'is_empty_text': True, 'subsections': [ {'name': 'Table of Contents', 'text': 'Some text here.', 'is_empty_text': False, 'subsections': []}, { 'name': 'Dataset Description', 'text': 'Some text here.', 'is_empty_text': False, 'subsections': [ { 'name': 'Dataset Summary', 'text': 'Some text here.', 'is_empty_text': False, 'subsections': [ { 'name': 'Extra Ignored Subsection', 'text': '', 'is_empty_text': True, 'subsections': [], } ], }, { 'name': 'Supported Tasks and Leaderboards', 'text': '', 'is_empty_text': True, 'subsections': [], }, {'name': 'Languages', 'text': 'Language Text', 'is_empty_text': False, 'subsections': []}, ], }, ], } ], } __SCREAMING_SNAKE_CASE : List[Any] = '\\n---\n---\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' __SCREAMING_SNAKE_CASE : Union[str, Any] = ( 'The following issues were found for the README at `{path}`:\n-\tEmpty YAML markers are present in the README.' ) __SCREAMING_SNAKE_CASE : int = '\\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' __SCREAMING_SNAKE_CASE : Tuple = ( 'The following issues were found for the README at `{path}`:\n-\tNo YAML markers are present in the README.' ) __SCREAMING_SNAKE_CASE : int = '\\n---\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' __SCREAMING_SNAKE_CASE : Tuple = 'The following issues were found for the README at `{path}`:\n-\tOnly the start of YAML tags present in the README.' __SCREAMING_SNAKE_CASE : List[str] = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' __SCREAMING_SNAKE_CASE : int = 'The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Summary` but it is empty.\n-\tExpected some text in section `Dataset Summary` but it is empty (text in subsections are ignored).' __SCREAMING_SNAKE_CASE : int = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n' __SCREAMING_SNAKE_CASE : Any = 'The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Card for My Dataset` but it is empty.\n-\tSection `Dataset Card for My Dataset` expected the following subsections: `Table of Contents`, `Dataset Description`. Found \'None\'.' __SCREAMING_SNAKE_CASE : Any = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Languages\nLanguage Text\n' __SCREAMING_SNAKE_CASE : List[str] = 'The following issues were found for the README at `{path}`:\n-\tSection `Dataset Description` is missing subsection: `Supported Tasks and Leaderboards`.' __SCREAMING_SNAKE_CASE : List[Any] = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\n' __SCREAMING_SNAKE_CASE : Dict = 'The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Languages` but it is empty.' __SCREAMING_SNAKE_CASE : Tuple = '\\n---\nlanguage:\n- zh\n- en\n---\n\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' __SCREAMING_SNAKE_CASE : Dict = 'The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README.' __SCREAMING_SNAKE_CASE : Any = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n# Dataset Card My Dataset\n' __SCREAMING_SNAKE_CASE : Tuple = 'The following issues were found for the README at `{path}`:\n-\tThe README has several first-level headings: `Dataset Card for My Dataset`, `Dataset Card My Dataset`. Only one heading is expected. Skipping further validation for this README.' __SCREAMING_SNAKE_CASE : List[str] = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' __SCREAMING_SNAKE_CASE : List[Any] = 'The following issues were found for the README at `{path}`:\n-\tNo first-level heading starting with `Dataset Card for` found in README. Skipping further validation for this README.' __SCREAMING_SNAKE_CASE : Tuple = '' __SCREAMING_SNAKE_CASE : List[str] = 'The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README.\n-\tNo YAML markers are present in the README.' __SCREAMING_SNAKE_CASE : List[Any] = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' __SCREAMING_SNAKE_CASE : Optional[int] = 'The following issues were found while parsing the README at `{path}`:\n-\tMultiple sections with the same heading `Dataset Card for My Dataset` have been found. Please keep only one of these sections.' @pytest.mark.parametrize( """readme_md, expected_dict""" , [ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ] , ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: assert ReadMe.from_string(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).to_dict() == expected_dict @pytest.mark.parametrize( """readme_md, expected_error""" , [ (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML), (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML), (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML), (README_EMPTY, EXPECTED_ERROR_README_EMPTY), (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION), (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL), (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION), (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT), (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL), (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL), (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT), ] , ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> int: with pytest.raises(_SCREAMING_SNAKE_CASE , match=re.escape(expected_error.format(path="""root""" ) ) ): snake_case_ = ReadMe.from_string(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) readme.validate() @pytest.mark.parametrize( """readme_md, expected_error""" , [ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] , ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple: with pytest.raises(_SCREAMING_SNAKE_CASE , match=re.escape(expected_error.format(path="""root""" ) ) ): ReadMe.from_string(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( """readme_md,""" , [ (README_MULTIPLE_SAME_HEADING_1), ] , ) def _a ( _SCREAMING_SNAKE_CASE ) -> Optional[int]: ReadMe.from_string(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , suppress_parsing_errors=_SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( """readme_md, expected_dict""" , [ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ] , ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> int: with tempfile.TemporaryDirectory() as tmp_dir: snake_case_ = Path(_SCREAMING_SNAKE_CASE ) / """README.md""" with open(_SCREAMING_SNAKE_CASE , """w+""" ) as readme_file: readme_file.write(_SCREAMING_SNAKE_CASE ) snake_case_ = ReadMe.from_readme(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).to_dict() assert out["name"] == path assert out["text"] == "" assert out["is_empty_text"] assert out["subsections"] == expected_dict["subsections"] @pytest.mark.parametrize( """readme_md, expected_error""" , [ (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML), (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML), (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML), (README_EMPTY, EXPECTED_ERROR_README_EMPTY), (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION), (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL), (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION), (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT), (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL), (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL), (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT), ] , ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple: with tempfile.TemporaryDirectory() as tmp_dir: snake_case_ = Path(_SCREAMING_SNAKE_CASE ) / """README.md""" with open(_SCREAMING_SNAKE_CASE , """w+""" ) as readme_file: readme_file.write(_SCREAMING_SNAKE_CASE ) snake_case_ = expected_error.format(path=_SCREAMING_SNAKE_CASE ) with pytest.raises(_SCREAMING_SNAKE_CASE , match=re.escape(_SCREAMING_SNAKE_CASE ) ): snake_case_ = ReadMe.from_readme(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) readme.validate() @pytest.mark.parametrize( """readme_md, expected_error""" , [ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] , ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[int]: with tempfile.TemporaryDirectory() as tmp_dir: snake_case_ = Path(_SCREAMING_SNAKE_CASE ) / """README.md""" with open(_SCREAMING_SNAKE_CASE , """w+""" ) as readme_file: readme_file.write(_SCREAMING_SNAKE_CASE ) snake_case_ = expected_error.format(path=_SCREAMING_SNAKE_CASE ) with pytest.raises(_SCREAMING_SNAKE_CASE , match=re.escape(_SCREAMING_SNAKE_CASE ) ): ReadMe.from_readme(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @pytest.mark.parametrize( """readme_md,""" , [ (README_MULTIPLE_SAME_HEADING_1), ] , ) def _a ( _SCREAMING_SNAKE_CASE ) -> int: with tempfile.TemporaryDirectory() as tmp_dir: snake_case_ = Path(_SCREAMING_SNAKE_CASE ) / """README.md""" with open(_SCREAMING_SNAKE_CASE , """w+""" ) as readme_file: readme_file.write(_SCREAMING_SNAKE_CASE ) ReadMe.from_readme(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , suppress_parsing_errors=_SCREAMING_SNAKE_CASE )
711
"""simple docstring""" import secrets from random import shuffle from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation def _a ( _SCREAMING_SNAKE_CASE = 8 ) -> str: snake_case_ = ascii_letters + digits + punctuation return "".join(secrets.choice(_SCREAMING_SNAKE_CASE ) for _ in range(_SCREAMING_SNAKE_CASE ) ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: # Password Generator = full boot with random_number, random_letters, and # random_character FUNCTIONS # Put your code here... i -= len(_SCREAMING_SNAKE_CASE ) snake_case_ = i // 3 snake_case_ = i % 3 # chars = chars_incl + random_letters(ascii_letters, i / 3 + remainder) + # random_number(digits, i / 3) + random_characters(punctuation, i / 3) snake_case_ = ( chars_incl + random(_SCREAMING_SNAKE_CASE , quotient + remainder ) + random(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) + random(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) snake_case_ = list(_SCREAMING_SNAKE_CASE ) shuffle(_SCREAMING_SNAKE_CASE ) return "".join(_SCREAMING_SNAKE_CASE ) # random is a generalised function for letters, characters and numbers def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: return "".join(secrets.choice(_SCREAMING_SNAKE_CASE ) for _ in range(_SCREAMING_SNAKE_CASE ) ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: pass # Put your code here... def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[str]: pass # Put your code here... def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[int]: pass # Put your code here... def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 8 ) -> bool: if len(_SCREAMING_SNAKE_CASE ) < min_length: # Your Password must be at least 8 characters long return False snake_case_ = any(char in ascii_uppercase for char in password ) snake_case_ = any(char in ascii_lowercase for char in password ) snake_case_ = any(char in digits for char in password ) snake_case_ = any(char in punctuation for char in password ) return upper and lower and num and spec_char # Passwords should contain UPPERCASE, lowerase # numbers, and special characters def _a ( ) -> str: snake_case_ = int(input("""Please indicate the max length of your password: """ ).strip() ) snake_case_ = input( """Please indicate the characters that must be in your password: """ ).strip() print("""Password generated:""" , password_generator(_SCREAMING_SNAKE_CASE ) ) print( """Alternative Password generated:""" , alternative_password_generator(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) , ) print("""[If you are thinking of using this passsword, You better save it.]""" ) if __name__ == "__main__": main()
2
0
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE ) -> str: return "".join([hex(_SCREAMING_SNAKE_CASE )[2:].zfill(2 ).upper() for byte in list(_SCREAMING_SNAKE_CASE )] ) def _a ( _SCREAMING_SNAKE_CASE ) -> bytes: # Check data validity, following RFC3548 # https://www.ietf.org/rfc/rfc3548.txt if (len(_SCREAMING_SNAKE_CASE ) % 2) != 0: raise ValueError( """Base16 encoded data is invalid: Data does not have an even number of hex digits.""" ) # Check the character set - the standard base16 alphabet # is uppercase according to RFC3548 section 6 if not set(_SCREAMING_SNAKE_CASE ) <= set("""0123456789ABCDEF""" ): raise ValueError( """Base16 encoded data is invalid: Data is not uppercase hex or it contains invalid characters.""" ) # For every two hexadecimal digits (= a byte), turn it into an integer. # Then, string the result together into bytes, and return it. return bytes(int(data[i] + data[i + 1] , 16 ) for i in range(0 , len(_SCREAMING_SNAKE_CASE ) , 2 ) ) if __name__ == "__main__": import doctest doctest.testmod()
712
"""simple docstring""" import json import os import tempfile import unittest import numpy as np from datasets import load_dataset 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 if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ImageGPTImageProcessor class __A (unittest.TestCase): '''simple docstring''' def __init__( self : int , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Tuple=7 , UpperCAmelCase_ : Dict=3 , UpperCAmelCase_ : Tuple=18 , UpperCAmelCase_ : Optional[Any]=30 , UpperCAmelCase_ : str=400 , UpperCAmelCase_ : int=True , UpperCAmelCase_ : Optional[int]=None , UpperCAmelCase_ : Optional[Any]=True , ) ->Optional[Any]: """simple docstring""" snake_case_ = size if size is not None else {"""height""": 18, """width""": 18} snake_case_ = parent snake_case_ = batch_size snake_case_ = num_channels snake_case_ = image_size snake_case_ = min_resolution snake_case_ = max_resolution snake_case_ = do_resize snake_case_ = size snake_case_ = do_normalize def lowerCAmelCase ( self : List[str] ) ->Optional[Any]: """simple docstring""" return { # here we create 2 clusters for the sake of simplicity "clusters": np.asarray( [ [0.8_866_443_634_033_203, 0.6_618_829_369_544_983, 0.3_891_746_401_786_804], [-0.6_042_559_146_881_104, -0.02_295_008_860_528_469, 0.5_423_797_369_003_296], ] ), "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, } @require_torch @require_vision class __A (snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: List[Any] = ImageGPTImageProcessor if is_vision_available() else None def lowerCAmelCase ( self : Optional[int] ) ->Optional[int]: """simple docstring""" snake_case_ = ImageGPTImageProcessingTester(self ) @property def lowerCAmelCase ( self : Tuple ) ->List[Any]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(UpperCAmelCase_ , """clusters""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """do_resize""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """size""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """do_normalize""" ) ) def lowerCAmelCase ( self : Optional[int] ) ->Optional[Any]: """simple docstring""" snake_case_ = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""height""": 18, """width""": 18} ) snake_case_ = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {"""height""": 42, """width""": 42} ) def lowerCAmelCase ( self : Any ) ->List[Any]: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) snake_case_ = json.loads(image_processor.to_json_string() ) for key, value in self.image_processor_dict.items(): if key == "clusters": self.assertTrue(np.array_equal(UpperCAmelCase_ , obj[key] ) ) else: self.assertEqual(obj[key] , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] ) ->Dict: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: snake_case_ = os.path.join(UpperCAmelCase_ , """image_processor.json""" ) image_processor_first.to_json_file(UpperCAmelCase_ ) snake_case_ = self.image_processing_class.from_json_file(UpperCAmelCase_ ).to_dict() snake_case_ = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(UpperCAmelCase_ , image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->List[Any]: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: image_processor_first.save_pretrained(UpperCAmelCase_ ) snake_case_ = self.image_processing_class.from_pretrained(UpperCAmelCase_ ).to_dict() snake_case_ = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(UpperCAmelCase_ , image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] , UpperCAmelCase_ ) @unittest.skip("""ImageGPT requires clusters at initialization""" ) def lowerCAmelCase ( self : List[Any] ) ->Tuple: """simple docstring""" pass def _a ( ) -> str: snake_case_ = load_dataset("""hf-internal-testing/fixtures_image_utils""" , split="""test""" ) snake_case_ = Image.open(dataset[4]["""file"""] ) snake_case_ = Image.open(dataset[5]["""file"""] ) snake_case_ = [imagea, imagea] return images @require_vision @require_torch class __A (unittest.TestCase): '''simple docstring''' @slow def lowerCAmelCase ( self : Tuple ) ->List[str]: """simple docstring""" snake_case_ = ImageGPTImageProcessor.from_pretrained("""openai/imagegpt-small""" ) snake_case_ = prepare_images() # test non-batched snake_case_ = image_processing(images[0] , return_tensors="""pt""" ) self.assertIsInstance(encoding.input_ids , torch.LongTensor ) self.assertEqual(encoding.input_ids.shape , (1, 1_024) ) snake_case_ = [306, 191, 191] self.assertEqual(encoding.input_ids[0, :3].tolist() , UpperCAmelCase_ ) # test batched snake_case_ = image_processing(UpperCAmelCase_ , return_tensors="""pt""" ) self.assertIsInstance(encoding.input_ids , torch.LongTensor ) self.assertEqual(encoding.input_ids.shape , (2, 1_024) ) snake_case_ = [303, 13, 13] self.assertEqual(encoding.input_ids[1, -3:].tolist() , UpperCAmelCase_ )
2
0
from typing import Optional import torch import torch.utils.checkpoint from torch import Tensor, nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import ( BackboneOutput, BaseModelOutputWithNoAttention, BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention, ) from ...modeling_utils import PreTrainedModel from ...utils import ( add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings, ) from ...utils.backbone_utils import BackboneMixin from .configuration_resnet import ResNetConfig __SCREAMING_SNAKE_CASE : List[str] = logging.get_logger(__name__) # General docstring __SCREAMING_SNAKE_CASE : str = 'ResNetConfig' # Base docstring __SCREAMING_SNAKE_CASE : Any = 'microsoft/resnet-50' __SCREAMING_SNAKE_CASE : Tuple = [1, 2_048, 7, 7] # Image classification docstring __SCREAMING_SNAKE_CASE : Optional[Any] = 'microsoft/resnet-50' __SCREAMING_SNAKE_CASE : Optional[int] = 'tiger cat' __SCREAMING_SNAKE_CASE : Tuple = [ 'microsoft/resnet-50', # See all resnet models at https://huggingface.co/models?filter=resnet ] class __A (nn.Module): '''simple docstring''' def __init__( self : Union[str, Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : int , UpperCAmelCase_ : int = 3 , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : str = "relu" ) ->Tuple: """simple docstring""" super().__init__() snake_case_ = nn.Convad( UpperCAmelCase_ , UpperCAmelCase_ , kernel_size=UpperCAmelCase_ , stride=UpperCAmelCase_ , padding=kernel_size // 2 , bias=UpperCAmelCase_ ) snake_case_ = nn.BatchNormad(UpperCAmelCase_ ) snake_case_ = ACTaFN[activation] if activation is not None else nn.Identity() def lowerCAmelCase ( self : int , UpperCAmelCase_ : Tensor ) ->Tensor: """simple docstring""" snake_case_ = self.convolution(UpperCAmelCase_ ) snake_case_ = self.normalization(UpperCAmelCase_ ) snake_case_ = self.activation(UpperCAmelCase_ ) return hidden_state class __A (nn.Module): '''simple docstring''' def __init__( self : Optional[Any] , UpperCAmelCase_ : ResNetConfig ) ->Tuple: """simple docstring""" super().__init__() snake_case_ = ResNetConvLayer( config.num_channels , config.embedding_size , kernel_size=7 , stride=2 , activation=config.hidden_act ) snake_case_ = nn.MaxPoolad(kernel_size=3 , stride=2 , padding=1 ) snake_case_ = config.num_channels def lowerCAmelCase ( self : List[Any] , UpperCAmelCase_ : Tensor ) ->Tensor: """simple docstring""" snake_case_ = pixel_values.shape[1] if num_channels != self.num_channels: raise ValueError( """Make sure that the channel dimension of the pixel values match with the one set in the configuration.""" ) snake_case_ = self.embedder(UpperCAmelCase_ ) snake_case_ = self.pooler(UpperCAmelCase_ ) return embedding class __A (nn.Module): '''simple docstring''' def __init__( self : Union[str, Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : int , UpperCAmelCase_ : int = 2 ) ->List[Any]: """simple docstring""" super().__init__() snake_case_ = nn.Convad(UpperCAmelCase_ , UpperCAmelCase_ , kernel_size=1 , stride=UpperCAmelCase_ , bias=UpperCAmelCase_ ) snake_case_ = nn.BatchNormad(UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] , UpperCAmelCase_ : Tensor ) ->Tensor: """simple docstring""" snake_case_ = self.convolution(UpperCAmelCase_ ) snake_case_ = self.normalization(UpperCAmelCase_ ) return hidden_state class __A (nn.Module): '''simple docstring''' def __init__( self : Tuple , UpperCAmelCase_ : int , UpperCAmelCase_ : int , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : str = "relu" ) ->Tuple: """simple docstring""" super().__init__() snake_case_ = in_channels != out_channels or stride != 1 snake_case_ = ( ResNetShortCut(UpperCAmelCase_ , UpperCAmelCase_ , stride=UpperCAmelCase_ ) if should_apply_shortcut else nn.Identity() ) snake_case_ = nn.Sequential( ResNetConvLayer(UpperCAmelCase_ , UpperCAmelCase_ , stride=UpperCAmelCase_ ) , ResNetConvLayer(UpperCAmelCase_ , UpperCAmelCase_ , activation=UpperCAmelCase_ ) , ) snake_case_ = ACTaFN[activation] def lowerCAmelCase ( self : Optional[Any] , UpperCAmelCase_ : Optional[Any] ) ->Tuple: """simple docstring""" snake_case_ = hidden_state snake_case_ = self.layer(UpperCAmelCase_ ) snake_case_ = self.shortcut(UpperCAmelCase_ ) hidden_state += residual snake_case_ = self.activation(UpperCAmelCase_ ) return hidden_state class __A (nn.Module): '''simple docstring''' def __init__( self : Tuple , UpperCAmelCase_ : int , UpperCAmelCase_ : int , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : str = "relu" , UpperCAmelCase_ : int = 4 ) ->Tuple: """simple docstring""" super().__init__() snake_case_ = in_channels != out_channels or stride != 1 snake_case_ = out_channels // reduction snake_case_ = ( ResNetShortCut(UpperCAmelCase_ , UpperCAmelCase_ , stride=UpperCAmelCase_ ) if should_apply_shortcut else nn.Identity() ) snake_case_ = nn.Sequential( ResNetConvLayer(UpperCAmelCase_ , UpperCAmelCase_ , kernel_size=1 ) , ResNetConvLayer(UpperCAmelCase_ , UpperCAmelCase_ , stride=UpperCAmelCase_ ) , ResNetConvLayer(UpperCAmelCase_ , UpperCAmelCase_ , kernel_size=1 , activation=UpperCAmelCase_ ) , ) snake_case_ = ACTaFN[activation] def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : List[Any] ) ->List[str]: """simple docstring""" snake_case_ = hidden_state snake_case_ = self.layer(UpperCAmelCase_ ) snake_case_ = self.shortcut(UpperCAmelCase_ ) hidden_state += residual snake_case_ = self.activation(UpperCAmelCase_ ) return hidden_state class __A (nn.Module): '''simple docstring''' def __init__( self : str , UpperCAmelCase_ : ResNetConfig , UpperCAmelCase_ : int , UpperCAmelCase_ : int , UpperCAmelCase_ : int = 2 , UpperCAmelCase_ : int = 2 , ) ->List[Any]: """simple docstring""" super().__init__() snake_case_ = ResNetBottleNeckLayer if config.layer_type == """bottleneck""" else ResNetBasicLayer snake_case_ = nn.Sequential( # downsampling is done in the first layer with stride of 2 layer(UpperCAmelCase_ , UpperCAmelCase_ , stride=UpperCAmelCase_ , activation=config.hidden_act ) , *[layer(UpperCAmelCase_ , UpperCAmelCase_ , activation=config.hidden_act ) for _ in range(depth - 1 )] , ) def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : Tensor ) ->Tensor: """simple docstring""" snake_case_ = input for layer in self.layers: snake_case_ = layer(UpperCAmelCase_ ) return hidden_state class __A (nn.Module): '''simple docstring''' def __init__( self : Tuple , UpperCAmelCase_ : ResNetConfig ) ->List[Any]: """simple docstring""" super().__init__() snake_case_ = nn.ModuleList([] ) # based on `downsample_in_first_stage` the first layer of the first stage may or may not downsample the input self.stages.append( ResNetStage( UpperCAmelCase_ , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , ) ) snake_case_ = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for (in_channels, out_channels), depth in zip(UpperCAmelCase_ , config.depths[1:] ): self.stages.append(ResNetStage(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , depth=UpperCAmelCase_ ) ) def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : Tensor , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : bool = True ) ->BaseModelOutputWithNoAttention: """simple docstring""" snake_case_ = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: snake_case_ = hidden_states + (hidden_state,) snake_case_ = stage_module(UpperCAmelCase_ ) if output_hidden_states: snake_case_ = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return BaseModelOutputWithNoAttention( last_hidden_state=UpperCAmelCase_ , hidden_states=UpperCAmelCase_ , ) class __A (snake_case__): '''simple docstring''' __lowercase: List[Any] = ResNetConfig __lowercase: List[Any] = """resnet""" __lowercase: Optional[Any] = """pixel_values""" __lowercase: List[Any] = True def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : str ) ->Tuple: """simple docstring""" if isinstance(UpperCAmelCase_ , nn.Convad ): nn.init.kaiming_normal_(module.weight , mode="""fan_out""" , nonlinearity="""relu""" ) elif isinstance(UpperCAmelCase_ , (nn.BatchNormad, nn.GroupNorm) ): nn.init.constant_(module.weight , 1 ) nn.init.constant_(module.bias , 0 ) def lowerCAmelCase ( self : str , UpperCAmelCase_ : Any , UpperCAmelCase_ : Optional[int]=False ) ->Tuple: """simple docstring""" if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): snake_case_ = value __SCREAMING_SNAKE_CASE : int = R'\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it\n as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n\n Parameters:\n config ([`ResNetConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n' __SCREAMING_SNAKE_CASE : List[Any] = R'\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`ConvNextImageProcessor.__call__`] for details.\n\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n' @add_start_docstrings( """The bare ResNet model outputting raw features without any specific head on top.""" , snake_case__ , ) class __A (snake_case__): '''simple docstring''' def __init__( self : str , UpperCAmelCase_ : Tuple ) ->Union[str, Any]: """simple docstring""" super().__init__(UpperCAmelCase_ ) snake_case_ = config snake_case_ = ResNetEmbeddings(UpperCAmelCase_ ) snake_case_ = ResNetEncoder(UpperCAmelCase_ ) snake_case_ = nn.AdaptiveAvgPoolad((1, 1) ) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(UpperCAmelCase_ ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=UpperCAmelCase_ , config_class=_CONFIG_FOR_DOC , modality="""vision""" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : Tensor , UpperCAmelCase_ : Optional[bool] = None , UpperCAmelCase_ : Optional[bool] = None ) ->BaseModelOutputWithPoolingAndNoAttention: """simple docstring""" snake_case_ = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) snake_case_ = return_dict if return_dict is not None else self.config.use_return_dict snake_case_ = self.embedder(UpperCAmelCase_ ) snake_case_ = self.encoder( UpperCAmelCase_ , output_hidden_states=UpperCAmelCase_ , return_dict=UpperCAmelCase_ ) snake_case_ = encoder_outputs[0] snake_case_ = self.pooler(UpperCAmelCase_ ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=UpperCAmelCase_ , pooler_output=UpperCAmelCase_ , hidden_states=encoder_outputs.hidden_states , ) @add_start_docstrings( """ ResNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet. """ , snake_case__ , ) class __A (snake_case__): '''simple docstring''' def __init__( self : int , UpperCAmelCase_ : int ) ->Any: """simple docstring""" super().__init__(UpperCAmelCase_ ) snake_case_ = config.num_labels snake_case_ = ResNetModel(UpperCAmelCase_ ) # classification head snake_case_ = nn.Sequential( nn.Flatten() , nn.Linear(config.hidden_sizes[-1] , config.num_labels ) if config.num_labels > 0 else nn.Identity() , ) # initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(UpperCAmelCase_ ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=UpperCAmelCase_ , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def lowerCAmelCase ( self : int , UpperCAmelCase_ : Optional[torch.FloatTensor] = None , UpperCAmelCase_ : Optional[torch.LongTensor] = None , UpperCAmelCase_ : Optional[bool] = None , UpperCAmelCase_ : Optional[bool] = None , ) ->ImageClassifierOutputWithNoAttention: """simple docstring""" snake_case_ = return_dict if return_dict is not None else self.config.use_return_dict snake_case_ = self.resnet(UpperCAmelCase_ , output_hidden_states=UpperCAmelCase_ , return_dict=UpperCAmelCase_ ) snake_case_ = outputs.pooler_output if return_dict else outputs[1] snake_case_ = self.classifier(UpperCAmelCase_ ) snake_case_ = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: snake_case_ = """regression""" elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): snake_case_ = """single_label_classification""" else: snake_case_ = """multi_label_classification""" if self.config.problem_type == "regression": snake_case_ = MSELoss() if self.num_labels == 1: snake_case_ = loss_fct(logits.squeeze() , labels.squeeze() ) else: snake_case_ = loss_fct(UpperCAmelCase_ , UpperCAmelCase_ ) elif self.config.problem_type == "single_label_classification": snake_case_ = CrossEntropyLoss() snake_case_ = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": snake_case_ = BCEWithLogitsLoss() snake_case_ = loss_fct(UpperCAmelCase_ , UpperCAmelCase_ ) if not return_dict: snake_case_ = (logits,) + outputs[2:] return (loss,) + output if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=UpperCAmelCase_ , logits=UpperCAmelCase_ , hidden_states=outputs.hidden_states ) @add_start_docstrings( """ ResNet backbone, to be used with frameworks like DETR and MaskFormer. """ , snake_case__ , ) class __A (snake_case__ , snake_case__): '''simple docstring''' def __init__( self : List[Any] , UpperCAmelCase_ : Any ) ->Union[str, Any]: """simple docstring""" super().__init__(UpperCAmelCase_ ) super()._init_backbone(UpperCAmelCase_ ) snake_case_ = [config.embedding_size] + config.hidden_sizes snake_case_ = ResNetEmbeddings(UpperCAmelCase_ ) snake_case_ = ResNetEncoder(UpperCAmelCase_ ) # initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(UpperCAmelCase_ ) @replace_return_docstrings(output_type=UpperCAmelCase_ , config_class=_CONFIG_FOR_DOC ) def lowerCAmelCase ( self : str , UpperCAmelCase_ : Tensor , UpperCAmelCase_ : Optional[bool] = None , UpperCAmelCase_ : Optional[bool] = None ) ->BackboneOutput: """simple docstring""" snake_case_ = return_dict if return_dict is not None else self.config.use_return_dict snake_case_ = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) snake_case_ = self.embedder(UpperCAmelCase_ ) snake_case_ = self.encoder(UpperCAmelCase_ , output_hidden_states=UpperCAmelCase_ , return_dict=UpperCAmelCase_ ) snake_case_ = outputs.hidden_states snake_case_ = () for idx, stage in enumerate(self.stage_names ): if stage in self.out_features: feature_maps += (hidden_states[idx],) if not return_dict: snake_case_ = (feature_maps,) if output_hidden_states: output += (outputs.hidden_states,) return output return BackboneOutput( feature_maps=UpperCAmelCase_ , hidden_states=outputs.hidden_states if output_hidden_states else None , attentions=UpperCAmelCase_ , )
713
"""simple docstring""" import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, ) from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST class __A : '''simple docstring''' def __init__( self : Optional[int] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[Any]=13 , UpperCAmelCase_ : Optional[int]=7 , UpperCAmelCase_ : List[str]=True , UpperCAmelCase_ : int=True , UpperCAmelCase_ : List[Any]=True , UpperCAmelCase_ : Optional[int]=True , UpperCAmelCase_ : List[str]=99 , UpperCAmelCase_ : Dict=24 , UpperCAmelCase_ : List[str]=2 , UpperCAmelCase_ : Optional[Any]=6 , UpperCAmelCase_ : int=37 , UpperCAmelCase_ : Optional[Any]="gelu" , UpperCAmelCase_ : Optional[Any]=0.1 , UpperCAmelCase_ : List[Any]=0.1 , UpperCAmelCase_ : Any=512 , UpperCAmelCase_ : str=16 , UpperCAmelCase_ : List[str]=2 , UpperCAmelCase_ : Optional[int]=0.02 , UpperCAmelCase_ : Tuple=3 , UpperCAmelCase_ : Union[str, Any]=None , UpperCAmelCase_ : Any=1_000 , ) ->Tuple: """simple docstring""" snake_case_ = parent snake_case_ = batch_size snake_case_ = seq_length snake_case_ = is_training snake_case_ = use_input_mask snake_case_ = use_token_type_ids snake_case_ = use_labels snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = max_position_embeddings snake_case_ = type_vocab_size snake_case_ = type_sequence_label_size snake_case_ = initializer_range snake_case_ = num_labels snake_case_ = scope snake_case_ = range_bbox def lowerCAmelCase ( self : Tuple ) ->int: """simple docstring""" snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case_ = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox ) # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: snake_case_ = bbox[i, j, 3] snake_case_ = bbox[i, j, 1] snake_case_ = t if bbox[i, j, 2] < bbox[i, j, 0]: snake_case_ = bbox[i, j, 2] snake_case_ = bbox[i, j, 0] snake_case_ = t snake_case_ = None if self.use_input_mask: snake_case_ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) snake_case_ = None if self.use_token_type_ids: snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) snake_case_ = None snake_case_ = None if self.use_labels: snake_case_ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) snake_case_ = self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def lowerCAmelCase ( self : int ) ->Optional[int]: """simple docstring""" return LiltConfig( 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 , ) def lowerCAmelCase ( self : Any , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Any , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[int] , ) ->str: """simple docstring""" snake_case_ = LiltModel(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ , bbox=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ ) snake_case_ = model(UpperCAmelCase_ , bbox=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ ) snake_case_ = model(UpperCAmelCase_ , bbox=UpperCAmelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def lowerCAmelCase ( self : int , UpperCAmelCase_ : str , UpperCAmelCase_ : Any , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : str , UpperCAmelCase_ : List[Any] , ) ->Dict: """simple docstring""" snake_case_ = self.num_labels snake_case_ = LiltForTokenClassification(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model( UpperCAmelCase_ , bbox=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowerCAmelCase ( self : Any , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : str , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : int , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : List[str] , ) ->Dict: """simple docstring""" snake_case_ = LiltForQuestionAnswering(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model( UpperCAmelCase_ , bbox=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , start_positions=UpperCAmelCase_ , end_positions=UpperCAmelCase_ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def lowerCAmelCase ( self : int ) ->Optional[int]: """simple docstring""" snake_case_ = self.prepare_config_and_inputs() ( ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ) = config_and_inputs snake_case_ = { """input_ids""": input_ids, """bbox""": bbox, """token_type_ids""": token_type_ids, """attention_mask""": input_mask, } return config, inputs_dict @require_torch class __A (snake_case__ , snake_case__ , snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Optional[int] = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) __lowercase: Optional[Any] = ( { """feature-extraction""": LiltModel, """question-answering""": LiltForQuestionAnswering, """text-classification""": LiltForSequenceClassification, """token-classification""": LiltForTokenClassification, """zero-shot""": LiltForSequenceClassification, } if is_torch_available() else {} ) __lowercase: Union[str, Any] = False __lowercase: List[str] = False def lowerCAmelCase ( self : str , UpperCAmelCase_ : int , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[int] ) ->Optional[int]: """simple docstring""" return True def lowerCAmelCase ( self : Dict ) ->Union[str, Any]: """simple docstring""" snake_case_ = LiltModelTester(self ) snake_case_ = ConfigTester(self , config_class=UpperCAmelCase_ , hidden_size=37 ) def lowerCAmelCase ( self : str ) ->List[Any]: """simple docstring""" self.config_tester.run_common_tests() def lowerCAmelCase ( self : List[str] ) ->int: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] ) ->List[str]: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: snake_case_ = type self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def lowerCAmelCase ( self : List[Any] ) ->Dict: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->Dict: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*UpperCAmelCase_ ) @slow def lowerCAmelCase ( self : Union[str, Any] ) ->Optional[int]: """simple docstring""" for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ = LiltModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) @require_torch @slow class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : Optional[int] ) ->Dict: """simple docstring""" snake_case_ = LiltModel.from_pretrained("""SCUT-DLVCLab/lilt-roberta-en-base""" ).to(UpperCAmelCase_ ) snake_case_ = torch.tensor([[1, 2]] , device=UpperCAmelCase_ ) snake_case_ = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=UpperCAmelCase_ ) # forward pass with torch.no_grad(): snake_case_ = model(input_ids=UpperCAmelCase_ , bbox=UpperCAmelCase_ ) snake_case_ = torch.Size([1, 2, 768] ) snake_case_ = torch.tensor( [[-0.0_653, 0.0_950, -0.0_061], [-0.0_545, 0.0_926, -0.0_324]] , device=UpperCAmelCase_ , ) self.assertTrue(outputs.last_hidden_state.shape , UpperCAmelCase_ ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , UpperCAmelCase_ , atol=1E-3 ) )
2
0
"""simple docstring""" import warnings from typing import Any, Dict, List, Optional, Union import numpy as np from ...audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import PaddingStrategy, TensorType, logging __SCREAMING_SNAKE_CASE : Optional[int] = logging.get_logger(__name__) class __A (snake_case__): '''simple docstring''' __lowercase: Dict = ["""input_values""", """attention_mask"""] def __init__( self : List[Any] , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : int = 16_000 , UpperCAmelCase_ : float = 0.0 , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : int = 80 , UpperCAmelCase_ : int = 16 , UpperCAmelCase_ : int = 64 , UpperCAmelCase_ : str = "hann_window" , UpperCAmelCase_ : float = 1.0 , UpperCAmelCase_ : float = 80 , UpperCAmelCase_ : float = 7_600 , UpperCAmelCase_ : float = 1E-10 , UpperCAmelCase_ : int = 2 , UpperCAmelCase_ : bool = True , **UpperCAmelCase_ : str , ) ->str: """simple docstring""" super().__init__(feature_size=UpperCAmelCase_ , sampling_rate=UpperCAmelCase_ , padding_value=UpperCAmelCase_ , **UpperCAmelCase_ ) snake_case_ = do_normalize snake_case_ = return_attention_mask snake_case_ = num_mel_bins snake_case_ = hop_length snake_case_ = win_length snake_case_ = win_function snake_case_ = frame_signal_scale snake_case_ = fmin snake_case_ = fmax snake_case_ = mel_floor snake_case_ = reduction_factor snake_case_ = win_length * sampling_rate // 1_000 snake_case_ = hop_length * sampling_rate // 1_000 snake_case_ = optimal_fft_length(self.sample_size ) snake_case_ = (self.n_fft // 2) + 1 snake_case_ = window_function(window_length=self.sample_size , name=self.win_function , periodic=UpperCAmelCase_ ) snake_case_ = mel_filter_bank( num_frequency_bins=self.n_freqs , num_mel_filters=self.num_mel_bins , min_frequency=self.fmin , max_frequency=self.fmax , sampling_rate=self.sampling_rate , norm="""slaney""" , mel_scale="""slaney""" , ) if frame_signal_scale != 1.0: warnings.warn( """The argument `frame_signal_scale` is deprecated and will be removed in version 4.30.0 of Transformers""" , UpperCAmelCase_ , ) if reduction_factor != 2.0: warnings.warn( """The argument `reduction_factor` is deprecated and will be removed in version 4.30.0 of Transformers""" , UpperCAmelCase_ , ) @staticmethod # Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm def lowerCAmelCase ( UpperCAmelCase_ : List[np.ndarray] , UpperCAmelCase_ : List[np.ndarray] , UpperCAmelCase_ : float = 0.0 ) ->List[np.ndarray]: """simple docstring""" if attention_mask is not None: snake_case_ = np.array(UpperCAmelCase_ , np.intaa ) snake_case_ = [] for vector, length in zip(UpperCAmelCase_ , attention_mask.sum(-1 ) ): snake_case_ = (vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1E-7 ) if length < normed_slice.shape[0]: snake_case_ = padding_value normed_input_values.append(UpperCAmelCase_ ) else: snake_case_ = [(x - x.mean()) / np.sqrt(x.var() + 1E-7 ) for x in input_values] return normed_input_values def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : np.ndarray , ) ->np.ndarray: """simple docstring""" snake_case_ = spectrogram( UpperCAmelCase_ , window=self.window , frame_length=self.sample_size , hop_length=self.sample_stride , fft_length=self.n_fft , mel_filters=self.mel_filters , mel_floor=self.mel_floor , log_mel="""log10""" , ) return log_mel_spec.T def __call__( self : int , UpperCAmelCase_ : Optional[Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]] = None , UpperCAmelCase_ : Optional[Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]] = None , UpperCAmelCase_ : Union[bool, str, PaddingStrategy] = False , UpperCAmelCase_ : Optional[int] = None , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : Optional[int] = None , UpperCAmelCase_ : Optional[bool] = None , UpperCAmelCase_ : Optional[Union[str, TensorType]] = None , UpperCAmelCase_ : Optional[int] = None , **UpperCAmelCase_ : Optional[Any] , ) ->BatchFeature: """simple docstring""" if audio is None and audio_target is None: raise ValueError("""You must provide either `audio` or `audio_target` values.""" ) if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( F"""The model corresponding to this feature extractor: {self} was trained using a sampling rate of""" F""" {self.sampling_rate}. Please make sure that the provided audio input was sampled with""" F""" {self.sampling_rate} and not {sampling_rate}.""" ) else: logger.warning( """It is strongly recommended to pass the ``sampling_rate`` argument to this function. """ """Failing to do so can result in silent errors that might be hard to debug.""" ) if audio is not None: snake_case_ = self._process_audio( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , **UpperCAmelCase_ , ) else: snake_case_ = None if audio_target is not None: snake_case_ = self._process_audio( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , **UpperCAmelCase_ , ) if inputs is None: return inputs_target else: snake_case_ = inputs_target["""input_values"""] snake_case_ = inputs_target.get("""attention_mask""" ) if decoder_attention_mask is not None: snake_case_ = decoder_attention_mask return inputs def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : Union[bool, str, PaddingStrategy] = False , UpperCAmelCase_ : Optional[int] = None , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : Optional[int] = None , UpperCAmelCase_ : Optional[bool] = None , UpperCAmelCase_ : Optional[Union[str, TensorType]] = None , **UpperCAmelCase_ : Optional[int] , ) ->BatchFeature: """simple docstring""" snake_case_ = isinstance(UpperCAmelCase_ , np.ndarray ) and len(speech.shape ) > 1 if is_batched_numpy and len(speech.shape ) > 2: raise ValueError(F"""Only mono-channel audio is supported for input to {self}""" ) snake_case_ = is_batched_numpy or ( isinstance(UpperCAmelCase_ , (list, tuple) ) and (isinstance(speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: snake_case_ = [np.asarray(UpperCAmelCase_ , dtype=np.floataa ) for speech in speech] elif not is_batched and not isinstance(UpperCAmelCase_ , np.ndarray ): snake_case_ = np.asarray(UpperCAmelCase_ , dtype=np.floataa ) elif isinstance(UpperCAmelCase_ , np.ndarray ) and speech.dtype is np.dtype(np.floataa ): snake_case_ = speech.astype(np.floataa ) # always return batch if not is_batched: snake_case_ = [speech] # needed to make pad() work on spectrogram inputs snake_case_ = self.feature_size # convert into correct format for padding if is_target: snake_case_ = [self._extract_mel_features(UpperCAmelCase_ ) for waveform in speech] snake_case_ = BatchFeature({"""input_values""": features} ) snake_case_ = self.num_mel_bins else: snake_case_ = BatchFeature({"""input_values""": speech} ) snake_case_ = self.pad( UpperCAmelCase_ , padding=UpperCAmelCase_ , max_length=UpperCAmelCase_ , truncation=UpperCAmelCase_ , pad_to_multiple_of=UpperCAmelCase_ , return_attention_mask=UpperCAmelCase_ , **UpperCAmelCase_ , ) snake_case_ = feature_size_hack # convert input values to correct format snake_case_ = padded_inputs["""input_values"""] if not isinstance(input_values[0] , np.ndarray ): snake_case_ = [np.asarray(UpperCAmelCase_ , dtype=np.floataa ) for array in input_values] elif ( not isinstance(UpperCAmelCase_ , np.ndarray ) and isinstance(input_values[0] , np.ndarray ) and input_values[0].dtype is np.dtype(np.floataa ) ): snake_case_ = [array.astype(np.floataa ) for array in input_values] elif isinstance(UpperCAmelCase_ , np.ndarray ) and input_values.dtype is np.dtype(np.floataa ): snake_case_ = input_values.astype(np.floataa ) # convert attention_mask to correct format snake_case_ = padded_inputs.get("""attention_mask""" ) if attention_mask is not None: snake_case_ = [np.asarray(UpperCAmelCase_ , dtype=np.intaa ) for array in attention_mask] # zero-mean and unit-variance normalization if not is_target and self.do_normalize: snake_case_ = ( attention_mask if self._get_padding_strategies(UpperCAmelCase_ , max_length=UpperCAmelCase_ ) is not PaddingStrategy.DO_NOT_PAD else None ) snake_case_ = self.zero_mean_unit_var_norm( padded_inputs["""input_values"""] , attention_mask=UpperCAmelCase_ , padding_value=self.padding_value ) if return_tensors is not None: snake_case_ = padded_inputs.convert_to_tensors(UpperCAmelCase_ ) return padded_inputs def lowerCAmelCase ( self : Any ) ->Dict[str, Any]: """simple docstring""" snake_case_ = super().to_dict() # Don't serialize these as they are derived from the other properties. snake_case_ = ["""window""", """mel_filters""", """sample_size""", """sample_stride""", """n_fft""", """n_freqs"""] for name in names: if name in output: del output[name] return output
714
"""simple docstring""" from __future__ import annotations def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> list[int]: snake_case_ = 0 snake_case_ = len(_SCREAMING_SNAKE_CASE ) - 1 while i < j: if nums[i] + nums[j] == target: return [i, j] elif nums[i] + nums[j] < target: snake_case_ = i + 1 else: snake_case_ = j - 1 return [] if __name__ == "__main__": import doctest doctest.testmod() print(f"""{two_pointer([2, 7, 11, 15], 9) = }""")
2
0
"""simple docstring""" import gc import random import unittest import numpy as np import torch from diffusers import ( DDIMScheduler, KandinskyVaaControlnetPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) 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 from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class __A (snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Dict = KandinskyVaaControlnetPipeline __lowercase: str = ["""image_embeds""", """negative_image_embeds""", """hint"""] __lowercase: List[str] = ["""image_embeds""", """negative_image_embeds""", """hint"""] __lowercase: Union[str, Any] = [ """generator""", """height""", """width""", """latents""", """guidance_scale""", """num_inference_steps""", """return_dict""", """guidance_scale""", """num_images_per_prompt""", """output_type""", """return_dict""", ] __lowercase: Tuple = False @property def lowerCAmelCase ( self : Any ) ->Union[str, Any]: """simple docstring""" return 32 @property def lowerCAmelCase ( self : Optional[Any] ) ->Union[str, Any]: """simple docstring""" return 32 @property def lowerCAmelCase ( self : int ) ->List[str]: """simple docstring""" return self.time_input_dim @property def lowerCAmelCase ( self : Union[str, Any] ) ->Union[str, Any]: """simple docstring""" return self.time_input_dim * 4 @property def lowerCAmelCase ( self : Dict ) ->Optional[int]: """simple docstring""" return 100 @property def lowerCAmelCase ( self : str ) ->List[Any]: """simple docstring""" torch.manual_seed(0 ) snake_case_ = { """in_channels""": 8, # Out channels is double in channels because predicts mean and variance """out_channels""": 8, """addition_embed_type""": """image_hint""", """down_block_types""": ("""ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D"""), """up_block_types""": ("""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""), """mid_block_type""": """UNetMidBlock2DSimpleCrossAttn""", """block_out_channels""": (self.block_out_channels_a, self.block_out_channels_a * 2), """layers_per_block""": 1, """encoder_hid_dim""": self.text_embedder_hidden_size, """encoder_hid_dim_type""": """image_proj""", """cross_attention_dim""": self.cross_attention_dim, """attention_head_dim""": 4, """resnet_time_scale_shift""": """scale_shift""", """class_embed_type""": None, } snake_case_ = UNetaDConditionModel(**UpperCAmelCase_ ) return model @property def lowerCAmelCase ( self : Any ) ->Optional[Any]: """simple docstring""" return { "block_out_channels": [32, 32, 64, 64], "down_block_types": [ "DownEncoderBlock2D", "DownEncoderBlock2D", "DownEncoderBlock2D", "AttnDownEncoderBlock2D", ], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": ["AttnUpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"], "vq_embed_dim": 4, } @property def lowerCAmelCase ( self : Any ) ->int: """simple docstring""" torch.manual_seed(0 ) snake_case_ = VQModel(**self.dummy_movq_kwargs ) return model def lowerCAmelCase ( self : Dict ) ->str: """simple docstring""" snake_case_ = self.dummy_unet snake_case_ = self.dummy_movq snake_case_ = DDIMScheduler( num_train_timesteps=1_000 , beta_schedule="""linear""" , beta_start=0.00_085 , beta_end=0.012 , clip_sample=UpperCAmelCase_ , set_alpha_to_one=UpperCAmelCase_ , steps_offset=1 , prediction_type="""epsilon""" , thresholding=UpperCAmelCase_ , ) snake_case_ = { """unet""": unet, """scheduler""": scheduler, """movq""": movq, } return components def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[Any]=0 ) ->List[str]: """simple docstring""" snake_case_ = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(UpperCAmelCase_ ) ).to(UpperCAmelCase_ ) snake_case_ = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( UpperCAmelCase_ ) # create hint snake_case_ = floats_tensor((1, 3, 64, 64) , rng=random.Random(UpperCAmelCase_ ) ).to(UpperCAmelCase_ ) if str(UpperCAmelCase_ ).startswith("""mps""" ): snake_case_ = torch.manual_seed(UpperCAmelCase_ ) else: snake_case_ = torch.Generator(device=UpperCAmelCase_ ).manual_seed(UpperCAmelCase_ ) snake_case_ = { """image_embeds""": image_embeds, """negative_image_embeds""": negative_image_embeds, """hint""": hint, """generator""": generator, """height""": 64, """width""": 64, """guidance_scale""": 4.0, """num_inference_steps""": 2, """output_type""": """np""", } return inputs def lowerCAmelCase ( self : List[str] ) ->List[Any]: """simple docstring""" snake_case_ = """cpu""" snake_case_ = self.get_dummy_components() snake_case_ = self.pipeline_class(**UpperCAmelCase_ ) snake_case_ = pipe.to(UpperCAmelCase_ ) pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) snake_case_ = pipe(**self.get_dummy_inputs(UpperCAmelCase_ ) ) snake_case_ = output.images snake_case_ = pipe( **self.get_dummy_inputs(UpperCAmelCase_ ) , return_dict=UpperCAmelCase_ , )[0] snake_case_ = image[0, -3:, -3:, -1] snake_case_ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) snake_case_ = np.array( [0.6_959_826, 0.868_279, 0.7_558_092, 0.68_769_467, 0.85_805_804, 0.65_977_496, 0.44_885_302, 0.5_959_111, 0.4_251_595] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 ), F""" expected_slice {expected_slice}, but got {image_slice.flatten()}""" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 ), F""" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}""" @slow @require_torch_gpu class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : List[Any] ) ->Union[str, Any]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCAmelCase ( self : List[str] ) ->List[str]: """simple docstring""" snake_case_ = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinskyv22/kandinskyv22_controlnet_robotcat_fp16.npy""" ) snake_case_ = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinskyv22/hint_image_cat.png""" ) snake_case_ = torch.from_numpy(np.array(UpperCAmelCase_ ) ).float() / 255.0 snake_case_ = hint.permute(2 , 0 , 1 ).unsqueeze(0 ) snake_case_ = KandinskyVaaPriorPipeline.from_pretrained( """kandinsky-community/kandinsky-2-2-prior""" , torch_dtype=torch.floataa ) pipe_prior.to(UpperCAmelCase_ ) snake_case_ = KandinskyVaaControlnetPipeline.from_pretrained( """kandinsky-community/kandinsky-2-2-controlnet-depth""" , torch_dtype=torch.floataa ) snake_case_ = pipeline.to(UpperCAmelCase_ ) pipeline.set_progress_bar_config(disable=UpperCAmelCase_ ) snake_case_ = """A robot, 4k photo""" snake_case_ = torch.Generator(device="""cuda""" ).manual_seed(0 ) snake_case_ , snake_case_ = pipe_prior( UpperCAmelCase_ , generator=UpperCAmelCase_ , num_inference_steps=5 , negative_prompt="""""" , ).to_tuple() snake_case_ = torch.Generator(device="""cuda""" ).manual_seed(0 ) snake_case_ = pipeline( image_embeds=UpperCAmelCase_ , negative_image_embeds=UpperCAmelCase_ , hint=UpperCAmelCase_ , generator=UpperCAmelCase_ , num_inference_steps=100 , output_type="""np""" , ) snake_case_ = output.images[0] assert image.shape == (512, 512, 3) assert_mean_pixel_difference(UpperCAmelCase_ , UpperCAmelCase_ )
715
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __SCREAMING_SNAKE_CASE : Optional[Any] = { 'configuration_biogpt': ['BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BioGptConfig'], 'tokenization_biogpt': ['BioGptTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : Optional[Any] = [ 'BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST', 'BioGptForCausalLM', 'BioGptForTokenClassification', 'BioGptForSequenceClassification', 'BioGptModel', 'BioGptPreTrainedModel', ] if TYPE_CHECKING: from .configuration_biogpt import BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, BioGptConfig from .tokenization_biogpt import BioGptTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_biogpt import ( BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptPreTrainedModel, ) else: import sys __SCREAMING_SNAKE_CASE : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
2
0
"""simple docstring""" import string def _a ( _SCREAMING_SNAKE_CASE ) -> None: for key in range(len(string.ascii_uppercase ) ): snake_case_ = """""" for symbol in message: if symbol in string.ascii_uppercase: snake_case_ = string.ascii_uppercase.find(_SCREAMING_SNAKE_CASE ) snake_case_ = num - key if num < 0: snake_case_ = num + len(string.ascii_uppercase ) snake_case_ = translated + string.ascii_uppercase[num] else: snake_case_ = translated + symbol print(f"""Decryption using Key #{key}: {translated}""" ) def _a ( ) -> None: snake_case_ = input("""Encrypted message: """ ) snake_case_ = message.upper() decrypt(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": import doctest doctest.testmod() main()
716
"""simple docstring""" __SCREAMING_SNAKE_CASE : str = 'Input must be a string of 8 numbers plus letter' __SCREAMING_SNAKE_CASE : Dict = 'TRWAGMYFPDXBNJZSQVHLCKE' def _a ( _SCREAMING_SNAKE_CASE ) -> bool: if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): snake_case_ = f"""Expected string as input, found {type(_SCREAMING_SNAKE_CASE ).__name__}""" raise TypeError(_SCREAMING_SNAKE_CASE ) snake_case_ = spanish_id.replace("""-""" , """""" ).upper() if len(_SCREAMING_SNAKE_CASE ) != 9: raise ValueError(_SCREAMING_SNAKE_CASE ) try: snake_case_ = int(spanish_id_clean[0:8] ) snake_case_ = spanish_id_clean[8] except ValueError as ex: raise ValueError(_SCREAMING_SNAKE_CASE ) from ex if letter.isdigit(): raise ValueError(_SCREAMING_SNAKE_CASE ) return letter == LOOKUP_LETTERS[number % 23] if __name__ == "__main__": import doctest doctest.testmod()
2
0
"""simple docstring""" from typing import Dict, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, flip_channel_order, get_resize_output_image_size, 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_torch_available, is_torch_tensor, is_vision_available, logging if is_vision_available(): import PIL if is_torch_available(): import torch __SCREAMING_SNAKE_CASE : Union[str, Any] = logging.get_logger(__name__) class __A (snake_case__): '''simple docstring''' __lowercase: Any = ["""pixel_values"""] def __init__( self : List[str] , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Dict[str, int] = None , UpperCAmelCase_ : PILImageResampling = PILImageResampling.BILINEAR , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Union[int, float] = 1 / 255 , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Dict[str, int] = None , UpperCAmelCase_ : bool = True , **UpperCAmelCase_ : Tuple , ) ->None: """simple docstring""" super().__init__(**UpperCAmelCase_ ) snake_case_ = size if size is not None else {"""shortest_edge""": 224} snake_case_ = get_size_dict(UpperCAmelCase_ , default_to_square=UpperCAmelCase_ ) snake_case_ = crop_size if crop_size is not None else {"""height""": 256, """width""": 256} snake_case_ = get_size_dict(UpperCAmelCase_ , param_name="""crop_size""" ) snake_case_ = do_resize snake_case_ = size snake_case_ = resample snake_case_ = do_rescale snake_case_ = rescale_factor snake_case_ = do_center_crop snake_case_ = crop_size snake_case_ = do_flip_channel_order def lowerCAmelCase ( self : Optional[Any] , UpperCAmelCase_ : np.ndarray , UpperCAmelCase_ : Dict[str, int] , UpperCAmelCase_ : PILImageResampling = PIL.Image.BILINEAR , UpperCAmelCase_ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase_ : Union[str, Any] , ) ->np.ndarray: """simple docstring""" snake_case_ = get_size_dict(UpperCAmelCase_ , default_to_square=UpperCAmelCase_ ) if "shortest_edge" not in size: raise ValueError(F"""The `size` dictionary must contain the key `shortest_edge`. Got {size.keys()}""" ) snake_case_ = get_resize_output_image_size(UpperCAmelCase_ , size=size["""shortest_edge"""] , default_to_square=UpperCAmelCase_ ) return resize(UpperCAmelCase_ , size=UpperCAmelCase_ , resample=UpperCAmelCase_ , data_format=UpperCAmelCase_ , **UpperCAmelCase_ ) def lowerCAmelCase ( self : List[Any] , UpperCAmelCase_ : np.ndarray , UpperCAmelCase_ : Dict[str, int] , UpperCAmelCase_ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase_ : List[str] , ) ->np.ndarray: """simple docstring""" snake_case_ = 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()}""" ) return center_crop(UpperCAmelCase_ , size=(size["""height"""], size["""width"""]) , data_format=UpperCAmelCase_ , **UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : np.ndarray , UpperCAmelCase_ : Union[int, float] , UpperCAmelCase_ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase_ : str , ) ->Optional[int]: """simple docstring""" return rescale(UpperCAmelCase_ , scale=UpperCAmelCase_ , data_format=UpperCAmelCase_ , **UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : np.ndarray , UpperCAmelCase_ : Optional[Union[str, ChannelDimension]] = None ) ->np.ndarray: """simple docstring""" return flip_channel_order(UpperCAmelCase_ , data_format=UpperCAmelCase_ ) def lowerCAmelCase ( self : List[Any] , UpperCAmelCase_ : ImageInput , UpperCAmelCase_ : bool = None , UpperCAmelCase_ : Dict[str, int] = None , UpperCAmelCase_ : PILImageResampling = None , UpperCAmelCase_ : bool = None , UpperCAmelCase_ : float = None , UpperCAmelCase_ : bool = None , UpperCAmelCase_ : Dict[str, int] = None , UpperCAmelCase_ : bool = None , UpperCAmelCase_ : Optional[Union[str, TensorType]] = None , UpperCAmelCase_ : ChannelDimension = ChannelDimension.FIRST , **UpperCAmelCase_ : Any , ) ->PIL.Image.Image: """simple docstring""" snake_case_ = do_resize if do_resize is not None else self.do_resize snake_case_ = resample if resample is not None else self.resample snake_case_ = do_rescale if do_rescale is not None else self.do_rescale snake_case_ = rescale_factor if rescale_factor is not None else self.rescale_factor snake_case_ = do_center_crop if do_center_crop is not None else self.do_center_crop snake_case_ = ( do_flip_channel_order if do_flip_channel_order is not None else self.do_flip_channel_order ) snake_case_ = size if size is not None else self.size snake_case_ = get_size_dict(UpperCAmelCase_ , default_to_square=UpperCAmelCase_ ) snake_case_ = crop_size if crop_size is not None else self.crop_size snake_case_ = get_size_dict(UpperCAmelCase_ , param_name="""crop_size""" ) snake_case_ = 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: raise ValueError("""Size must be specified if do_resize is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) if do_center_crop and crop_size is None: raise ValueError("""Crop size must be specified if do_center_crop is True.""" ) # All transformations expect numpy arrays. snake_case_ = [to_numpy_array(UpperCAmelCase_ ) for image in images] if do_resize: snake_case_ = [self.resize(image=UpperCAmelCase_ , size=UpperCAmelCase_ , resample=UpperCAmelCase_ ) for image in images] if do_center_crop: snake_case_ = [self.center_crop(image=UpperCAmelCase_ , size=UpperCAmelCase_ ) for image in images] if do_rescale: snake_case_ = [self.rescale(image=UpperCAmelCase_ , scale=UpperCAmelCase_ ) for image in images] # the pretrained checkpoints assume images are BGR, not RGB if do_flip_channel_order: snake_case_ = [self.flip_channel_order(image=UpperCAmelCase_ ) for image in images] snake_case_ = [to_channel_dimension_format(UpperCAmelCase_ , UpperCAmelCase_ ) for image in images] snake_case_ = {"""pixel_values""": images} return BatchFeature(data=UpperCAmelCase_ , tensor_type=UpperCAmelCase_ ) def lowerCAmelCase ( self : int , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : List[Tuple] = None ) ->Dict: """simple docstring""" snake_case_ = 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_ ): snake_case_ = target_sizes.numpy() snake_case_ = [] for idx in range(len(UpperCAmelCase_ ) ): snake_case_ = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode="""bilinear""" , align_corners=UpperCAmelCase_ ) snake_case_ = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(UpperCAmelCase_ ) else: snake_case_ = logits.argmax(dim=1 ) snake_case_ = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
717
"""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 logging __SCREAMING_SNAKE_CASE : List[str] = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Optional[int] = {'vocab_file': 'spiece.model'} __SCREAMING_SNAKE_CASE : List[str] = { 'vocab_file': { 'albert-base-v1': 'https://huggingface.co/albert-base-v1/resolve/main/spiece.model', 'albert-large-v1': 'https://huggingface.co/albert-large-v1/resolve/main/spiece.model', 'albert-xlarge-v1': 'https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model', 'albert-xxlarge-v1': 'https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model', 'albert-base-v2': 'https://huggingface.co/albert-base-v2/resolve/main/spiece.model', 'albert-large-v2': 'https://huggingface.co/albert-large-v2/resolve/main/spiece.model', 'albert-xlarge-v2': 'https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model', 'albert-xxlarge-v2': 'https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model', } } __SCREAMING_SNAKE_CASE : List[str] = { 'albert-base-v1': 512, 'albert-large-v1': 512, 'albert-xlarge-v1': 512, 'albert-xxlarge-v1': 512, 'albert-base-v2': 512, 'albert-large-v2': 512, 'albert-xlarge-v2': 512, 'albert-xxlarge-v2': 512, } __SCREAMING_SNAKE_CASE : int = '▁' class __A (snake_case__): '''simple docstring''' __lowercase: Optional[Any] = VOCAB_FILES_NAMES __lowercase: Optional[int] = PRETRAINED_VOCAB_FILES_MAP __lowercase: Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : int , UpperCAmelCase_ : Any , UpperCAmelCase_ : Dict=True , UpperCAmelCase_ : Dict=True , UpperCAmelCase_ : List[str]=False , UpperCAmelCase_ : List[Any]="[CLS]" , UpperCAmelCase_ : Any="[SEP]" , UpperCAmelCase_ : str="<unk>" , UpperCAmelCase_ : str="[SEP]" , UpperCAmelCase_ : Optional[Any]="<pad>" , UpperCAmelCase_ : Optional[int]="[CLS]" , UpperCAmelCase_ : int="[MASK]" , UpperCAmelCase_ : Optional[Dict[str, Any]] = None , **UpperCAmelCase_ : Union[str, Any] , ) ->None: """simple docstring""" snake_case_ = ( AddedToken(UpperCAmelCase_ , lstrip=UpperCAmelCase_ , rstrip=UpperCAmelCase_ , normalized=UpperCAmelCase_ ) if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) else mask_token ) snake_case_ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=UpperCAmelCase_ , remove_space=UpperCAmelCase_ , keep_accents=UpperCAmelCase_ , bos_token=UpperCAmelCase_ , eos_token=UpperCAmelCase_ , unk_token=UpperCAmelCase_ , sep_token=UpperCAmelCase_ , pad_token=UpperCAmelCase_ , cls_token=UpperCAmelCase_ , mask_token=UpperCAmelCase_ , sp_model_kwargs=self.sp_model_kwargs , **UpperCAmelCase_ , ) snake_case_ = do_lower_case snake_case_ = remove_space snake_case_ = keep_accents snake_case_ = vocab_file snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(UpperCAmelCase_ ) @property def lowerCAmelCase ( self : List[Any] ) ->Dict: """simple docstring""" return len(self.sp_model ) def lowerCAmelCase ( self : str ) ->List[Any]: """simple docstring""" snake_case_ = {self.convert_ids_to_tokens(UpperCAmelCase_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Dict ) ->List[str]: """simple docstring""" snake_case_ = self.__dict__.copy() snake_case_ = None return state def __setstate__( self : Tuple , UpperCAmelCase_ : Optional[int] ) ->Optional[int]: """simple docstring""" snake_case_ = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): snake_case_ = {} snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : Any ) ->str: """simple docstring""" if self.remove_space: snake_case_ = """ """.join(inputs.strip().split() ) else: snake_case_ = inputs snake_case_ = outputs.replace("""``""" , """\"""" ).replace("""''""" , """\"""" ) if not self.keep_accents: snake_case_ = unicodedata.normalize("""NFKD""" , UpperCAmelCase_ ) snake_case_ = """""".join([c for c in outputs if not unicodedata.combining(UpperCAmelCase_ )] ) if self.do_lower_case: snake_case_ = outputs.lower() return outputs def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : str ) ->List[str]: """simple docstring""" snake_case_ = self.preprocess_text(UpperCAmelCase_ ) snake_case_ = self.sp_model.encode(UpperCAmelCase_ , out_type=UpperCAmelCase_ ) snake_case_ = [] for piece in pieces: if len(UpperCAmelCase_ ) > 1 and piece[-1] == str(""",""" ) and piece[-2].isdigit(): snake_case_ = self.sp_model.EncodeAsPieces(piece[:-1].replace(UpperCAmelCase_ , """""" ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: snake_case_ = cur_pieces[1:] else: snake_case_ = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(UpperCAmelCase_ ) else: new_pieces.append(UpperCAmelCase_ ) return new_pieces def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : Optional[int] ) ->Dict: """simple docstring""" return self.sp_model.PieceToId(UpperCAmelCase_ ) def lowerCAmelCase ( self : str , UpperCAmelCase_ : Union[str, Any] ) ->Optional[int]: """simple docstring""" return self.sp_model.IdToPiece(UpperCAmelCase_ ) def lowerCAmelCase ( self : str , UpperCAmelCase_ : Dict ) ->Any: """simple docstring""" snake_case_ = [] snake_case_ = """""" snake_case_ = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(UpperCAmelCase_ ) + token snake_case_ = True snake_case_ = [] else: current_sub_tokens.append(UpperCAmelCase_ ) snake_case_ = False out_string += self.sp_model.decode(UpperCAmelCase_ ) return out_string.strip() def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ) ->List[int]: """simple docstring""" snake_case_ = [self.sep_token_id] snake_case_ = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None , UpperCAmelCase_ : bool = False ) ->List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=UpperCAmelCase_ , token_ids_a=UpperCAmelCase_ , already_has_special_tokens=UpperCAmelCase_ ) if token_ids_a is not None: return [1] + ([0] * len(UpperCAmelCase_ )) + [1] + ([0] * len(UpperCAmelCase_ )) + [1] return [1] + ([0] * len(UpperCAmelCase_ )) + [1] def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ) ->List[int]: """simple docstring""" snake_case_ = [self.sep_token_id] snake_case_ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def lowerCAmelCase ( self : str , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None ) ->Tuple[str]: """simple docstring""" if not os.path.isdir(UpperCAmelCase_ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return snake_case_ = os.path.join( UpperCAmelCase_ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCAmelCase_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , UpperCAmelCase_ ) elif not os.path.isfile(self.vocab_file ): with open(UpperCAmelCase_ , """wb""" ) as fi: snake_case_ = self.sp_model.serialized_model_proto() fi.write(UpperCAmelCase_ ) return (out_vocab_file,)
2
0
"""simple docstring""" from __future__ import annotations def _a ( _SCREAMING_SNAKE_CASE ) -> bool: snake_case_ = str(_SCREAMING_SNAKE_CASE ) return n == n[::-1] def _a ( _SCREAMING_SNAKE_CASE = 1_000_000 ) -> int: snake_case_ = 0 for i in range(1 , _SCREAMING_SNAKE_CASE ): if is_palindrome(_SCREAMING_SNAKE_CASE ) and is_palindrome(bin(_SCREAMING_SNAKE_CASE ).split("""b""" )[1] ): total += i return total if __name__ == "__main__": print(solution(int(str(input().strip()))))
718
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE ) -> list: # bit count represents no. of bits in the gray code if bit_count < 0: raise ValueError("""The given input must be positive""" ) # get the generated string sequence snake_case_ = gray_code_sequence_string(_SCREAMING_SNAKE_CASE ) # # convert them to integers for i in range(len(_SCREAMING_SNAKE_CASE ) ): snake_case_ = int(sequence[i] , 2 ) return sequence def _a ( _SCREAMING_SNAKE_CASE ) -> list: # The approach is a recursive one # Base case achieved when either n = 0 or n=1 if bit_count == 0: return ["0"] if bit_count == 1: return ["0", "1"] snake_case_ = 1 << bit_count # defines the length of the sequence # 1<< n is equivalent to 2^n # recursive answer will generate answer for n-1 bits snake_case_ = gray_code_sequence_string(bit_count - 1 ) snake_case_ = [] # append 0 to first half of the smaller sequence generated for i in range(seq_len // 2 ): snake_case_ = """0""" + smaller_sequence[i] sequence.append(_SCREAMING_SNAKE_CASE ) # append 1 to second half ... start from the end of the list for i in reversed(range(seq_len // 2 ) ): snake_case_ = """1""" + smaller_sequence[i] sequence.append(_SCREAMING_SNAKE_CASE ) return sequence if __name__ == "__main__": import doctest doctest.testmod()
2
0
from functools import lru_cache @lru_cache def _a ( _SCREAMING_SNAKE_CASE ) -> int: if num < 0: raise ValueError("""Number should not be negative.""" ) return 1 if num in (0, 1) else num * factorial(num - 1 ) if __name__ == "__main__": import doctest doctest.testmod()
719
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __SCREAMING_SNAKE_CASE : Optional[Any] = { 'configuration_megatron_bert': ['MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MegatronBertConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : Tuple = [ 'MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'MegatronBertForCausalLM', 'MegatronBertForMaskedLM', 'MegatronBertForMultipleChoice', 'MegatronBertForNextSentencePrediction', 'MegatronBertForPreTraining', 'MegatronBertForQuestionAnswering', 'MegatronBertForSequenceClassification', 'MegatronBertForTokenClassification', 'MegatronBertModel', 'MegatronBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_megatron_bert import MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MegatronBertConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_megatron_bert import ( MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, MegatronBertPreTrainedModel, ) else: import sys __SCREAMING_SNAKE_CASE : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
2
0
"""simple docstring""" from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, is_torch_available, is_vision_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_VISION_2_SEQ_MAPPING if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_VISION_2_SEQ_MAPPING __SCREAMING_SNAKE_CASE : List[Any] = logging.get_logger(__name__) @add_end_docstrings(snake_case__) class __A (snake_case__): '''simple docstring''' def __init__( self : int , *UpperCAmelCase_ : str , **UpperCAmelCase_ : int ) ->Any: """simple docstring""" super().__init__(*UpperCAmelCase_ , **UpperCAmelCase_ ) requires_backends(self , """vision""" ) self.check_model_type( TF_MODEL_FOR_VISION_2_SEQ_MAPPING if self.framework == """tf""" else MODEL_FOR_VISION_2_SEQ_MAPPING ) def lowerCAmelCase ( self : Any , UpperCAmelCase_ : Dict=None , UpperCAmelCase_ : Union[str, Any]=None , UpperCAmelCase_ : int=None ) ->Dict: """simple docstring""" snake_case_ = {} snake_case_ = {} if prompt is not None: snake_case_ = prompt if generate_kwargs is not None: snake_case_ = generate_kwargs if max_new_tokens is not None: if "generate_kwargs" not in forward_kwargs: snake_case_ = {} if "max_new_tokens" in forward_kwargs["generate_kwargs"]: raise ValueError( """'max_new_tokens' is defined twice, once in 'generate_kwargs' and once as a direct parameter,""" """ please use only one""" ) snake_case_ = max_new_tokens return preprocess_params, forward_kwargs, {} def __call__( self : str , UpperCAmelCase_ : Union[str, List[str], "Image.Image", List["Image.Image"]] , **UpperCAmelCase_ : int ) ->int: """simple docstring""" return super().__call__(UpperCAmelCase_ , **UpperCAmelCase_ ) def lowerCAmelCase ( self : List[Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[Any]=None ) ->List[str]: """simple docstring""" snake_case_ = load_image(UpperCAmelCase_ ) if prompt is not None: if not isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): raise ValueError( F"""Received an invalid text input, got - {type(UpperCAmelCase_ )} - but expected a single string. """ """Note also that one single text can be provided for conditional image to text generation.""" ) snake_case_ = self.model.config.model_type if model_type == "git": snake_case_ = self.image_processor(images=UpperCAmelCase_ , return_tensors=self.framework ) snake_case_ = self.tokenizer(text=UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_ ).input_ids snake_case_ = [self.tokenizer.cls_token_id] + input_ids snake_case_ = torch.tensor(UpperCAmelCase_ ).unsqueeze(0 ) model_inputs.update({"""input_ids""": input_ids} ) elif model_type == "pix2struct": snake_case_ = self.image_processor(images=UpperCAmelCase_ , header_text=UpperCAmelCase_ , return_tensors=self.framework ) elif model_type != "vision-encoder-decoder": # vision-encoder-decoder does not support conditional generation snake_case_ = self.image_processor(images=UpperCAmelCase_ , return_tensors=self.framework ) snake_case_ = self.tokenizer(UpperCAmelCase_ , return_tensors=self.framework ) model_inputs.update(UpperCAmelCase_ ) else: raise ValueError(F"""Model type {model_type} does not support conditional text generation""" ) else: snake_case_ = self.image_processor(images=UpperCAmelCase_ , return_tensors=self.framework ) if self.model.config.model_type == "git" and prompt is None: snake_case_ = None return model_inputs def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : int=None ) ->List[str]: """simple docstring""" if ( "input_ids" in model_inputs and isinstance(model_inputs["""input_ids"""] , UpperCAmelCase_ ) and all(x is None for x in model_inputs["""input_ids"""] ) ): snake_case_ = None if generate_kwargs is None: snake_case_ = {} # FIXME: We need to pop here due to a difference in how `generation.py` and `generation.tf_utils.py` # parse inputs. In the Tensorflow version, `generate` raises an error if we don't use `input_ids` whereas # the PyTorch version matches it with `self.model.main_input_name` or `self.model.encoder.main_input_name` # in the `_prepare_model_inputs` method. snake_case_ = model_inputs.pop(self.model.main_input_name ) snake_case_ = self.model.generate(UpperCAmelCase_ , **UpperCAmelCase_ , **UpperCAmelCase_ ) return model_outputs def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : List[str] ) ->Optional[int]: """simple docstring""" snake_case_ = [] for output_ids in model_outputs: snake_case_ = { """generated_text""": self.tokenizer.decode( UpperCAmelCase_ , skip_special_tokens=UpperCAmelCase_ , ) } records.append(UpperCAmelCase_ ) return records
720
"""simple docstring""" import argparse import json import os from pathlib import Path import requests import torch from transformers import JukeboxConfig, JukeboxModel from transformers.utils import logging logging.set_verbosity_info() __SCREAMING_SNAKE_CASE : str = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Optional[int] = 'https://openaipublic.azureedge.net/jukebox/models/' __SCREAMING_SNAKE_CASE : List[Any] = { 'jukebox-1b-lyrics': [ '5b/vqvae.pth.tar', '5b/prior_level_0.pth.tar', '5b/prior_level_1.pth.tar', '1b_lyrics/prior_level_2.pth.tar', ], 'jukebox-5b-lyrics': [ '5b/vqvae.pth.tar', '5b/prior_level_0.pth.tar', '5b/prior_level_1.pth.tar', '5b_lyrics/prior_level_2.pth.tar', ], } def _a ( _SCREAMING_SNAKE_CASE ) -> int: if key.endswith(""".model.1.bias""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.1.bias""" , """.conv1d_1.bias""" ) elif key.endswith(""".model.1.weight""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.1.weight""" , """.conv1d_1.weight""" ) elif key.endswith(""".model.3.bias""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.3.bias""" , """.conv1d_2.bias""" ) elif key.endswith(""".model.3.weight""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.3.weight""" , """.conv1d_2.weight""" ) if "conditioner_blocks.0." in key: snake_case_ = key.replace("""conditioner_blocks.0""" , """conditioner_blocks""" ) if "prime_prior" in key: snake_case_ = key.replace("""prime_prior""" , """encoder""" ) if ".emb." in key and "total" not in key and "absolute" not in key and "relative" not in key: snake_case_ = key.replace(""".emb.""" , """.""" ) if key.endswith("""k""" ): # replace vqvae.X.k with vqvae.X.codebook return key.replace(""".k""" , """.codebook""" ) if "y_emb." in key: return key.replace("""y_emb.""" , """metadata_embedding.""" ) if "x_emb.emb." in key: snake_case_ = key.replace("""0.x_emb.emb""" , """embed_tokens""" ) if "prime_state_ln" in key: return key.replace("""prime_state_ln""" , """encoder.final_layer_norm""" ) if ".ln" in key: return key.replace(""".ln""" , """.layer_norm""" ) if "_ln" in key: return key.replace("""_ln""" , """_layer_norm""" ) if "prime_state_proj" in key: return key.replace("""prime_state_proj""" , """encoder.proj_in""" ) if "prime_x_out" in key: return key.replace("""prime_x_out""" , """encoder.lm_head""" ) if "prior.x_out" in key: return key.replace("""x_out""" , """fc_proj_out""" ) if "x_emb" in key: return key.replace("""x_emb""" , """embed_tokens""" ) return key def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: snake_case_ = {} import re snake_case_ = re.compile(r"""encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)""" ) snake_case_ = re.compile( r"""encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""encoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)""" ) snake_case_ = re.compile( r"""decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""decoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""conditioner_blocks.(\d*).cond.model.(\d*).(\d).(bias|weight)""" ) snake_case_ = re.compile( r"""conditioner_blocks.(\d*).cond.model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""conditioner_blocks.(\d*).cond.model.(\d*).(bias|weight)""" ) for original_key, value in state_dict.items(): # rename vqvae.encoder keys if re_encoder_block_conv_in.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_encoder_block_conv_in.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) snake_case_ = f"""encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.{groups[-1]}""" snake_case_ = re_encoder_block_conv_in.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_encoder_block_resnet.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_encoder_block_resnet.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) snake_case_ = {"""1""": 1, """3""": 2}[groups[-2]] snake_case_ = f"""encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.""" snake_case_ = f"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}""" snake_case_ = prefix + resnet_block snake_case_ = re_encoder_block_resnet.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_encoder_block_proj_out.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_encoder_block_proj_out.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = f"""encoders.{groups[0]}.level_blocks.{groups[1]}.proj_out.{groups[-1]}""" snake_case_ = re_encoder_block_proj_out.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # rename vqvae.decoder keys elif re_decoder_block_conv_out.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_decoder_block_conv_out.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) - 2 snake_case_ = f"""decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.{groups[-1]}""" snake_case_ = re_decoder_block_conv_out.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_decoder_block_resnet.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_decoder_block_resnet.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) - 2 snake_case_ = {"""1""": 1, """3""": 2}[groups[-2]] snake_case_ = f"""decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.""" snake_case_ = f"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}""" snake_case_ = prefix + resnet_block snake_case_ = re_decoder_block_resnet.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_decoder_block_proj_in.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_decoder_block_proj_in.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = f"""decoders.{groups[0]}.level_blocks.{groups[1]}.proj_in.{groups[-1]}""" snake_case_ = re_decoder_block_proj_in.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # rename prior cond.model to upsampler.upsample_block and resnet elif re_prior_cond_conv_out.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_prior_cond_conv_out.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[1] ) * 2 + int(groups[2] ) - 2 snake_case_ = f"""conditioner_blocks.upsampler.upsample_block.{block_index}.{groups[-1]}""" snake_case_ = re_prior_cond_conv_out.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_prior_cond_resnet.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_prior_cond_resnet.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[1] ) * 2 + int(groups[2] ) - 2 snake_case_ = {"""1""": 1, """3""": 2}[groups[-2]] snake_case_ = f"""conditioner_blocks.upsampler.upsample_block.{block_index}.""" snake_case_ = f"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}""" snake_case_ = prefix + resnet_block snake_case_ = re_prior_cond_resnet.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_prior_cond_proj_in.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_prior_cond_proj_in.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = f"""conditioner_blocks.upsampler.proj_in.{groups[-1]}""" snake_case_ = re_prior_cond_proj_in.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # keep original key else: snake_case_ = original_key snake_case_ = replace_key(_SCREAMING_SNAKE_CASE ) if f"""{key_prefix}.{key}""" not in model_state_dict or key is None: print(f"""failed converting {original_key} to {key}, does not match""" ) # handle missmatched shape elif value.shape != model_state_dict[f"""{key_prefix}.{key}"""].shape: snake_case_ = model_state_dict[f"""{key_prefix}.{key}"""] print(f"""{original_key}-> {key} : \nshape {val.shape} and { value.shape}, do not match""" ) snake_case_ = original_key snake_case_ = original_key snake_case_ = value return new_dict @torch.no_grad() def _a ( _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> Optional[int]: for file in MODEL_MAPPING[model_name]: if not os.path.isfile(f"""{pytorch_dump_folder_path}/{file.split("/" )[-1]}""" ): snake_case_ = requests.get(f"""{PREFIX}{file}""" , allow_redirects=_SCREAMING_SNAKE_CASE ) os.makedirs(f"""{pytorch_dump_folder_path}/""" , exist_ok=_SCREAMING_SNAKE_CASE ) open(f"""{pytorch_dump_folder_path}/{file.split("/" )[-1]}""" , """wb""" ).write(r.content ) snake_case_ = MODEL_MAPPING[model_name.split("""/""" )[-1]] snake_case_ = JukeboxConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) snake_case_ = JukeboxModel(_SCREAMING_SNAKE_CASE ) snake_case_ = [] snake_case_ = {} for i, dict_name in enumerate(_SCREAMING_SNAKE_CASE ): snake_case_ = torch.load(f"""{pytorch_dump_folder_path}/{dict_name.split("/" )[-1]}""" )["""model"""] snake_case_ = {} for k in old_dic.keys(): if k.endswith(""".b""" ): snake_case_ = old_dic[k] elif k.endswith(""".w""" ): snake_case_ = old_dic[k] elif "level_2" not in dict_name and "cond.model." in k: snake_case_ = old_dic[k] else: snake_case_ = old_dic[k] snake_case_ = """vqvae""" if i == 0 else f"""priors.{3 - i}""" snake_case_ = fix_jukebox_keys(_SCREAMING_SNAKE_CASE , model.state_dict() , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) weight_dict.append(_SCREAMING_SNAKE_CASE ) snake_case_ = weight_dict.pop(0 ) model.vqvae.load_state_dict(_SCREAMING_SNAKE_CASE ) for i in range(len(_SCREAMING_SNAKE_CASE ) ): model.priors[i].load_state_dict(weight_dict[2 - i] ) Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) with open(f"""{pytorch_dump_folder_path}/mapping.json""" , """w""" ) as txtfile: json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) print(f"""Saving model {model_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) return weight_dict if __name__ == "__main__": __SCREAMING_SNAKE_CASE : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='jukebox-5b-lyrics', type=str, help='Name of the model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default='jukebox-5b-lyrics-converted', type=str, help='Path to the output PyTorch model directory.', ) __SCREAMING_SNAKE_CASE : str = parser.parse_args() convert_openai_checkpoint(args.model_name, args.pytorch_dump_folder_path)
2
0
"""simple docstring""" import io import itertools import json from dataclasses import dataclass from typing import Optional import pyarrow as pa import pyarrow.json as paj import datasets from datasets.table import table_cast from datasets.utils.file_utils import readline __SCREAMING_SNAKE_CASE : str = datasets.utils.logging.get_logger(__name__) @dataclass class __A (datasets.BuilderConfig): '''simple docstring''' __lowercase: Optional[datasets.Features] = None __lowercase: str = "utf-8" __lowercase: Optional[str] = None __lowercase: Optional[str] = None __lowercase: bool = True # deprecated __lowercase: Optional[int] = None # deprecated __lowercase: int = 10 << 20 # 10MB __lowercase: Optional[bool] = None class __A (datasets.ArrowBasedBuilder): '''simple docstring''' __lowercase: str = JsonConfig def lowerCAmelCase ( self : Optional[int] ) ->Tuple: """simple docstring""" if self.config.block_size is not None: logger.warning("""The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead""" ) snake_case_ = self.config.block_size if self.config.use_threads is not True: logger.warning( """The JSON loader parameter `use_threads` is deprecated and doesn't have any effect anymore.""" ) if self.config.newlines_in_values is not None: raise ValueError("""The JSON loader parameter `newlines_in_values` is no longer supported""" ) return datasets.DatasetInfo(features=self.config.features ) def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : Union[str, Any] ) ->List[Any]: """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}""" ) snake_case_ = dl_manager.download_and_extract(self.config.data_files ) if isinstance(UpperCAmelCase_ , (str, list, tuple) ): snake_case_ = data_files if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): snake_case_ = [files] snake_case_ = [dl_manager.iter_files(UpperCAmelCase_ ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"""files""": files} )] snake_case_ = [] for split_name, files in data_files.items(): if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): snake_case_ = [files] snake_case_ = [dl_manager.iter_files(UpperCAmelCase_ ) for file in files] splits.append(datasets.SplitGenerator(name=UpperCAmelCase_ , gen_kwargs={"""files""": files} ) ) return splits def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : pa.Table ) ->pa.Table: """simple docstring""" if self.config.features is not None: # adding missing columns for column_name in set(self.config.features ) - set(pa_table.column_names ): snake_case_ = self.config.features.arrow_schema.field(UpperCAmelCase_ ).type snake_case_ = pa_table.append_column(UpperCAmelCase_ , pa.array([None] * len(UpperCAmelCase_ ) , type=UpperCAmelCase_ ) ) # more expensive cast to support nested structures with keys in a different order # allows str <-> int/float or str to Audio for example snake_case_ = table_cast(UpperCAmelCase_ , self.config.features.arrow_schema ) return pa_table def lowerCAmelCase ( self : Optional[Any] , UpperCAmelCase_ : str ) ->List[str]: """simple docstring""" for file_idx, file in enumerate(itertools.chain.from_iterable(UpperCAmelCase_ ) ): # If the file is one json object and if we need to look at the list of items in one specific field if self.config.field is not None: with open(UpperCAmelCase_ , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f: snake_case_ = json.load(UpperCAmelCase_ ) # We keep only the field we are interested in snake_case_ = dataset[self.config.field] # We accept two format: a list of dicts or a dict of lists if isinstance(UpperCAmelCase_ , (list, tuple) ): snake_case_ = set().union(*[row.keys() for row in dataset] ) snake_case_ = {col: [row.get(UpperCAmelCase_ ) for row in dataset] for col in keys} else: snake_case_ = dataset snake_case_ = pa.Table.from_pydict(UpperCAmelCase_ ) yield file_idx, self._cast_table(UpperCAmelCase_ ) # If the file has one json object per line else: with open(UpperCAmelCase_ , """rb""" ) as f: snake_case_ = 0 # Use block_size equal to the chunk size divided by 32 to leverage multithreading # Set a default minimum value of 16kB if the chunk size is really small snake_case_ = max(self.config.chunksize // 32 , 16 << 10 ) snake_case_ = ( self.config.encoding_errors if self.config.encoding_errors is not None else """strict""" ) while True: snake_case_ = f.read(self.config.chunksize ) if not batch: break # Finish current line try: batch += f.readline() except (AttributeError, io.UnsupportedOperation): batch += readline(UpperCAmelCase_ ) # PyArrow only accepts utf-8 encoded bytes if self.config.encoding != "utf-8": snake_case_ = batch.decode(self.config.encoding , errors=UpperCAmelCase_ ).encode("""utf-8""" ) try: while True: try: snake_case_ = paj.read_json( io.BytesIO(UpperCAmelCase_ ) , read_options=paj.ReadOptions(block_size=UpperCAmelCase_ ) ) break except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e: if ( isinstance(UpperCAmelCase_ , pa.ArrowInvalid ) and "straddling" not in str(UpperCAmelCase_ ) or block_size > len(UpperCAmelCase_ ) ): raise else: # Increase the block size in case it was too small. # The block size will be reset for the next file. logger.debug( F"""Batch of {len(UpperCAmelCase_ )} bytes couldn't be parsed with block_size={block_size}. Retrying with block_size={block_size * 2}.""" ) block_size *= 2 except pa.ArrowInvalid as e: try: with open( UpperCAmelCase_ , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f: snake_case_ = json.load(UpperCAmelCase_ ) except json.JSONDecodeError: logger.error(F"""Failed to read file '{file}' with error {type(UpperCAmelCase_ )}: {e}""" ) raise e # If possible, parse the file as a list of json objects and exit the loop if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): # list is the only sequence type supported in JSON try: snake_case_ = set().union(*[row.keys() for row in dataset] ) snake_case_ = {col: [row.get(UpperCAmelCase_ ) for row in dataset] for col in keys} snake_case_ = pa.Table.from_pydict(UpperCAmelCase_ ) except (pa.ArrowInvalid, AttributeError) as e: logger.error(F"""Failed to read file '{file}' with error {type(UpperCAmelCase_ )}: {e}""" ) raise ValueError(F"""Not able to read records in the JSON file at {file}.""" ) from None yield file_idx, self._cast_table(UpperCAmelCase_ ) break else: logger.error(F"""Failed to read file '{file}' with error {type(UpperCAmelCase_ )}: {e}""" ) raise ValueError( F"""Not able to read records in the JSON file at {file}. """ F"""You should probably indicate the field of the JSON file containing your records. """ F"""This JSON file contain the following fields: {str(list(dataset.keys() ) )}. """ F"""Select the correct one and provide it as `field='XXX'` to the dataset loading method. """ ) from None # 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(UpperCAmelCase_ ) batch_idx += 1
721
"""simple docstring""" # XXX: we want transformers master here - in the absense of conftest manipulating sys.path: # hack it in for now: import sys from pathlib import Path __SCREAMING_SNAKE_CASE : Union[str, Any] = Path(__file__).resolve().parents[3] / 'src' sys.path.insert(1, str(git_repo_path)) import dataclasses # noqa import io # noqa import itertools # noqa import json # noqa import os # noqa import unittest # noqa from copy import deepcopy # noqa from parameterized import parameterized # noqa from transformers import TrainingArguments, is_torch_available # noqa from transformers.deepspeed import is_deepspeed_available # noqa from transformers.file_utils import WEIGHTS_NAME # noqa from transformers.testing_utils import ( # noqa CaptureLogger, ExtendSysPath, TestCasePlus, execute_subprocess_async, get_gpu_count, mockenv_context, require_deepspeed, require_torch_gpu, require_torch_multi_gpu, slow, ) from transformers.trainer_utils import set_seed # noqa set_seed(42) __SCREAMING_SNAKE_CASE : Dict = {'base': 'patrickvonplaten/wav2vec2_tiny_random', 'robust': 'patrickvonplaten/wav2vec2_tiny_random_robust'} __SCREAMING_SNAKE_CASE : Dict = 'zero2' __SCREAMING_SNAKE_CASE : List[Any] = 'zero3' __SCREAMING_SNAKE_CASE : int = [ZEROa, ZEROa] def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: # customize the test name generator function as we want both params to appear in the sub-test # name, as by default it shows only the first param snake_case_ = parameterized.to_safe_name("""_""".join(str(_SCREAMING_SNAKE_CASE ) for x in param.args ) ) return f"""{func.__name__}_{param_based_name}""" # Cartesian-product of zero stages with models to test __SCREAMING_SNAKE_CASE : Dict = list(itertools.product(stages, models.keys())) @slow @require_deepspeed @require_torch_gpu class __A (snake_case__): '''simple docstring''' @parameterized.expand(UpperCAmelCase_ , name_func=UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Union[str, Any] ) ->Any: """simple docstring""" self.run_and_check( stage=UpperCAmelCase_ , model=UpperCAmelCase_ , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) @require_torch_multi_gpu @parameterized.expand(UpperCAmelCase_ , name_func=UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[Any] ) ->Optional[Any]: """simple docstring""" self.run_and_check( stage=UpperCAmelCase_ , model=UpperCAmelCase_ , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) @parameterized.expand(UpperCAmelCase_ , name_func=UpperCAmelCase_ ) def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[int] ) ->List[str]: """simple docstring""" self.run_and_check( stage=UpperCAmelCase_ , model=UpperCAmelCase_ , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) @require_torch_multi_gpu @parameterized.expand(UpperCAmelCase_ , name_func=UpperCAmelCase_ ) def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : str , UpperCAmelCase_ : List[Any] ) ->Optional[int]: """simple docstring""" self.run_and_check( stage=UpperCAmelCase_ , model=UpperCAmelCase_ , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : Union[str, Any] ) ->Optional[int]: """simple docstring""" pass def lowerCAmelCase ( self : Any , UpperCAmelCase_ : str , UpperCAmelCase_ : str , UpperCAmelCase_ : int = 10 , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : bool = True , ) ->List[str]: """simple docstring""" snake_case_ = models[model] snake_case_ = self.run_trainer( stage=UpperCAmelCase_ , model_name=UpperCAmelCase_ , eval_steps=UpperCAmelCase_ , num_train_epochs=1 , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) self.do_checks(UpperCAmelCase_ ) return output_dir def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : str , UpperCAmelCase_ : int = 10 , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : bool = True , ) ->List[str]: """simple docstring""" snake_case_ = self.get_auto_remove_tmp_dir("""./xxx""" , after=UpperCAmelCase_ ) snake_case_ = F""" --model_name_or_path {model_name} --dataset_name hf-internal-testing/librispeech_asr_dummy --dataset_config_name clean --train_split_name validation --validation_split_name validation --output_dir {output_dir} --num_train_epochs {str(UpperCAmelCase_ )} --per_device_train_batch_size 2 --per_device_eval_batch_size 2 --evaluation_strategy steps --learning_rate 5e-4 --warmup_steps 8 --orthography timit --preprocessing_num_workers 1 --group_by_length --freeze_feature_extractor --report_to none --save_steps 0 --eval_steps {eval_steps} --report_to none """.split() if fpaa: args.extend(["""--fp16"""] ) # currently ds_config_wav2vec2_zero.json requires "zero_optimization.find_unused_parameters": true, # hence the separate config files snake_case_ = F"""--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json""".split() snake_case_ = [F"""{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py"""] snake_case_ = self.get_launcher(UpperCAmelCase_ ) snake_case_ = launcher + script + args + ds_args # keep for quick debug # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die execute_subprocess_async(UpperCAmelCase_ , env=self.get_env() ) return output_dir def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : Any=False ) ->Tuple: """simple docstring""" snake_case_ = min(2 , get_gpu_count() ) if distributed else 1 return F"""deepspeed --num_nodes 1 --num_gpus {num_gpus}""".split()
2
0
"""simple docstring""" import inspect import unittest from transformers import DPTConfig from transformers.file_utils import is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device 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 MODEL_MAPPING, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel from transformers.models.dpt.modeling_dpt import DPT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DPTImageProcessor class __A : '''simple docstring''' def __init__( self : Optional[Any] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : int=2 , UpperCAmelCase_ : str=32 , UpperCAmelCase_ : Any=16 , UpperCAmelCase_ : Optional[int]=3 , UpperCAmelCase_ : Optional[int]=True , UpperCAmelCase_ : Optional[Any]=True , UpperCAmelCase_ : Dict=32 , UpperCAmelCase_ : Dict=4 , UpperCAmelCase_ : Any=[0, 1, 2, 3] , UpperCAmelCase_ : Optional[int]=4 , UpperCAmelCase_ : Tuple=37 , UpperCAmelCase_ : List[str]="gelu" , UpperCAmelCase_ : List[str]=0.1 , UpperCAmelCase_ : Dict=0.1 , UpperCAmelCase_ : Union[str, Any]=0.02 , UpperCAmelCase_ : Union[str, Any]=3 , UpperCAmelCase_ : Any=[1, 384, 24, 24] , UpperCAmelCase_ : List[Any]=True , UpperCAmelCase_ : str=None , ) ->Any: """simple docstring""" snake_case_ = parent snake_case_ = batch_size snake_case_ = image_size snake_case_ = patch_size snake_case_ = num_channels snake_case_ = is_training snake_case_ = use_labels snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = backbone_out_indices snake_case_ = num_attention_heads snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = initializer_range snake_case_ = num_labels snake_case_ = backbone_featmap_shape snake_case_ = scope snake_case_ = is_hybrid # sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token) snake_case_ = (image_size // patch_size) ** 2 snake_case_ = num_patches + 1 def lowerCAmelCase ( self : List[str] ) ->Union[str, Any]: """simple docstring""" snake_case_ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case_ = None if self.use_labels: snake_case_ = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) snake_case_ = self.get_config() return config, pixel_values, labels def lowerCAmelCase ( self : List[Any] ) ->List[str]: """simple docstring""" snake_case_ = { """global_padding""": """same""", """layer_type""": """bottleneck""", """depths""": [3, 4, 9], """out_features""": ["""stage1""", """stage2""", """stage3"""], """embedding_dynamic_padding""": True, """hidden_sizes""": [96, 192, 384, 768], """num_groups""": 2, } return DPTConfig( 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 , backbone_out_indices=self.backbone_out_indices , 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=UpperCAmelCase_ , initializer_range=self.initializer_range , is_hybrid=self.is_hybrid , backbone_config=UpperCAmelCase_ , backbone_featmap_shape=self.backbone_featmap_shape , ) def lowerCAmelCase ( self : str , UpperCAmelCase_ : int , UpperCAmelCase_ : Dict , UpperCAmelCase_ : str ) ->Union[str, Any]: """simple docstring""" snake_case_ = DPTModel(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCAmelCase ( self : str , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int , UpperCAmelCase_ : Union[str, Any] ) ->Union[str, Any]: """simple docstring""" snake_case_ = self.num_labels snake_case_ = DPTForDepthEstimation(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ ) self.parent.assertEqual(result.predicted_depth.shape , (self.batch_size, self.image_size, self.image_size) ) def lowerCAmelCase ( self : int , UpperCAmelCase_ : str , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int ) ->List[Any]: """simple docstring""" snake_case_ = self.num_labels snake_case_ = DPTForSemanticSegmentation(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size, self.image_size) ) def lowerCAmelCase ( self : Any ) ->List[Any]: """simple docstring""" snake_case_ = self.prepare_config_and_inputs() snake_case_ , snake_case_ , snake_case_ = config_and_inputs snake_case_ = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class __A (snake_case__ , snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Dict = (DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else () __lowercase: Optional[Any] = ( { """depth-estimation""": DPTForDepthEstimation, """feature-extraction""": DPTModel, """image-segmentation""": DPTForSemanticSegmentation, } if is_torch_available() else {} ) __lowercase: Union[str, Any] = False __lowercase: Tuple = False __lowercase: Tuple = False def lowerCAmelCase ( self : Optional[int] ) ->List[Any]: """simple docstring""" snake_case_ = DPTModelTester(self ) snake_case_ = ConfigTester(self , config_class=UpperCAmelCase_ , has_text_modality=UpperCAmelCase_ , hidden_size=37 ) def lowerCAmelCase ( self : List[Any] ) ->Any: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason="""DPT does not use inputs_embeds""" ) def lowerCAmelCase ( self : Union[str, Any] ) ->str: """simple docstring""" pass def lowerCAmelCase ( self : Dict ) ->Union[str, Any]: """simple docstring""" snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ = model_class(UpperCAmelCase_ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) snake_case_ = model.get_output_embeddings() self.assertTrue(x is None or isinstance(UpperCAmelCase_ , nn.Linear ) ) def lowerCAmelCase ( self : Optional[Any] ) ->Union[str, Any]: """simple docstring""" snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ = model_class(UpperCAmelCase_ ) snake_case_ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case_ = [*signature.parameters.keys()] snake_case_ = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] ) ->Optional[Any]: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def lowerCAmelCase ( self : Tuple ) ->str: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_depth_estimation(*UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->Optional[int]: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->Tuple: """simple docstring""" for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() snake_case_ = True if model_class in get_values(UpperCAmelCase_ ): continue snake_case_ = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.train() snake_case_ = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ , return_labels=UpperCAmelCase_ ) snake_case_ = model(**UpperCAmelCase_ ).loss loss.backward() def lowerCAmelCase ( self : Tuple ) ->List[str]: """simple docstring""" for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() snake_case_ = False snake_case_ = True if model_class in get_values(UpperCAmelCase_ ) or not model_class.supports_gradient_checkpointing: continue snake_case_ = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.gradient_checkpointing_enable() model.train() snake_case_ = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ , return_labels=UpperCAmelCase_ ) snake_case_ = model(**UpperCAmelCase_ ).loss loss.backward() def lowerCAmelCase ( self : Optional[Any] ) ->Dict: """simple docstring""" snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() snake_case_ = _config_zero_init(UpperCAmelCase_ ) for model_class in self.all_model_classes: snake_case_ = model_class(config=UpperCAmelCase_ ) # Skip the check for the backbone snake_case_ = [] for name, module in model.named_modules(): if module.__class__.__name__ == "DPTViTHybridEmbeddings": snake_case_ = [F"""{name}.{key}""" for key in module.state_dict().keys()] break for name, param in model.named_parameters(): if param.requires_grad: if name in backbone_params: continue 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""" , ) @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def lowerCAmelCase ( self : Tuple ) ->List[str]: """simple docstring""" pass @slow def lowerCAmelCase ( self : Union[str, Any] ) ->Dict: """simple docstring""" for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]: snake_case_ = DPTModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) def lowerCAmelCase ( self : List[Any] ) ->Union[str, Any]: """simple docstring""" snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() snake_case_ = """add""" with self.assertRaises(UpperCAmelCase_ ): snake_case_ = DPTForDepthEstimation(UpperCAmelCase_ ) def _a ( ) -> Any: snake_case_ = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision @slow class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : Dict ) ->str: """simple docstring""" snake_case_ = DPTImageProcessor.from_pretrained("""Intel/dpt-hybrid-midas""" ) snake_case_ = DPTForDepthEstimation.from_pretrained("""Intel/dpt-hybrid-midas""" ).to(UpperCAmelCase_ ) snake_case_ = prepare_img() snake_case_ = image_processor(images=UpperCAmelCase_ , return_tensors="""pt""" ).to(UpperCAmelCase_ ) # forward pass with torch.no_grad(): snake_case_ = model(**UpperCAmelCase_ ) snake_case_ = outputs.predicted_depth # verify the predicted depth snake_case_ = torch.Size((1, 384, 384) ) self.assertEqual(predicted_depth.shape , UpperCAmelCase_ ) snake_case_ = torch.tensor( [[[5.6_437, 5.6_146, 5.6_511], [5.4_371, 5.5_649, 5.5_958], [5.5_215, 5.5_184, 5.5_293]]] ).to(UpperCAmelCase_ ) self.assertTrue(torch.allclose(outputs.predicted_depth[:3, :3, :3] / 100 , UpperCAmelCase_ , atol=1E-4 ) )
700
"""simple docstring""" import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, Features, Value from .base import TaskTemplate @dataclass(frozen=snake_case__) class __A (snake_case__): '''simple docstring''' __lowercase: str = field(default="""automatic-speech-recognition""" , metadata={"""include_in_asdict_even_if_is_default""": True}) __lowercase: ClassVar[Features] = Features({"""audio""": Audio()}) __lowercase: ClassVar[Features] = Features({"""transcription""": Value("""string""")}) __lowercase: str = "audio" __lowercase: str = "transcription" def lowerCAmelCase ( self : List[Any] , UpperCAmelCase_ : Any ) ->int: """simple docstring""" if self.audio_column not in features: raise ValueError(F"""Column {self.audio_column} is not present in features.""" ) if not isinstance(features[self.audio_column] , UpperCAmelCase_ ): raise ValueError(F"""Column {self.audio_column} is not an Audio type.""" ) snake_case_ = copy.deepcopy(self ) snake_case_ = self.input_schema.copy() snake_case_ = features[self.audio_column] snake_case_ = input_schema return task_template @property def lowerCAmelCase ( self : List[str] ) ->Dict[str, str]: """simple docstring""" return {self.audio_column: "audio", self.transcription_column: "transcription"}
2
0
"""simple docstring""" import itertools import math def _a ( _SCREAMING_SNAKE_CASE ) -> bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(_SCREAMING_SNAKE_CASE ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def _a ( ) -> List[Any]: snake_case_ = 2 while True: if is_prime(_SCREAMING_SNAKE_CASE ): yield num num += 1 def _a ( _SCREAMING_SNAKE_CASE = 10_001 ) -> int: return next(itertools.islice(prime_generator() , nth - 1 , _SCREAMING_SNAKE_CASE ) ) if __name__ == "__main__": print(f"""{solution() = }""")
701
"""simple docstring""" from functools import reduce __SCREAMING_SNAKE_CASE : Tuple = ( '73167176531330624919225119674426574742355349194934' '96983520312774506326239578318016984801869478851843' '85861560789112949495459501737958331952853208805511' '12540698747158523863050715693290963295227443043557' '66896648950445244523161731856403098711121722383113' '62229893423380308135336276614282806444486645238749' '30358907296290491560440772390713810515859307960866' '70172427121883998797908792274921901699720888093776' '65727333001053367881220235421809751254540594752243' '52584907711670556013604839586446706324415722155397' '53697817977846174064955149290862569321978468622482' '83972241375657056057490261407972968652414535100474' '82166370484403199890008895243450658541227588666881' '16427171479924442928230863465674813919123162824586' '17866458359124566529476545682848912883142607690042' '24219022671055626321111109370544217506941658960408' '07198403850962455444362981230987879927244284909188' '84580156166097919133875499200524063689912560717606' '05886116467109405077541002256983155200055935729725' '71636269561882670428252483600823257530420752963450' ) def _a ( _SCREAMING_SNAKE_CASE = N ) -> int: return max( # mypy cannot properly interpret reduce int(reduce(lambda _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : str(int(_SCREAMING_SNAKE_CASE ) * int(_SCREAMING_SNAKE_CASE ) ) , n[i : i + 13] ) ) for i in range(len(_SCREAMING_SNAKE_CASE ) - 12 ) ) if __name__ == "__main__": print(f"""{solution() = }""")
2
0
"""simple docstring""" import math from typing import Optional import numpy as np from ...configuration_utils import PretrainedConfig from ...utils import logging __SCREAMING_SNAKE_CASE : Dict = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Union[str, Any] = { 'facebook/encodec_24khz': 'https://huggingface.co/facebook/encodec_24khz/resolve/main/config.json', 'facebook/encodec_48khz': 'https://huggingface.co/facebook/encodec_48khz/resolve/main/config.json', } class __A (snake_case__): '''simple docstring''' __lowercase: str = """encodec""" def __init__( self : Optional[Any] , UpperCAmelCase_ : int=[1.5, 3.0, 6.0, 12.0, 24.0] , UpperCAmelCase_ : Dict=24_000 , UpperCAmelCase_ : List[str]=1 , UpperCAmelCase_ : Tuple=False , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : Dict=128 , UpperCAmelCase_ : int=32 , UpperCAmelCase_ : Tuple=1 , UpperCAmelCase_ : Any=[8, 5, 4, 2] , UpperCAmelCase_ : Union[str, Any]="weight_norm" , UpperCAmelCase_ : Dict=7 , UpperCAmelCase_ : str=7 , UpperCAmelCase_ : int=3 , UpperCAmelCase_ : List[str]=2 , UpperCAmelCase_ : List[Any]=True , UpperCAmelCase_ : Tuple="reflect" , UpperCAmelCase_ : List[Any]=2 , UpperCAmelCase_ : Dict=2 , UpperCAmelCase_ : Union[str, Any]=1.0 , UpperCAmelCase_ : List[str]=1_024 , UpperCAmelCase_ : int=None , UpperCAmelCase_ : str=True , **UpperCAmelCase_ : str , ) ->Optional[Any]: """simple docstring""" snake_case_ = target_bandwidths snake_case_ = sampling_rate snake_case_ = audio_channels snake_case_ = normalize snake_case_ = chunk_length_s snake_case_ = overlap snake_case_ = hidden_size snake_case_ = num_filters snake_case_ = num_residual_layers snake_case_ = upsampling_ratios snake_case_ = norm_type snake_case_ = kernel_size snake_case_ = last_kernel_size snake_case_ = residual_kernel_size snake_case_ = dilation_growth_rate snake_case_ = use_causal_conv snake_case_ = pad_mode snake_case_ = compress snake_case_ = num_lstm_layers snake_case_ = trim_right_ratio snake_case_ = codebook_size snake_case_ = codebook_dim if codebook_dim is not None else hidden_size snake_case_ = use_conv_shortcut if self.norm_type not in ["weight_norm", "time_group_norm"]: raise ValueError( F"""self.norm_type must be one of `\"weight_norm\"`, `\"time_group_norm\"`), got {self.norm_type}""" ) super().__init__(**UpperCAmelCase_ ) @property def lowerCAmelCase ( self : List[Any] ) ->Optional[int]: """simple docstring""" if self.chunk_length_s is None: return None else: return int(self.chunk_length_s * self.sampling_rate ) @property def lowerCAmelCase ( self : str ) ->Optional[int]: """simple docstring""" if self.chunk_length_s is None or self.overlap is None: return None else: return max(1 , int((1.0 - self.overlap) * self.chunk_length ) ) @property def lowerCAmelCase ( self : Any ) ->int: """simple docstring""" snake_case_ = np.prod(self.upsampling_ratios ) return math.ceil(self.sampling_rate / hop_length ) @property def lowerCAmelCase ( self : Optional[Any] ) ->int: """simple docstring""" return int(1_000 * self.target_bandwidths[-1] // (self.frame_rate * 10) )
702
"""simple docstring""" from ....configuration_utils import PretrainedConfig from ....utils import logging __SCREAMING_SNAKE_CASE : str = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : str = { 'speechbrain/m-ctc-t-large': 'https://huggingface.co/speechbrain/m-ctc-t-large/resolve/main/config.json', # See all M-CTC-T models at https://huggingface.co/models?filter=mctct } class __A (snake_case__): '''simple docstring''' __lowercase: Any = """mctct""" def __init__( self : Dict , UpperCAmelCase_ : List[Any]=8_065 , UpperCAmelCase_ : Tuple=1_536 , UpperCAmelCase_ : Optional[Any]=36 , UpperCAmelCase_ : int=6_144 , UpperCAmelCase_ : Dict=4 , UpperCAmelCase_ : Any=384 , UpperCAmelCase_ : List[str]=920 , UpperCAmelCase_ : Any=1E-5 , UpperCAmelCase_ : Any=0.3 , UpperCAmelCase_ : Tuple="relu" , UpperCAmelCase_ : Union[str, Any]=0.02 , UpperCAmelCase_ : Dict=0.3 , UpperCAmelCase_ : str=0.3 , UpperCAmelCase_ : Any=1 , UpperCAmelCase_ : Any=0 , UpperCAmelCase_ : int=2 , UpperCAmelCase_ : str=1 , UpperCAmelCase_ : Tuple=0.3 , UpperCAmelCase_ : Optional[Any]=1 , UpperCAmelCase_ : Optional[Any]=(7,) , UpperCAmelCase_ : Optional[Any]=(3,) , UpperCAmelCase_ : List[str]=80 , UpperCAmelCase_ : Tuple=1 , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : List[str]="sum" , UpperCAmelCase_ : Union[str, Any]=False , **UpperCAmelCase_ : Any , ) ->Dict: """simple docstring""" super().__init__(**UpperCAmelCase_ , pad_token_id=UpperCAmelCase_ , bos_token_id=UpperCAmelCase_ , eos_token_id=UpperCAmelCase_ ) snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = intermediate_size snake_case_ = num_attention_heads snake_case_ = attention_head_dim snake_case_ = max_position_embeddings snake_case_ = layer_norm_eps snake_case_ = layerdrop snake_case_ = hidden_act snake_case_ = initializer_range snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = pad_token_id snake_case_ = bos_token_id snake_case_ = eos_token_id snake_case_ = conv_glu_dim snake_case_ = conv_dropout snake_case_ = num_conv_layers snake_case_ = input_feat_per_channel snake_case_ = input_channels snake_case_ = conv_channels snake_case_ = ctc_loss_reduction snake_case_ = ctc_zero_infinity # prevents config testing fail with exporting to json snake_case_ = list(UpperCAmelCase_ ) snake_case_ = list(UpperCAmelCase_ ) if len(self.conv_kernel ) != self.num_conv_layers: raise ValueError( """Configuration for convolutional module is incorrect. """ """It is required that `len(config.conv_kernel)` == `config.num_conv_layers` """ F"""but is `len(config.conv_kernel) = {len(self.conv_kernel )}`, """ F"""`config.num_conv_layers = {self.num_conv_layers}`.""" )
2
0
"""simple docstring""" import collections import inspect import unittest from typing import Dict, List, Tuple from transformers import MaskFormerSwinConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device from transformers.utils import is_torch_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MaskFormerSwinBackbone from transformers.models.maskformer import MaskFormerSwinModel class __A : '''simple docstring''' def __init__( self : List[Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Any=13 , UpperCAmelCase_ : Dict=32 , UpperCAmelCase_ : List[Any]=2 , UpperCAmelCase_ : Optional[int]=3 , UpperCAmelCase_ : Optional[int]=16 , UpperCAmelCase_ : Dict=[1, 2, 1] , UpperCAmelCase_ : List[Any]=[2, 2, 4] , UpperCAmelCase_ : str=2 , UpperCAmelCase_ : Dict=2.0 , UpperCAmelCase_ : Dict=True , UpperCAmelCase_ : Tuple=0.0 , UpperCAmelCase_ : int=0.0 , UpperCAmelCase_ : List[Any]=0.1 , UpperCAmelCase_ : Any="gelu" , UpperCAmelCase_ : int=False , UpperCAmelCase_ : List[Any]=True , UpperCAmelCase_ : List[str]=0.02 , UpperCAmelCase_ : Union[str, Any]=1E-5 , UpperCAmelCase_ : Union[str, Any]=True , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : Optional[int]=10 , UpperCAmelCase_ : Any=8 , UpperCAmelCase_ : Optional[int]=["stage1", "stage2", "stage3"] , UpperCAmelCase_ : str=[1, 2, 3] , ) ->Dict: """simple docstring""" snake_case_ = parent snake_case_ = batch_size snake_case_ = image_size snake_case_ = patch_size snake_case_ = num_channels snake_case_ = embed_dim snake_case_ = depths snake_case_ = num_heads snake_case_ = window_size snake_case_ = mlp_ratio snake_case_ = qkv_bias snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = drop_path_rate snake_case_ = hidden_act snake_case_ = use_absolute_embeddings snake_case_ = patch_norm snake_case_ = layer_norm_eps snake_case_ = initializer_range snake_case_ = is_training snake_case_ = scope snake_case_ = use_labels snake_case_ = type_sequence_label_size snake_case_ = encoder_stride snake_case_ = out_features snake_case_ = out_indices def lowerCAmelCase ( self : str ) ->List[str]: """simple docstring""" snake_case_ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case_ = None if self.use_labels: snake_case_ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case_ = self.get_config() return config, pixel_values, labels def lowerCAmelCase ( self : Any ) ->Dict: """simple docstring""" return MaskFormerSwinConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , out_features=self.out_features , out_indices=self.out_indices , ) def lowerCAmelCase ( self : str , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : List[Any] ) ->Dict: """simple docstring""" snake_case_ = MaskFormerSwinModel(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ ) snake_case_ = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) snake_case_ = 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 lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : str , UpperCAmelCase_ : str , UpperCAmelCase_ : Tuple ) ->Tuple: """simple docstring""" snake_case_ = MaskFormerSwinBackbone(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [13, 16, 16, 16] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , [16, 32, 64] ) # verify ValueError with self.parent.assertRaises(UpperCAmelCase_ ): snake_case_ = ["""stem"""] snake_case_ = MaskFormerSwinBackbone(config=UpperCAmelCase_ ) def lowerCAmelCase ( self : Any ) ->Union[str, Any]: """simple docstring""" snake_case_ = self.prepare_config_and_inputs() snake_case_ , snake_case_ , snake_case_ = config_and_inputs snake_case_ = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class __A (snake_case__ , snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Optional[Any] = ( ( MaskFormerSwinModel, MaskFormerSwinBackbone, ) if is_torch_available() else () ) __lowercase: Tuple = {"""feature-extraction""": MaskFormerSwinModel} if is_torch_available() else {} __lowercase: Tuple = False __lowercase: Optional[int] = False __lowercase: Dict = False __lowercase: int = False __lowercase: List[str] = False def lowerCAmelCase ( self : Optional[Any] ) ->str: """simple docstring""" snake_case_ = MaskFormerSwinModelTester(self ) snake_case_ = ConfigTester(self , config_class=UpperCAmelCase_ , embed_dim=37 ) @require_torch_multi_gpu @unittest.skip( reason=( """`MaskFormerSwinModel` outputs `hidden_states_spatial_dimensions` which doesn't work well with""" """ `nn.DataParallel`""" ) ) def lowerCAmelCase ( self : int ) ->Any: """simple docstring""" pass def lowerCAmelCase ( self : int ) ->Union[str, Any]: """simple docstring""" 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 lowerCAmelCase ( self : Any ) ->Tuple: """simple docstring""" return def lowerCAmelCase ( self : List[Any] ) ->List[str]: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def lowerCAmelCase ( self : Dict ) ->int: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*UpperCAmelCase_ ) @unittest.skip("""Swin does not use inputs_embeds""" ) def lowerCAmelCase ( self : Optional[Any] ) ->int: """simple docstring""" pass @unittest.skip("""Swin does not support feedforward chunking""" ) def lowerCAmelCase ( self : Any ) ->int: """simple docstring""" pass def lowerCAmelCase ( self : List[Any] ) ->int: """simple docstring""" snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ = model_class(UpperCAmelCase_ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) snake_case_ = model.get_output_embeddings() self.assertTrue(x is None or isinstance(UpperCAmelCase_ , nn.Linear ) ) def lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ = model_class(UpperCAmelCase_ ) snake_case_ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case_ = [*signature.parameters.keys()] snake_case_ = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , UpperCAmelCase_ ) @unittest.skip(reason="""MaskFormerSwin is only used as backbone and doesn't support output_attentions""" ) def lowerCAmelCase ( self : List[str] ) ->Optional[Any]: """simple docstring""" pass @unittest.skip(reason="""MaskFormerSwin is only used as an internal backbone""" ) def lowerCAmelCase ( self : int ) ->Tuple: """simple docstring""" pass def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[Any] ) ->Optional[int]: """simple docstring""" snake_case_ = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() with torch.no_grad(): snake_case_ = model(**self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) ) snake_case_ = outputs.hidden_states snake_case_ = getattr( self.model_tester , """expected_num_hidden_layers""" , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(UpperCAmelCase_ ) , UpperCAmelCase_ ) # Swin has a different seq_length snake_case_ = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) snake_case_ = (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] , ) def lowerCAmelCase ( self : Optional[Any] ) ->Dict: """simple docstring""" snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() snake_case_ = ( 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: snake_case_ = True self.check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] snake_case_ = True self.check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() snake_case_ = 3 snake_case_ = ( 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) ) snake_case_ = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) snake_case_ = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) snake_case_ = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: snake_case_ = True self.check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] snake_case_ = True self.check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , (padded_height, padded_width) ) @unittest.skip(reason="""MaskFormerSwin doesn't have pretrained checkpoints""" ) def lowerCAmelCase ( self : str ) ->Optional[int]: """simple docstring""" pass @unittest.skip(reason="""This will be fixed once MaskFormerSwin is replaced by native Swin""" ) def lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" pass @unittest.skip(reason="""This will be fixed once MaskFormerSwin is replaced by native Swin""" ) def lowerCAmelCase ( self : int ) ->Optional[int]: """simple docstring""" pass def lowerCAmelCase ( self : List[str] ) ->List[Any]: """simple docstring""" snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() def set_nan_tensor_to_zero(UpperCAmelCase_ : List[Any] ): snake_case_ = 0 return t def check_equivalence(UpperCAmelCase_ : str , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[int]={} ): with torch.no_grad(): snake_case_ = model(**UpperCAmelCase_ , return_dict=UpperCAmelCase_ , **UpperCAmelCase_ ) snake_case_ = model(**UpperCAmelCase_ , return_dict=UpperCAmelCase_ , **UpperCAmelCase_ ).to_tuple() def recursive_check(UpperCAmelCase_ : Any , UpperCAmelCase_ : Optional[int] ): if isinstance(UpperCAmelCase_ , (List, Tuple) ): for tuple_iterable_value, dict_iterable_value in zip(UpperCAmelCase_ , UpperCAmelCase_ ): recursive_check(UpperCAmelCase_ , UpperCAmelCase_ ) elif isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): for tuple_iterable_value, dict_iterable_value in zip( tuple_object.values() , dict_object.values() ): recursive_check(UpperCAmelCase_ , UpperCAmelCase_ ) elif tuple_object is None: return else: self.assertTrue( torch.allclose( set_nan_tensor_to_zero(UpperCAmelCase_ ) , set_nan_tensor_to_zero(UpperCAmelCase_ ) , atol=1E-5 ) , msg=( """Tuple and dict output are not equal. Difference:""" F""" {torch.max(torch.abs(tuple_object - dict_object ) )}. Tuple has `nan`:""" F""" {torch.isnan(UpperCAmelCase_ ).any()} and `inf`: {torch.isinf(UpperCAmelCase_ )}. Dict has""" F""" `nan`: {torch.isnan(UpperCAmelCase_ ).any()} and `inf`: {torch.isinf(UpperCAmelCase_ )}.""" ) , ) recursive_check(UpperCAmelCase_ , UpperCAmelCase_ ) for model_class in self.all_model_classes: snake_case_ = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) check_equivalence(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ , return_labels=UpperCAmelCase_ ) snake_case_ = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ , return_labels=UpperCAmelCase_ ) check_equivalence(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) check_equivalence(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , {"""output_hidden_states""": True} ) snake_case_ = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ , return_labels=UpperCAmelCase_ ) snake_case_ = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ , return_labels=UpperCAmelCase_ ) check_equivalence(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , {"""output_hidden_states""": True} ) @require_torch class __A (unittest.TestCase , snake_case__): '''simple docstring''' __lowercase: Union[str, Any] = (MaskFormerSwinBackbone,) if is_torch_available() else () __lowercase: Tuple = MaskFormerSwinConfig def lowerCAmelCase ( self : str ) ->Any: """simple docstring""" snake_case_ = MaskFormerSwinModelTester(self ) def lowerCAmelCase ( self : Optional[Any] ) ->int: """simple docstring""" snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() snake_case_ = inputs_dict["""pixel_values"""].shape[0] for backbone_class in self.all_model_classes: snake_case_ = backbone_class(UpperCAmelCase_ ) backbone.to(UpperCAmelCase_ ) backbone.eval() snake_case_ = backbone(**UpperCAmelCase_ ) # Test default outputs and verify feature maps self.assertIsInstance(outputs.feature_maps , UpperCAmelCase_ ) self.assertTrue(len(outputs.feature_maps ) == len(backbone.channels ) ) for feature_map, n_channels in zip(outputs.feature_maps , backbone.channels ): self.assertTrue(feature_map.shape[:2] , (batch_size, n_channels) ) self.assertIsNone(outputs.hidden_states ) self.assertIsNone(outputs.attentions ) # Test output_hidden_states=True snake_case_ = backbone(**UpperCAmelCase_ , output_hidden_states=UpperCAmelCase_ ) self.assertIsNotNone(outputs.hidden_states ) self.assertTrue(len(outputs.hidden_states ) , len(backbone.stage_names ) ) # We skip the stem layer for hidden_states, n_channels in zip(outputs.hidden_states[1:] , backbone.channels ): for hidden_state in hidden_states: # Hidden states are in the format (batch_size, (height * width), n_channels) snake_case_ , snake_case_ , snake_case_ = hidden_state.shape self.assertTrue((h_batch_size, h_n_channels) , (batch_size, n_channels) ) # Test output_attentions=True if self.has_attentions: snake_case_ = backbone(**UpperCAmelCase_ , output_attentions=UpperCAmelCase_ ) self.assertIsNotNone(outputs.attentions )
703
"""simple docstring""" from math import factorial def _a ( _SCREAMING_SNAKE_CASE = 100 ) -> int: return sum(int(_SCREAMING_SNAKE_CASE ) for x in str(factorial(_SCREAMING_SNAKE_CASE ) ) ) if __name__ == "__main__": print(solution(int(input('Enter the Number: ').strip())))
2
0
"""simple docstring""" import unittest from transformers import PegasusConfig, PegasusTokenizer, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html __SCREAMING_SNAKE_CASE : List[str] = 'platform' import jax import jax.numpy as jnp import numpy as np from transformers import FlaxPegasusForConditionalGeneration, FlaxPegasusModel @require_flax class __A : '''simple docstring''' __lowercase: List[str] = PegasusConfig __lowercase: Dict = {} __lowercase: Optional[Any] = """gelu""" def __init__( self : List[Any] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : str=13 , UpperCAmelCase_ : Dict=7 , UpperCAmelCase_ : Dict=True , UpperCAmelCase_ : List[str]=False , UpperCAmelCase_ : List[Any]=99 , UpperCAmelCase_ : Union[str, Any]=32 , UpperCAmelCase_ : List[str]=5 , UpperCAmelCase_ : str=4 , UpperCAmelCase_ : Any=37 , UpperCAmelCase_ : int=0.1 , UpperCAmelCase_ : Optional[Any]=0.1 , UpperCAmelCase_ : Union[str, Any]=20 , UpperCAmelCase_ : Dict=2 , UpperCAmelCase_ : Optional[Any]=1 , UpperCAmelCase_ : Tuple=0 , ) ->Optional[int]: """simple docstring""" snake_case_ = parent snake_case_ = batch_size snake_case_ = seq_length snake_case_ = is_training snake_case_ = use_labels snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = intermediate_size snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = max_position_embeddings snake_case_ = eos_token_id snake_case_ = pad_token_id snake_case_ = bos_token_id def lowerCAmelCase ( self : int ) ->Any: """simple docstring""" snake_case_ = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ).clip(3 , self.vocab_size ) snake_case_ = np.expand_dims(np.array([self.eos_token_id] * self.batch_size ) , 1 ) snake_case_ = np.concatenate([input_ids, eos_tensor] , axis=1 ) snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case_ = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) snake_case_ = prepare_pegasus_inputs_dict(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) return config, inputs_dict def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : Any , UpperCAmelCase_ : int , UpperCAmelCase_ : str ) ->str: """simple docstring""" snake_case_ = 20 snake_case_ = model_class_name(UpperCAmelCase_ ) snake_case_ = model.encode(inputs_dict["""input_ids"""] ) snake_case_ , snake_case_ = ( inputs_dict["""decoder_input_ids"""], inputs_dict["""decoder_attention_mask"""], ) snake_case_ = model.init_cache(decoder_input_ids.shape[0] , UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype="""i4""" ) snake_case_ = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) snake_case_ = model.decode( decoder_input_ids[:, :-1] , UpperCAmelCase_ , decoder_attention_mask=UpperCAmelCase_ , past_key_values=UpperCAmelCase_ , decoder_position_ids=UpperCAmelCase_ , ) snake_case_ = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="""i4""" ) snake_case_ = model.decode( decoder_input_ids[:, -1:] , UpperCAmelCase_ , decoder_attention_mask=UpperCAmelCase_ , past_key_values=outputs_cache.past_key_values , decoder_position_ids=UpperCAmelCase_ , ) snake_case_ = model.decode(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=F"""Max diff is {diff}""" ) def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : int , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : List[Any] ) ->Dict: """simple docstring""" snake_case_ = 20 snake_case_ = model_class_name(UpperCAmelCase_ ) snake_case_ = model.encode(inputs_dict["""input_ids"""] ) snake_case_ , snake_case_ = ( inputs_dict["""decoder_input_ids"""], inputs_dict["""decoder_attention_mask"""], ) snake_case_ = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) snake_case_ = model.init_cache(decoder_input_ids.shape[0] , UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) snake_case_ = model.decode( decoder_input_ids[:, :-1] , UpperCAmelCase_ , decoder_attention_mask=UpperCAmelCase_ , past_key_values=UpperCAmelCase_ , decoder_position_ids=UpperCAmelCase_ , ) snake_case_ = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="""i4""" ) snake_case_ = model.decode( decoder_input_ids[:, -1:] , UpperCAmelCase_ , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=UpperCAmelCase_ , decoder_position_ids=UpperCAmelCase_ , ) snake_case_ = model.decode(UpperCAmelCase_ , UpperCAmelCase_ , decoder_attention_mask=UpperCAmelCase_ ) snake_case_ = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=F"""Max diff is {diff}""" ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , ) -> Dict: '''simple docstring''' if attention_mask is None: snake_case_ = np.not_equal(_SCREAMING_SNAKE_CASE , config.pad_token_id ).astype(np.inta ) if decoder_attention_mask is None: snake_case_ = np.concatenate( [ np.ones(decoder_input_ids[:, :1].shape , dtype=np.inta ), np.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ).astype(np.inta ), ] , axis=-1 , ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, } @require_flax class __A (snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Optional[int] = ( ( FlaxPegasusForConditionalGeneration, FlaxPegasusModel, ) if is_flax_available() else () ) __lowercase: Union[str, Any] = (FlaxPegasusForConditionalGeneration,) if is_flax_available() else () __lowercase: List[str] = True __lowercase: str = False __lowercase: Optional[int] = False __lowercase: List[str] = False def lowerCAmelCase ( self : Tuple ) ->int: """simple docstring""" snake_case_ = FlaxPegasusModelTester(self ) snake_case_ = ConfigTester(self , config_class=UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] ) ->Optional[Any]: """simple docstring""" self.config_tester.run_common_tests() def lowerCAmelCase ( self : Tuple ) ->Dict: """simple docstring""" snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] ) ->List[Any]: """simple docstring""" snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : Any ) ->List[Any]: """simple docstring""" snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): snake_case_ = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = model_class(UpperCAmelCase_ ) @jax.jit def encode_jitted(UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Optional[Any]=None , **UpperCAmelCase_ : Optional[Any] ): return model.encode(input_ids=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ ) with self.subTest("""JIT Enabled""" ): snake_case_ = encode_jitted(**UpperCAmelCase_ ).to_tuple() with self.subTest("""JIT Disabled""" ): with jax.disable_jit(): snake_case_ = encode_jitted(**UpperCAmelCase_ ).to_tuple() self.assertEqual(len(UpperCAmelCase_ ) , len(UpperCAmelCase_ ) ) for jitted_output, output in zip(UpperCAmelCase_ , UpperCAmelCase_ ): self.assertEqual(jitted_output.shape , output.shape ) def lowerCAmelCase ( self : List[Any] ) ->Any: """simple docstring""" snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): snake_case_ = model_class(UpperCAmelCase_ ) snake_case_ = model.encode(inputs_dict["""input_ids"""] , inputs_dict["""attention_mask"""] ) snake_case_ = { """decoder_input_ids""": inputs_dict["""decoder_input_ids"""], """decoder_attention_mask""": inputs_dict["""decoder_attention_mask"""], """encoder_outputs""": encoder_outputs, } @jax.jit def decode_jitted(UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : List[Any] ): return model.decode( decoder_input_ids=UpperCAmelCase_ , decoder_attention_mask=UpperCAmelCase_ , encoder_outputs=UpperCAmelCase_ , ) with self.subTest("""JIT Enabled""" ): snake_case_ = decode_jitted(**UpperCAmelCase_ ).to_tuple() with self.subTest("""JIT Disabled""" ): with jax.disable_jit(): snake_case_ = decode_jitted(**UpperCAmelCase_ ).to_tuple() self.assertEqual(len(UpperCAmelCase_ ) , len(UpperCAmelCase_ ) ) for jitted_output, output in zip(UpperCAmelCase_ , UpperCAmelCase_ ): self.assertEqual(jitted_output.shape , output.shape ) @slow def lowerCAmelCase ( self : Any ) ->List[str]: """simple docstring""" for model_class_name in self.all_model_classes: snake_case_ = model_class_name.from_pretrained("""google/pegasus-large""" , from_pt=UpperCAmelCase_ ) snake_case_ = np.ones((1, 1) ) snake_case_ = model(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) @slow def lowerCAmelCase ( self : Dict ) ->Tuple: """simple docstring""" snake_case_ = FlaxPegasusForConditionalGeneration.from_pretrained("""google/pegasus-xsum""" ) snake_case_ = PegasusTokenizer.from_pretrained("""google/pegasus-xsum""" ) snake_case_ = [ """ PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.""", """ The London trio are up for best UK act and best album, as well as getting two nominations in the best song category.\"We got told like this morning 'Oh I think you're nominated'\", said Dappy.\"And I was like 'Oh yeah, which one?' And now we've got nominated for four awards. I mean, wow!\"Bandmate Fazer added: \"We thought it's best of us to come down and mingle with everyone and say hello to the cameras. And now we find we've got four nominations.\"The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn't be too disappointed if they didn't win this time around.\"At the end of the day we're grateful to be where we are in our careers.\"If it don't happen then it don't happen - live to fight another day and keep on making albums and hits for the fans.\"Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers' All These Things That I've Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year's Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border.\"We just done Edinburgh the other day,\" said Dappy.\"We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!\" """, ] snake_case_ = [ """California's largest electricity provider has turned off power to hundreds of thousands of customers.""", """Pop group N-Dubz have revealed they were surprised to get four nominations for this year's Mobo Awards.""", ] snake_case_ = tokenizer(UpperCAmelCase_ , return_tensors="""np""" , truncation=UpperCAmelCase_ , max_length=512 , padding=UpperCAmelCase_ ) snake_case_ = model.generate(**UpperCAmelCase_ , num_beams=2 ).sequences snake_case_ = tokenizer.batch_decode(UpperCAmelCase_ , skip_special_tokens=UpperCAmelCase_ ) assert tgt_text == decoded
704
"""simple docstring""" import unittest import torch from diffusers import VQModel from diffusers.utils import floats_tensor, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class __A (snake_case__ , snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: str = VQModel __lowercase: Union[str, Any] = """sample""" @property def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : List[str]=(32, 32) ) ->Tuple: """simple docstring""" snake_case_ = 4 snake_case_ = 3 snake_case_ = floats_tensor((batch_size, num_channels) + sizes ).to(UpperCAmelCase_ ) return {"sample": image} @property def lowerCAmelCase ( self : Tuple ) ->str: """simple docstring""" return (3, 32, 32) @property def lowerCAmelCase ( self : List[Any] ) ->Any: """simple docstring""" return (3, 32, 32) def lowerCAmelCase ( self : Optional[int] ) ->Dict: """simple docstring""" snake_case_ = { """block_out_channels""": [32, 64], """in_channels""": 3, """out_channels""": 3, """down_block_types""": ["""DownEncoderBlock2D""", """DownEncoderBlock2D"""], """up_block_types""": ["""UpDecoderBlock2D""", """UpDecoderBlock2D"""], """latent_channels""": 3, } snake_case_ = self.dummy_input return init_dict, inputs_dict def lowerCAmelCase ( self : List[str] ) ->Dict: """simple docstring""" pass def lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" pass def lowerCAmelCase ( self : Any ) ->Union[str, Any]: """simple docstring""" snake_case_ , snake_case_ = VQModel.from_pretrained("""fusing/vqgan-dummy""" , output_loading_info=UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) self.assertEqual(len(loading_info["""missing_keys"""] ) , 0 ) model.to(UpperCAmelCase_ ) snake_case_ = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def lowerCAmelCase ( self : Tuple ) ->Optional[Any]: """simple docstring""" snake_case_ = VQModel.from_pretrained("""fusing/vqgan-dummy""" ) model.to(UpperCAmelCase_ ).eval() torch.manual_seed(0 ) if torch.cuda.is_available(): torch.cuda.manual_seed_all(0 ) snake_case_ = torch.randn(1 , model.config.in_channels , model.config.sample_size , model.config.sample_size ) snake_case_ = image.to(UpperCAmelCase_ ) with torch.no_grad(): snake_case_ = model(UpperCAmelCase_ ).sample snake_case_ = output[0, -1, -3:, -3:].flatten().cpu() # fmt: off snake_case_ = torch.tensor([-0.0_153, -0.4_044, -0.1_880, -0.5_161, -0.2_418, -0.4_072, -0.1_612, -0.0_633, -0.0_143] ) # fmt: on self.assertTrue(torch.allclose(UpperCAmelCase_ , UpperCAmelCase_ , atol=1E-3 ) )
2
0
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import PoolFormerImageProcessor class __A (unittest.TestCase): '''simple docstring''' def __init__( self : int , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Tuple=7 , UpperCAmelCase_ : Union[str, Any]=3 , UpperCAmelCase_ : List[str]=30 , UpperCAmelCase_ : Union[str, Any]=400 , UpperCAmelCase_ : List[Any]=True , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : Optional[int]=0.9 , UpperCAmelCase_ : int=None , UpperCAmelCase_ : List[str]=True , UpperCAmelCase_ : Dict=[0.5, 0.5, 0.5] , UpperCAmelCase_ : int=[0.5, 0.5, 0.5] , ) ->int: """simple docstring""" snake_case_ = size if size is not None else {"""shortest_edge""": 30} snake_case_ = crop_size if crop_size is not None else {"""height""": 30, """width""": 30} snake_case_ = parent snake_case_ = batch_size snake_case_ = num_channels snake_case_ = min_resolution snake_case_ = max_resolution snake_case_ = do_resize_and_center_crop snake_case_ = size snake_case_ = crop_pct snake_case_ = crop_size snake_case_ = do_normalize snake_case_ = image_mean snake_case_ = image_std def lowerCAmelCase ( self : Union[str, Any] ) ->Optional[int]: """simple docstring""" return { "size": self.size, "do_resize_and_center_crop": self.do_resize_and_center_crop, "crop_pct": self.crop_pct, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, } @require_torch @require_vision class __A (snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Dict = PoolFormerImageProcessor if is_vision_available() else None def lowerCAmelCase ( self : List[Any] ) ->Tuple: """simple docstring""" snake_case_ = PoolFormerImageProcessingTester(self ) @property def lowerCAmelCase ( self : Optional[Any] ) ->Any: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def lowerCAmelCase ( self : List[str] ) ->List[str]: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(UpperCAmelCase_ , """do_resize_and_center_crop""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """size""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """crop_pct""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """do_normalize""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """image_mean""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """image_std""" ) ) def lowerCAmelCase ( self : Any ) ->Dict: """simple docstring""" snake_case_ = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""shortest_edge""": 30} ) self.assertEqual(image_processor.crop_size , {"""height""": 30, """width""": 30} ) snake_case_ = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {"""shortest_edge""": 42} ) self.assertEqual(image_processor.crop_size , {"""height""": 84, """width""": 84} ) def lowerCAmelCase ( self : Any ) ->Union[str, Any]: """simple docstring""" pass def lowerCAmelCase ( self : Tuple ) ->int: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) # create random PIL images snake_case_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase_ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase_ , Image.Image ) # Test not batched input snake_case_ = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched snake_case_ = image_processing(UpperCAmelCase_ , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) def lowerCAmelCase ( self : List[str] ) ->List[str]: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors snake_case_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase_ , numpify=UpperCAmelCase_ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase_ , np.ndarray ) # Test not batched input snake_case_ = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched snake_case_ = image_processing(UpperCAmelCase_ , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) def lowerCAmelCase ( self : int ) ->Union[str, Any]: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors snake_case_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase_ , torchify=UpperCAmelCase_ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase_ , torch.Tensor ) # Test not batched input snake_case_ = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched snake_case_ = image_processing(UpperCAmelCase_ , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , )
705
"""simple docstring""" import gc import random import unittest import numpy as np import torch from diffusers import ( DDIMScheduler, KandinskyVaaControlnetPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) 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 from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class __A (snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Dict = KandinskyVaaControlnetPipeline __lowercase: str = ["""image_embeds""", """negative_image_embeds""", """hint"""] __lowercase: List[str] = ["""image_embeds""", """negative_image_embeds""", """hint"""] __lowercase: Union[str, Any] = [ """generator""", """height""", """width""", """latents""", """guidance_scale""", """num_inference_steps""", """return_dict""", """guidance_scale""", """num_images_per_prompt""", """output_type""", """return_dict""", ] __lowercase: Tuple = False @property def lowerCAmelCase ( self : Any ) ->Union[str, Any]: """simple docstring""" return 32 @property def lowerCAmelCase ( self : Optional[Any] ) ->Union[str, Any]: """simple docstring""" return 32 @property def lowerCAmelCase ( self : int ) ->List[str]: """simple docstring""" return self.time_input_dim @property def lowerCAmelCase ( self : Union[str, Any] ) ->Union[str, Any]: """simple docstring""" return self.time_input_dim * 4 @property def lowerCAmelCase ( self : Dict ) ->Optional[int]: """simple docstring""" return 100 @property def lowerCAmelCase ( self : str ) ->List[Any]: """simple docstring""" torch.manual_seed(0 ) snake_case_ = { """in_channels""": 8, # Out channels is double in channels because predicts mean and variance """out_channels""": 8, """addition_embed_type""": """image_hint""", """down_block_types""": ("""ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D"""), """up_block_types""": ("""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""), """mid_block_type""": """UNetMidBlock2DSimpleCrossAttn""", """block_out_channels""": (self.block_out_channels_a, self.block_out_channels_a * 2), """layers_per_block""": 1, """encoder_hid_dim""": self.text_embedder_hidden_size, """encoder_hid_dim_type""": """image_proj""", """cross_attention_dim""": self.cross_attention_dim, """attention_head_dim""": 4, """resnet_time_scale_shift""": """scale_shift""", """class_embed_type""": None, } snake_case_ = UNetaDConditionModel(**UpperCAmelCase_ ) return model @property def lowerCAmelCase ( self : Any ) ->Optional[Any]: """simple docstring""" return { "block_out_channels": [32, 32, 64, 64], "down_block_types": [ "DownEncoderBlock2D", "DownEncoderBlock2D", "DownEncoderBlock2D", "AttnDownEncoderBlock2D", ], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": ["AttnUpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"], "vq_embed_dim": 4, } @property def lowerCAmelCase ( self : Any ) ->int: """simple docstring""" torch.manual_seed(0 ) snake_case_ = VQModel(**self.dummy_movq_kwargs ) return model def lowerCAmelCase ( self : Dict ) ->str: """simple docstring""" snake_case_ = self.dummy_unet snake_case_ = self.dummy_movq snake_case_ = DDIMScheduler( num_train_timesteps=1_000 , beta_schedule="""linear""" , beta_start=0.00_085 , beta_end=0.012 , clip_sample=UpperCAmelCase_ , set_alpha_to_one=UpperCAmelCase_ , steps_offset=1 , prediction_type="""epsilon""" , thresholding=UpperCAmelCase_ , ) snake_case_ = { """unet""": unet, """scheduler""": scheduler, """movq""": movq, } return components def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[Any]=0 ) ->List[str]: """simple docstring""" snake_case_ = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(UpperCAmelCase_ ) ).to(UpperCAmelCase_ ) snake_case_ = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( UpperCAmelCase_ ) # create hint snake_case_ = floats_tensor((1, 3, 64, 64) , rng=random.Random(UpperCAmelCase_ ) ).to(UpperCAmelCase_ ) if str(UpperCAmelCase_ ).startswith("""mps""" ): snake_case_ = torch.manual_seed(UpperCAmelCase_ ) else: snake_case_ = torch.Generator(device=UpperCAmelCase_ ).manual_seed(UpperCAmelCase_ ) snake_case_ = { """image_embeds""": image_embeds, """negative_image_embeds""": negative_image_embeds, """hint""": hint, """generator""": generator, """height""": 64, """width""": 64, """guidance_scale""": 4.0, """num_inference_steps""": 2, """output_type""": """np""", } return inputs def lowerCAmelCase ( self : List[str] ) ->List[Any]: """simple docstring""" snake_case_ = """cpu""" snake_case_ = self.get_dummy_components() snake_case_ = self.pipeline_class(**UpperCAmelCase_ ) snake_case_ = pipe.to(UpperCAmelCase_ ) pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) snake_case_ = pipe(**self.get_dummy_inputs(UpperCAmelCase_ ) ) snake_case_ = output.images snake_case_ = pipe( **self.get_dummy_inputs(UpperCAmelCase_ ) , return_dict=UpperCAmelCase_ , )[0] snake_case_ = image[0, -3:, -3:, -1] snake_case_ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) snake_case_ = np.array( [0.6_959_826, 0.868_279, 0.7_558_092, 0.68_769_467, 0.85_805_804, 0.65_977_496, 0.44_885_302, 0.5_959_111, 0.4_251_595] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 ), F""" expected_slice {expected_slice}, but got {image_slice.flatten()}""" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 ), F""" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}""" @slow @require_torch_gpu class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : List[Any] ) ->Union[str, Any]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCAmelCase ( self : List[str] ) ->List[str]: """simple docstring""" snake_case_ = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinskyv22/kandinskyv22_controlnet_robotcat_fp16.npy""" ) snake_case_ = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinskyv22/hint_image_cat.png""" ) snake_case_ = torch.from_numpy(np.array(UpperCAmelCase_ ) ).float() / 255.0 snake_case_ = hint.permute(2 , 0 , 1 ).unsqueeze(0 ) snake_case_ = KandinskyVaaPriorPipeline.from_pretrained( """kandinsky-community/kandinsky-2-2-prior""" , torch_dtype=torch.floataa ) pipe_prior.to(UpperCAmelCase_ ) snake_case_ = KandinskyVaaControlnetPipeline.from_pretrained( """kandinsky-community/kandinsky-2-2-controlnet-depth""" , torch_dtype=torch.floataa ) snake_case_ = pipeline.to(UpperCAmelCase_ ) pipeline.set_progress_bar_config(disable=UpperCAmelCase_ ) snake_case_ = """A robot, 4k photo""" snake_case_ = torch.Generator(device="""cuda""" ).manual_seed(0 ) snake_case_ , snake_case_ = pipe_prior( UpperCAmelCase_ , generator=UpperCAmelCase_ , num_inference_steps=5 , negative_prompt="""""" , ).to_tuple() snake_case_ = torch.Generator(device="""cuda""" ).manual_seed(0 ) snake_case_ = pipeline( image_embeds=UpperCAmelCase_ , negative_image_embeds=UpperCAmelCase_ , hint=UpperCAmelCase_ , generator=UpperCAmelCase_ , num_inference_steps=100 , output_type="""np""" , ) snake_case_ = output.images[0] assert image.shape == (512, 512, 3) assert_mean_pixel_difference(UpperCAmelCase_ , UpperCAmelCase_ )
2
0
"""simple docstring""" import shutil import tempfile import unittest import numpy as np import pytest from transformers.testing_utils import require_vision from transformers.utils import is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, BertTokenizer, BlipImageProcessor, BlipProcessor, PreTrainedTokenizerFast @require_vision class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : Dict ) ->Tuple: """simple docstring""" snake_case_ = tempfile.mkdtemp() snake_case_ = BlipImageProcessor() snake_case_ = BertTokenizer.from_pretrained("""hf-internal-testing/tiny-random-BertModel""" ) snake_case_ = BlipProcessor(UpperCAmelCase_ , UpperCAmelCase_ ) processor.save_pretrained(self.tmpdirname ) def lowerCAmelCase ( self : str , **UpperCAmelCase_ : List[str] ) ->Dict: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ).tokenizer def lowerCAmelCase ( self : Dict , **UpperCAmelCase_ : Optional[Any] ) ->List[str]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ).image_processor def lowerCAmelCase ( self : Tuple ) ->Tuple: """simple docstring""" shutil.rmtree(self.tmpdirname ) def lowerCAmelCase ( self : Optional[int] ) ->List[Any]: """simple docstring""" snake_case_ = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] snake_case_ = [Image.fromarray(np.moveaxis(UpperCAmelCase_ , 0 , -1 ) ) for x in image_inputs] return image_inputs def lowerCAmelCase ( self : Union[str, Any] ) ->Tuple: """simple docstring""" snake_case_ = BlipProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) snake_case_ = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) snake_case_ = self.get_image_processor(do_normalize=UpperCAmelCase_ , padding_value=1.0 ) snake_case_ = BlipProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=UpperCAmelCase_ , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , UpperCAmelCase_ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , UpperCAmelCase_ ) def lowerCAmelCase ( self : Tuple ) ->List[str]: """simple docstring""" snake_case_ = self.get_image_processor() snake_case_ = self.get_tokenizer() snake_case_ = BlipProcessor(tokenizer=UpperCAmelCase_ , image_processor=UpperCAmelCase_ ) snake_case_ = self.prepare_image_inputs() snake_case_ = image_processor(UpperCAmelCase_ , return_tensors="""np""" ) snake_case_ = processor(images=UpperCAmelCase_ , return_tensors="""np""" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) def lowerCAmelCase ( self : Optional[Any] ) ->Dict: """simple docstring""" snake_case_ = self.get_image_processor() snake_case_ = self.get_tokenizer() snake_case_ = BlipProcessor(tokenizer=UpperCAmelCase_ , image_processor=UpperCAmelCase_ ) snake_case_ = """lower newer""" snake_case_ = processor(text=UpperCAmelCase_ ) snake_case_ = tokenizer(UpperCAmelCase_ , return_token_type_ids=UpperCAmelCase_ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def lowerCAmelCase ( self : str ) ->Optional[int]: """simple docstring""" snake_case_ = self.get_image_processor() snake_case_ = self.get_tokenizer() snake_case_ = BlipProcessor(tokenizer=UpperCAmelCase_ , image_processor=UpperCAmelCase_ ) snake_case_ = """lower newer""" snake_case_ = self.prepare_image_inputs() snake_case_ = processor(text=UpperCAmelCase_ , images=UpperCAmelCase_ ) self.assertListEqual(list(inputs.keys() ) , ["""pixel_values""", """input_ids""", """attention_mask"""] ) # test if it raises when no input is passed with pytest.raises(UpperCAmelCase_ ): processor() def lowerCAmelCase ( self : Optional[Any] ) ->Tuple: """simple docstring""" snake_case_ = self.get_image_processor() snake_case_ = self.get_tokenizer() snake_case_ = BlipProcessor(tokenizer=UpperCAmelCase_ , image_processor=UpperCAmelCase_ ) snake_case_ = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] snake_case_ = processor.batch_decode(UpperCAmelCase_ ) snake_case_ = tokenizer.batch_decode(UpperCAmelCase_ ) self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : Any ) ->List[Any]: """simple docstring""" snake_case_ = self.get_image_processor() snake_case_ = self.get_tokenizer() snake_case_ = BlipProcessor(tokenizer=UpperCAmelCase_ , image_processor=UpperCAmelCase_ ) snake_case_ = """lower newer""" snake_case_ = self.prepare_image_inputs() snake_case_ = processor(text=UpperCAmelCase_ , images=UpperCAmelCase_ ) # For now the processor supports only ['pixel_values', 'input_ids', 'attention_mask'] self.assertListEqual(list(inputs.keys() ) , ["""pixel_values""", """input_ids""", """attention_mask"""] )
706
"""simple docstring""" from __future__ import annotations from collections import deque class __A : '''simple docstring''' def __init__( self : List[Any] , UpperCAmelCase_ : list[str] ) ->List[Any]: """simple docstring""" snake_case_ = [] self.adlist.append( {"""value""": """""", """next_states""": [], """fail_state""": 0, """output""": []} ) for keyword in keywords: self.add_keyword(UpperCAmelCase_ ) self.set_fail_transitions() def lowerCAmelCase ( self : int , UpperCAmelCase_ : int , UpperCAmelCase_ : str ) ->int | None: """simple docstring""" for state in self.adlist[current_state]["next_states"]: if char == self.adlist[state]["value"]: return state return None def lowerCAmelCase ( self : int , UpperCAmelCase_ : str ) ->None: """simple docstring""" snake_case_ = 0 for character in keyword: snake_case_ = self.find_next_state(UpperCAmelCase_ , UpperCAmelCase_ ) if next_state is None: self.adlist.append( { """value""": character, """next_states""": [], """fail_state""": 0, """output""": [], } ) self.adlist[current_state]["next_states"].append(len(self.adlist ) - 1 ) snake_case_ = len(self.adlist ) - 1 else: snake_case_ = next_state self.adlist[current_state]["output"].append(UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->None: """simple docstring""" snake_case_ = deque() for node in self.adlist[0]["next_states"]: q.append(UpperCAmelCase_ ) snake_case_ = 0 while q: snake_case_ = q.popleft() for child in self.adlist[r]["next_states"]: q.append(UpperCAmelCase_ ) snake_case_ = self.adlist[r]["""fail_state"""] while ( self.find_next_state(UpperCAmelCase_ , self.adlist[child]["""value"""] ) is None and state != 0 ): snake_case_ = self.adlist[state]["""fail_state"""] snake_case_ = self.find_next_state( UpperCAmelCase_ , self.adlist[child]["""value"""] ) if self.adlist[child]["fail_state"] is None: snake_case_ = 0 snake_case_ = ( self.adlist[child]["""output"""] + self.adlist[self.adlist[child]["""fail_state"""]]["""output"""] ) def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : str ) ->dict[str, list[int]]: """simple docstring""" snake_case_ = {} # returns a dict with keywords and list of its occurrences snake_case_ = 0 for i in range(len(UpperCAmelCase_ ) ): while ( self.find_next_state(UpperCAmelCase_ , string[i] ) is None and current_state != 0 ): snake_case_ = self.adlist[current_state]["""fail_state"""] snake_case_ = self.find_next_state(UpperCAmelCase_ , string[i] ) if next_state is None: snake_case_ = 0 else: snake_case_ = next_state for key in self.adlist[current_state]["output"]: if key not in result: snake_case_ = [] result[key].append(i - len(UpperCAmelCase_ ) + 1 ) return result if __name__ == "__main__": import doctest doctest.testmod()
2
0
"""simple docstring""" from ..utils import DummyObject, requires_backends class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: str = ["""torch""", """transformers""", """onnx"""] def __init__( self : Union[str, Any] , *UpperCAmelCase_ : str , **UpperCAmelCase_ : Tuple ) ->Optional[int]: """simple docstring""" requires_backends(self , ["""torch""", """transformers""", """onnx"""] ) @classmethod def lowerCAmelCase ( cls : Optional[int] , *UpperCAmelCase_ : Any , **UpperCAmelCase_ : List[Any] ) ->Optional[int]: """simple docstring""" requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) @classmethod def lowerCAmelCase ( cls : Optional[int] , *UpperCAmelCase_ : List[str] , **UpperCAmelCase_ : Union[str, Any] ) ->Optional[Any]: """simple docstring""" requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: List[Any] = ["""torch""", """transformers""", """onnx"""] def __init__( self : Any , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : int ) ->int: """simple docstring""" requires_backends(self , ["""torch""", """transformers""", """onnx"""] ) @classmethod def lowerCAmelCase ( cls : str , *UpperCAmelCase_ : int , **UpperCAmelCase_ : int ) ->List[Any]: """simple docstring""" requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) @classmethod def lowerCAmelCase ( cls : Union[str, Any] , *UpperCAmelCase_ : Tuple , **UpperCAmelCase_ : Optional[Any] ) ->List[str]: """simple docstring""" requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Optional[Any] = ["""torch""", """transformers""", """onnx"""] def __init__( self : Tuple , *UpperCAmelCase_ : str , **UpperCAmelCase_ : str ) ->str: """simple docstring""" requires_backends(self , ["""torch""", """transformers""", """onnx"""] ) @classmethod def lowerCAmelCase ( cls : Union[str, Any] , *UpperCAmelCase_ : Tuple , **UpperCAmelCase_ : Union[str, Any] ) ->List[str]: """simple docstring""" requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) @classmethod def lowerCAmelCase ( cls : List[Any] , *UpperCAmelCase_ : List[str] , **UpperCAmelCase_ : Tuple ) ->Union[str, Any]: """simple docstring""" requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Optional[int] = ["""torch""", """transformers""", """onnx"""] def __init__( self : int , *UpperCAmelCase_ : Optional[int] , **UpperCAmelCase_ : List[Any] ) ->Tuple: """simple docstring""" requires_backends(self , ["""torch""", """transformers""", """onnx"""] ) @classmethod def lowerCAmelCase ( cls : List[str] , *UpperCAmelCase_ : List[Any] , **UpperCAmelCase_ : List[Any] ) ->Tuple: """simple docstring""" requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) @classmethod def lowerCAmelCase ( cls : List[Any] , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : str ) ->Optional[Any]: """simple docstring""" requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: Any = ["""torch""", """transformers""", """onnx"""] def __init__( self : Any , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : Union[str, Any] ) ->Tuple: """simple docstring""" requires_backends(self , ["""torch""", """transformers""", """onnx"""] ) @classmethod def lowerCAmelCase ( cls : List[str] , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : Union[str, Any] ) ->Dict: """simple docstring""" requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) @classmethod def lowerCAmelCase ( cls : List[Any] , *UpperCAmelCase_ : int , **UpperCAmelCase_ : Any ) ->List[Any]: """simple docstring""" requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) class __A (metaclass=snake_case__): '''simple docstring''' __lowercase: int = ["""torch""", """transformers""", """onnx"""] def __init__( self : Any , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : Tuple ) ->Any: """simple docstring""" requires_backends(self , ["""torch""", """transformers""", """onnx"""] ) @classmethod def lowerCAmelCase ( cls : int , *UpperCAmelCase_ : List[Any] , **UpperCAmelCase_ : Tuple ) ->Tuple: """simple docstring""" requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) @classmethod def lowerCAmelCase ( cls : List[str] , *UpperCAmelCase_ : Any , **UpperCAmelCase_ : Tuple ) ->Any: """simple docstring""" requires_backends(cls , ["""torch""", """transformers""", """onnx"""] )
707
"""simple docstring""" import inspect import unittest from transformers import ConvNextVaConfig from transformers.models.auto import get_values from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES 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 transformers import ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __A : '''simple docstring''' def __init__( self : Optional[int] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[int]=13 , UpperCAmelCase_ : str=32 , UpperCAmelCase_ : List[Any]=3 , UpperCAmelCase_ : Optional[Any]=4 , UpperCAmelCase_ : Dict=[10, 20, 30, 40] , UpperCAmelCase_ : List[Any]=[2, 2, 3, 2] , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : Any=37 , UpperCAmelCase_ : str="gelu" , UpperCAmelCase_ : Optional[int]=10 , UpperCAmelCase_ : Dict=0.02 , UpperCAmelCase_ : int=["stage2", "stage3", "stage4"] , UpperCAmelCase_ : Optional[int]=[2, 3, 4] , UpperCAmelCase_ : List[str]=None , ) ->Union[str, Any]: """simple docstring""" snake_case_ = parent snake_case_ = batch_size snake_case_ = image_size snake_case_ = num_channels snake_case_ = num_stages snake_case_ = hidden_sizes snake_case_ = depths snake_case_ = is_training snake_case_ = use_labels snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = num_labels snake_case_ = initializer_range snake_case_ = out_features snake_case_ = out_indices snake_case_ = scope def lowerCAmelCase ( self : List[str] ) ->str: """simple docstring""" snake_case_ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case_ = None if self.use_labels: snake_case_ = ids_tensor([self.batch_size] , self.num_labels ) snake_case_ = self.get_config() return config, pixel_values, labels def lowerCAmelCase ( self : Dict ) ->Optional[int]: """simple docstring""" return ConvNextVaConfig( num_channels=self.num_channels , hidden_sizes=self.hidden_sizes , depths=self.depths , num_stages=self.num_stages , hidden_act=self.hidden_act , is_decoder=UpperCAmelCase_ , initializer_range=self.initializer_range , out_features=self.out_features , out_indices=self.out_indices , num_labels=self.num_labels , ) def lowerCAmelCase ( self : List[Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Optional[Any] ) ->List[Any]: """simple docstring""" snake_case_ = ConvNextVaModel(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[Any] ) ->Any: """simple docstring""" snake_case_ = ConvNextVaForImageClassification(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCAmelCase ( self : Optional[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Union[str, Any] ) ->Tuple: """simple docstring""" snake_case_ = ConvNextVaBackbone(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ ) # verify hidden states self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:] ) # verify backbone works with out_features=None snake_case_ = None snake_case_ = ConvNextVaBackbone(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" snake_case_ = self.prepare_config_and_inputs() snake_case_ , snake_case_ , snake_case_ = config_and_inputs snake_case_ = {"""pixel_values""": pixel_values} return config, inputs_dict def lowerCAmelCase ( self : List[str] ) ->Union[str, Any]: """simple docstring""" snake_case_ = self.prepare_config_and_inputs() snake_case_ , snake_case_ , snake_case_ = config_and_inputs snake_case_ = {"""pixel_values""": pixel_values, """labels""": labels} return config, inputs_dict @require_torch class __A (snake_case__ , snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Optional[Any] = ( ( ConvNextVaModel, ConvNextVaForImageClassification, ConvNextVaBackbone, ) if is_torch_available() else () ) __lowercase: Union[str, Any] = ( {"""feature-extraction""": ConvNextVaModel, """image-classification""": ConvNextVaForImageClassification} if is_torch_available() else {} ) __lowercase: Union[str, Any] = False __lowercase: Optional[Any] = False __lowercase: Any = False __lowercase: Union[str, Any] = False __lowercase: Dict = False def lowerCAmelCase ( self : Union[str, Any] ) ->Tuple: """simple docstring""" snake_case_ = ConvNextVaModelTester(self ) snake_case_ = ConfigTester(self , config_class=UpperCAmelCase_ , has_text_modality=UpperCAmelCase_ , hidden_size=37 ) def lowerCAmelCase ( self : List[Any] ) ->Optional[Any]: """simple docstring""" 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 lowerCAmelCase ( self : str ) ->Optional[Any]: """simple docstring""" return @unittest.skip(reason="""ConvNextV2 does not use inputs_embeds""" ) def lowerCAmelCase ( self : Optional[int] ) ->Union[str, Any]: """simple docstring""" pass @unittest.skip(reason="""ConvNextV2 does not support input and output embeddings""" ) def lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" pass @unittest.skip(reason="""ConvNextV2 does not use feedforward chunking""" ) def lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" pass def lowerCAmelCase ( self : Dict ) ->Optional[int]: """simple docstring""" if not self.model_tester.is_training: return for model_class in self.all_model_classes: snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_with_labels() snake_case_ = True if model_class.__name__ in [ *get_values(UpperCAmelCase_ ), *get_values(UpperCAmelCase_ ), ]: continue snake_case_ = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.train() snake_case_ = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ , return_labels=UpperCAmelCase_ ) snake_case_ = model(**UpperCAmelCase_ ).loss loss.backward() def lowerCAmelCase ( self : Optional[int] ) ->Any: """simple docstring""" if not self.model_tester.is_training: return for model_class in self.all_model_classes: snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_with_labels() snake_case_ = False snake_case_ = True if ( model_class.__name__ in [*get_values(UpperCAmelCase_ ), *get_values(UpperCAmelCase_ )] or not model_class.supports_gradient_checkpointing ): continue snake_case_ = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.gradient_checkpointing_enable() model.train() snake_case_ = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ , return_labels=UpperCAmelCase_ ) snake_case_ = model(**UpperCAmelCase_ ).loss loss.backward() def lowerCAmelCase ( self : List[Any] ) ->Union[str, Any]: """simple docstring""" snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ = model_class(UpperCAmelCase_ ) snake_case_ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case_ = [*signature.parameters.keys()] snake_case_ = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] ) ->Union[str, Any]: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->Dict: """simple docstring""" def check_hidden_states_output(UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : str ): snake_case_ = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() with torch.no_grad(): snake_case_ = model(**self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) ) snake_case_ = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states snake_case_ = self.model_tester.num_stages self.assertEqual(len(UpperCAmelCase_ ) , expected_num_stages + 1 ) # ConvNextV2's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ = True check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] snake_case_ = True check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] ) ->Dict: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_ ) @slow def lowerCAmelCase ( self : Tuple ) ->str: """simple docstring""" for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ = ConvNextVaModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) def _a ( ) -> str: snake_case_ = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class __A (unittest.TestCase): '''simple docstring''' @cached_property def lowerCAmelCase ( self : Union[str, Any] ) ->Optional[int]: """simple docstring""" return AutoImageProcessor.from_pretrained("""facebook/convnextv2-tiny-1k-224""" ) if is_vision_available() else None @slow def lowerCAmelCase ( self : Tuple ) ->int: """simple docstring""" snake_case_ = ConvNextVaForImageClassification.from_pretrained("""facebook/convnextv2-tiny-1k-224""" ).to(UpperCAmelCase_ ) snake_case_ = self.default_image_processor snake_case_ = prepare_img() snake_case_ = preprocessor(images=UpperCAmelCase_ , return_tensors="""pt""" ).to(UpperCAmelCase_ ) # forward pass with torch.no_grad(): snake_case_ = model(**UpperCAmelCase_ ) # verify the logits snake_case_ = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape , UpperCAmelCase_ ) snake_case_ = torch.tensor([0.9_996, 0.1_966, -0.4_386] ).to(UpperCAmelCase_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCAmelCase_ , atol=1E-4 ) )
2
0
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE ) -> list: # bit count represents no. of bits in the gray code if bit_count < 0: raise ValueError("""The given input must be positive""" ) # get the generated string sequence snake_case_ = gray_code_sequence_string(_SCREAMING_SNAKE_CASE ) # # convert them to integers for i in range(len(_SCREAMING_SNAKE_CASE ) ): snake_case_ = int(sequence[i] , 2 ) return sequence def _a ( _SCREAMING_SNAKE_CASE ) -> list: # The approach is a recursive one # Base case achieved when either n = 0 or n=1 if bit_count == 0: return ["0"] if bit_count == 1: return ["0", "1"] snake_case_ = 1 << bit_count # defines the length of the sequence # 1<< n is equivalent to 2^n # recursive answer will generate answer for n-1 bits snake_case_ = gray_code_sequence_string(bit_count - 1 ) snake_case_ = [] # append 0 to first half of the smaller sequence generated for i in range(seq_len // 2 ): snake_case_ = """0""" + smaller_sequence[i] sequence.append(_SCREAMING_SNAKE_CASE ) # append 1 to second half ... start from the end of the list for i in reversed(range(seq_len // 2 ) ): snake_case_ = """1""" + smaller_sequence[i] sequence.append(_SCREAMING_SNAKE_CASE ) return sequence if __name__ == "__main__": import doctest doctest.testmod()
708
"""simple docstring""" import argparse from pathlib import Path from typing import Dict, OrderedDict, Tuple import torch from audiocraft.models import MusicGen from transformers import ( AutoFeatureExtractor, AutoTokenizer, EncodecModel, MusicgenDecoderConfig, MusicgenForConditionalGeneration, MusicgenProcessor, TaEncoderModel, ) from transformers.models.musicgen.modeling_musicgen import MusicgenForCausalLM from transformers.utils import logging logging.set_verbosity_info() __SCREAMING_SNAKE_CASE : Union[str, Any] = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : int = ['model.decoder.embed_positions.weights'] def _a ( _SCREAMING_SNAKE_CASE ) -> str: if "emb" in name: snake_case_ = name.replace("""emb""" , """model.decoder.embed_tokens""" ) if "transformer" in name: snake_case_ = name.replace("""transformer""" , """model.decoder""" ) if "cross_attention" in name: snake_case_ = name.replace("""cross_attention""" , """encoder_attn""" ) if "linear1" in name: snake_case_ = name.replace("""linear1""" , """fc1""" ) if "linear2" in name: snake_case_ = name.replace("""linear2""" , """fc2""" ) if "norm1" in name: snake_case_ = name.replace("""norm1""" , """self_attn_layer_norm""" ) if "norm_cross" in name: snake_case_ = name.replace("""norm_cross""" , """encoder_attn_layer_norm""" ) if "norm2" in name: snake_case_ = name.replace("""norm2""" , """final_layer_norm""" ) if "out_norm" in name: snake_case_ = name.replace("""out_norm""" , """model.decoder.layer_norm""" ) if "linears" in name: snake_case_ = name.replace("""linears""" , """lm_heads""" ) if "condition_provider.conditioners.description.output_proj" in name: snake_case_ = name.replace("""condition_provider.conditioners.description.output_proj""" , """enc_to_dec_proj""" ) return name def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple[Dict, Dict]: snake_case_ = list(state_dict.keys() ) snake_case_ = {} for key in keys: snake_case_ = state_dict.pop(_SCREAMING_SNAKE_CASE ) snake_case_ = rename_keys(_SCREAMING_SNAKE_CASE ) if "in_proj_weight" in key: # split fused qkv proj snake_case_ = val[:hidden_size, :] snake_case_ = val[hidden_size : 2 * hidden_size, :] snake_case_ = val[-hidden_size:, :] elif "enc_to_dec_proj" in key: snake_case_ = val else: snake_case_ = val return state_dict, enc_dec_proj_state_dict def _a ( _SCREAMING_SNAKE_CASE ) -> MusicgenDecoderConfig: if checkpoint == "small": # default config values snake_case_ = 1_024 snake_case_ = 24 snake_case_ = 16 elif checkpoint == "medium": snake_case_ = 1_536 snake_case_ = 48 snake_case_ = 24 elif checkpoint == "large": snake_case_ = 2_048 snake_case_ = 48 snake_case_ = 32 else: raise ValueError(f"""Checkpoint should be one of `['small', 'medium', 'large']`, got {checkpoint}.""" ) snake_case_ = MusicgenDecoderConfig( hidden_size=_SCREAMING_SNAKE_CASE , ffn_dim=hidden_size * 4 , num_hidden_layers=_SCREAMING_SNAKE_CASE , num_attention_heads=_SCREAMING_SNAKE_CASE , ) return config @torch.no_grad() def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE="cpu" ) -> Tuple: snake_case_ = MusicGen.get_pretrained(_SCREAMING_SNAKE_CASE , device=_SCREAMING_SNAKE_CASE ) snake_case_ = decoder_config_from_checkpoint(_SCREAMING_SNAKE_CASE ) snake_case_ = fairseq_model.lm.state_dict() snake_case_ , snake_case_ = rename_state_dict( _SCREAMING_SNAKE_CASE , hidden_size=decoder_config.hidden_size ) snake_case_ = TaEncoderModel.from_pretrained("""t5-base""" ) snake_case_ = EncodecModel.from_pretrained("""facebook/encodec_32khz""" ) snake_case_ = MusicgenForCausalLM(_SCREAMING_SNAKE_CASE ).eval() # load all decoder weights - expect that we'll be missing embeddings and enc-dec projection snake_case_ , snake_case_ = decoder.load_state_dict(_SCREAMING_SNAKE_CASE , strict=_SCREAMING_SNAKE_CASE ) for key in missing_keys.copy(): if key.startswith(("""text_encoder""", """audio_encoder""") ) or key in EXPECTED_MISSING_KEYS: missing_keys.remove(_SCREAMING_SNAKE_CASE ) if len(_SCREAMING_SNAKE_CASE ) > 0: raise ValueError(f"""Missing key(s) in state_dict: {missing_keys}""" ) if len(_SCREAMING_SNAKE_CASE ) > 0: raise ValueError(f"""Unexpected key(s) in state_dict: {unexpected_keys}""" ) # init the composite model snake_case_ = MusicgenForConditionalGeneration(text_encoder=_SCREAMING_SNAKE_CASE , audio_encoder=_SCREAMING_SNAKE_CASE , decoder=_SCREAMING_SNAKE_CASE ) # load the pre-trained enc-dec projection (from the decoder state dict) model.enc_to_dec_proj.load_state_dict(_SCREAMING_SNAKE_CASE ) # check we can do a forward pass snake_case_ = torch.arange(0 , 8 , dtype=torch.long ).reshape(2 , -1 ) snake_case_ = input_ids.reshape(2 * 4 , -1 ) with torch.no_grad(): snake_case_ = model(input_ids=_SCREAMING_SNAKE_CASE , decoder_input_ids=_SCREAMING_SNAKE_CASE ).logits if logits.shape != (8, 1, 2_048): raise ValueError("""Incorrect shape for logits""" ) # now construct the processor snake_case_ = AutoTokenizer.from_pretrained("""t5-base""" ) snake_case_ = AutoFeatureExtractor.from_pretrained("""facebook/encodec_32khz""" , padding_side="""left""" ) snake_case_ = MusicgenProcessor(feature_extractor=_SCREAMING_SNAKE_CASE , tokenizer=_SCREAMING_SNAKE_CASE ) # set the appropriate bos/pad token ids snake_case_ = 2_048 snake_case_ = 2_048 # set other default generation config params snake_case_ = int(30 * audio_encoder.config.frame_rate ) snake_case_ = True snake_case_ = 3.0 if pytorch_dump_folder is not None: Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) logger.info(f"""Saving model {checkpoint} to {pytorch_dump_folder}""" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) processor.save_pretrained(_SCREAMING_SNAKE_CASE ) if repo_id: logger.info(f"""Pushing model {checkpoint} to {repo_id}""" ) model.push_to_hub(_SCREAMING_SNAKE_CASE ) processor.push_to_hub(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( '--checkpoint', default='small', type=str, help='Checkpoint size of the MusicGen model you\'d like to convert. Can be one of: `[\'small\', \'medium\', \'large\']`.', ) parser.add_argument( '--pytorch_dump_folder', required=True, default=None, type=str, help='Path to the output PyTorch model directory.', ) parser.add_argument( '--push_to_hub', default=None, type=str, help='Where to upload the converted model on the 🤗 hub.' ) parser.add_argument( '--device', default='cpu', type=str, help='Torch device to run the conversion, either cpu or cuda.' ) __SCREAMING_SNAKE_CASE : int = parser.parse_args() convert_musicgen_checkpoint(args.checkpoint, args.pytorch_dump_folder, args.push_to_hub)
2
0
"""simple docstring""" import argparse import datetime import json import time import warnings from logging import getLogger from pathlib import Path from typing import Dict, List import torch from tqdm import tqdm from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from utils import calculate_bleu, calculate_rouge, chunks, parse_numeric_n_bool_cl_kwargs, use_task_specific_params __SCREAMING_SNAKE_CASE : Optional[Any] = getLogger(__name__) __SCREAMING_SNAKE_CASE : Optional[int] = 'cuda' if torch.cuda.is_available() else 'cpu' def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 8 , _SCREAMING_SNAKE_CASE = DEFAULT_DEVICE , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE="summarization" , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE , ) -> Dict: snake_case_ = Path(_SCREAMING_SNAKE_CASE ).open("""w""" , encoding="""utf-8""" ) snake_case_ = str(_SCREAMING_SNAKE_CASE ) snake_case_ = AutoModelForSeqaSeqLM.from_pretrained(_SCREAMING_SNAKE_CASE ).to(_SCREAMING_SNAKE_CASE ) if fpaa: snake_case_ = model.half() snake_case_ = AutoTokenizer.from_pretrained(_SCREAMING_SNAKE_CASE ) logger.info(f"""Inferred tokenizer type: {tokenizer.__class__}""" ) # if this is wrong, check config.model_type. snake_case_ = time.time() # update config with task specific params use_task_specific_params(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if prefix is None: snake_case_ = prefix or getattr(model.config , """prefix""" , """""" ) or """""" for examples_chunk in tqdm(list(chunks(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) ): snake_case_ = [prefix + text for text in examples_chunk] snake_case_ = tokenizer(_SCREAMING_SNAKE_CASE , return_tensors="""pt""" , truncation=_SCREAMING_SNAKE_CASE , padding="""longest""" ).to(_SCREAMING_SNAKE_CASE ) snake_case_ = model.generate( input_ids=batch.input_ids , attention_mask=batch.attention_mask , **_SCREAMING_SNAKE_CASE , ) snake_case_ = tokenizer.batch_decode(_SCREAMING_SNAKE_CASE , skip_special_tokens=_SCREAMING_SNAKE_CASE , clean_up_tokenization_spaces=_SCREAMING_SNAKE_CASE ) for hypothesis in dec: fout.write(hypothesis + """\n""" ) fout.flush() fout.close() snake_case_ = int(time.time() - start_time ) # seconds snake_case_ = len(_SCREAMING_SNAKE_CASE ) return {"n_obs": n_obs, "runtime": runtime, "seconds_per_sample": round(runtime / n_obs , 4 )} def _a ( ) -> List[str]: return datetime.datetime.now().strftime("""%Y-%m-%d %H:%M:%S""" ) def _a ( _SCREAMING_SNAKE_CASE=True ) -> Optional[Any]: snake_case_ = argparse.ArgumentParser() parser.add_argument("""model_name""" , type=_SCREAMING_SNAKE_CASE , help="""like facebook/bart-large-cnn,t5-base, etc.""" ) parser.add_argument("""input_path""" , type=_SCREAMING_SNAKE_CASE , help="""like cnn_dm/test.source""" ) parser.add_argument("""save_path""" , type=_SCREAMING_SNAKE_CASE , help="""where to save summaries""" ) parser.add_argument("""--reference_path""" , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , help="""like cnn_dm/test.target""" ) parser.add_argument("""--score_path""" , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , default="""metrics.json""" , help="""where to save metrics""" ) parser.add_argument("""--device""" , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , default=_SCREAMING_SNAKE_CASE , help="""cuda, cuda:1, cpu etc.""" ) parser.add_argument( """--prefix""" , type=_SCREAMING_SNAKE_CASE , required=_SCREAMING_SNAKE_CASE , default=_SCREAMING_SNAKE_CASE , help="""will be added to the begininng of src examples""" ) parser.add_argument("""--task""" , type=_SCREAMING_SNAKE_CASE , default="""summarization""" , help="""used for task_specific_params + metrics""" ) parser.add_argument("""--bs""" , type=_SCREAMING_SNAKE_CASE , default=8 , required=_SCREAMING_SNAKE_CASE , help="""batch size""" ) parser.add_argument( """--n_obs""" , type=_SCREAMING_SNAKE_CASE , default=-1 , required=_SCREAMING_SNAKE_CASE , help="""How many observations. Defaults to all.""" ) parser.add_argument("""--fp16""" , action="""store_true""" ) parser.add_argument("""--dump-args""" , action="""store_true""" , help="""print the custom hparams with the results""" ) parser.add_argument( """--info""" , nargs="""?""" , type=_SCREAMING_SNAKE_CASE , const=datetime_now() , help=( """use in conjunction w/ --dump-args to print with the results whatever other info you'd like, e.g.""" """ lang=en-ru. If no value is passed, the current datetime string will be used.""" ) , ) # Unspecified args like --num_beams=2 --decoder_start_token_id=4 are passed to model.generate snake_case_ , snake_case_ = parser.parse_known_args() snake_case_ = parse_numeric_n_bool_cl_kwargs(_SCREAMING_SNAKE_CASE ) if parsed_args and verbose: print(f"""parsed the following generate kwargs: {parsed_args}""" ) snake_case_ = [""" """ + x.rstrip() if """t5""" in args.model_name else x.rstrip() for x in open(args.input_path ).readlines()] if args.n_obs > 0: snake_case_ = examples[: args.n_obs] Path(args.save_path ).parent.mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) if args.reference_path is None and Path(args.score_path ).exists(): warnings.warn(f"""score_path {args.score_path} will be overwritten unless you type ctrl-c.""" ) if args.device == "cpu" and args.fpaa: # this mix leads to RuntimeError: "threshold_cpu" not implemented for 'Half' raise ValueError("""Can't mix --fp16 and --device cpu""" ) snake_case_ = generate_summaries_or_translations( _SCREAMING_SNAKE_CASE , args.save_path , args.model_name , batch_size=args.bs , device=args.device , fpaa=args.fpaa , task=args.task , prefix=args.prefix , **_SCREAMING_SNAKE_CASE , ) if args.reference_path is None: return {} # Compute scores snake_case_ = calculate_bleu if """translation""" in args.task else calculate_rouge snake_case_ = [x.rstrip() for x in open(args.save_path ).readlines()] snake_case_ = [x.rstrip() for x in open(args.reference_path ).readlines()][: len(_SCREAMING_SNAKE_CASE )] snake_case_ = score_fn(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) scores.update(_SCREAMING_SNAKE_CASE ) if args.dump_args: scores.update(_SCREAMING_SNAKE_CASE ) if args.info: snake_case_ = args.info if verbose: print(_SCREAMING_SNAKE_CASE ) if args.score_path is not None: json.dump(_SCREAMING_SNAKE_CASE , open(args.score_path , """w""" ) ) return scores if __name__ == "__main__": # Usage for MT: # python run_eval.py MODEL_NAME $DATA_DIR/test.source $save_dir/test_translations.txt --reference_path $DATA_DIR/test.target --score_path $save_dir/test_bleu.json --task translation $@ run_generate(verbose=True)
709
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> int: if index == number_of_items: return 0 snake_case_ = 0 snake_case_ = 0 snake_case_ = knapsack(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , index + 1 ) if weights[index] <= max_weight: snake_case_ = values[index] + knapsack( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , max_weight - weights[index] , index + 1 ) return max(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": import doctest doctest.testmod()
2
0
"""simple docstring""" import os try: from .build_directory_md import good_file_paths except ImportError: from build_directory_md import good_file_paths # type: ignore __SCREAMING_SNAKE_CASE : Union[str, Any] = list(good_file_paths()) assert filepaths, "good_file_paths() failed!" __SCREAMING_SNAKE_CASE : Optional[Any] = [file for file in filepaths if file != file.lower()] if upper_files: print(f"""{len(upper_files)} files contain uppercase characters:""") print('\n'.join(upper_files) + '\n') __SCREAMING_SNAKE_CASE : List[str] = [file for file in filepaths if ' ' in file] if space_files: print(f"""{len(space_files)} files contain space characters:""") print('\n'.join(space_files) + '\n') __SCREAMING_SNAKE_CASE : List[Any] = [file for file in filepaths if '-' in file] if hyphen_files: print(f"""{len(hyphen_files)} files contain hyphen characters:""") print('\n'.join(hyphen_files) + '\n') __SCREAMING_SNAKE_CASE : List[str] = [file for file in filepaths if os.sep not in file] if nodir_files: print(f"""{len(nodir_files)} files are not in a directory:""") print('\n'.join(nodir_files) + '\n') __SCREAMING_SNAKE_CASE : str = len(upper_files + space_files + hyphen_files + nodir_files) if bad_files: import sys sys.exit(bad_files)
710
"""simple docstring""" from math import factorial def _a ( _SCREAMING_SNAKE_CASE = 20 ) -> int: snake_case_ = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1, # 2, 3,... snake_case_ = n // 2 return int(factorial(_SCREAMING_SNAKE_CASE ) / (factorial(_SCREAMING_SNAKE_CASE ) * factorial(n - k )) ) if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution(20)) else: try: __SCREAMING_SNAKE_CASE : Optional[int] = int(sys.argv[1]) print(solution(n)) except ValueError: print('Invalid entry - please enter a number.')
2
0
"""simple docstring""" import numpy as np import torch from torch.utils.data import Dataset, IterableDataset from ..utils.generic import ModelOutput class __A (snake_case__): def __init__( self : Optional[int] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : str ) ->Tuple: """simple docstring""" snake_case_ = dataset snake_case_ = process snake_case_ = params def __len__( self : Tuple ) ->List[Any]: """simple docstring""" return len(self.dataset ) def __getitem__( self : List[str] , UpperCAmelCase_ : Any ) ->Dict: """simple docstring""" snake_case_ = self.dataset[i] snake_case_ = self.process(UpperCAmelCase_ , **self.params ) return processed class __A (snake_case__): def __init__( self : Optional[int] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : str=None ) ->Dict: """simple docstring""" snake_case_ = loader snake_case_ = infer snake_case_ = params if loader_batch_size == 1: # Let's spare some time by deactivating altogether snake_case_ = None snake_case_ = loader_batch_size # Internal bookkeeping snake_case_ = None snake_case_ = None def __len__( self : int ) ->Optional[int]: """simple docstring""" return len(self.loader ) def __iter__( self : Dict ) ->List[Any]: """simple docstring""" snake_case_ = iter(self.loader ) return self def lowerCAmelCase ( self : Tuple ) ->Dict: """simple docstring""" if isinstance(self._loader_batch_data , torch.Tensor ): # Batch data is simple tensor, just fetch the slice snake_case_ = self._loader_batch_data[self._loader_batch_index] else: # Batch data is assumed to be BaseModelOutput (or dict) snake_case_ = {} for k, element in self._loader_batch_data.items(): if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): # Convert ModelOutput to tuple first snake_case_ = element.to_tuple() if isinstance(element[0] , torch.Tensor ): snake_case_ = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): snake_case_ = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if k in {"hidden_states", "past_key_values", "attentions"} and isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): # Those are stored as lists of tensors so need specific unbatching. if isinstance(element[0] , torch.Tensor ): snake_case_ = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): snake_case_ = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if element is None: # This can happen for optional data that get passed around snake_case_ = None elif isinstance(element[self._loader_batch_index] , torch.Tensor ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers snake_case_ = element[self._loader_batch_index].unsqueeze(0 ) elif isinstance(element[self._loader_batch_index] , np.ndarray ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers snake_case_ = np.expand_dims(element[self._loader_batch_index] , 0 ) else: # This is typically a list, so no need to `unsqueeze`. snake_case_ = element[self._loader_batch_index] # Recreate the element by reusing the original class to make it look # batch_size=1 snake_case_ = self._loader_batch_data.__class__(UpperCAmelCase_ ) self._loader_batch_index += 1 return result def lowerCAmelCase ( self : List[str] ) ->Any: """simple docstring""" if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: # We are currently unrolling a batch so we just need to return # the current item within a batch return self.loader_batch_item() # We're out of items within a batch snake_case_ = next(self.iterator ) snake_case_ = self.infer(UpperCAmelCase_ , **self.params ) # We now have a batch of "inferred things". if self.loader_batch_size is not None: # Try to infer the size of the batch if isinstance(UpperCAmelCase_ , torch.Tensor ): snake_case_ = processed else: snake_case_ = list(processed.keys() )[0] snake_case_ = processed[key] if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): snake_case_ = len(UpperCAmelCase_ ) else: snake_case_ = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. snake_case_ = observed_batch_size # Setting internal index to unwrap the batch snake_case_ = processed snake_case_ = 0 return self.loader_batch_item() else: # We're not unrolling batches return processed class __A (snake_case__): def __init__( self : Optional[Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Optional[Any]=None ) ->str: """simple docstring""" super().__init__(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) def __iter__( self : Dict ) ->Optional[int]: """simple docstring""" snake_case_ = iter(self.loader ) snake_case_ = None return self def lowerCAmelCase ( self : Union[str, Any] ) ->Optional[Any]: """simple docstring""" if self.subiterator is None: snake_case_ = self.infer(next(self.iterator ) , **self.params ) try: # Try to return next item snake_case_ = next(self.subiterator ) except StopIteration: # When a preprocess iterator ends, we can start lookig at the next item # ChunkIterator will keep feeding until ALL elements of iterator # all have created their subiterator and have been iterating against. # # Another way to look at it, is we're basically flattening lists of lists # into a single list, but with generators snake_case_ = self.infer(next(self.iterator ) , **self.params ) snake_case_ = next(self.subiterator ) return processed class __A (snake_case__): def __iter__( self : List[Any] ) ->int: """simple docstring""" snake_case_ = iter(self.loader ) return self def lowerCAmelCase ( self : Optional[int] ) ->Tuple: """simple docstring""" snake_case_ = False snake_case_ = [] if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: while self._loader_batch_index < self.loader_batch_size: snake_case_ = self.loader_batch_item() snake_case_ = item.pop("""is_last""" ) accumulator.append(UpperCAmelCase_ ) if is_last: return accumulator while not is_last: snake_case_ = self.infer(next(self.iterator ) , **self.params ) if self.loader_batch_size is not None: if isinstance(UpperCAmelCase_ , torch.Tensor ): snake_case_ = processed else: snake_case_ = list(processed.keys() )[0] snake_case_ = processed[key] if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): snake_case_ = len(UpperCAmelCase_ ) else: snake_case_ = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. snake_case_ = observed_batch_size snake_case_ = processed snake_case_ = 0 while self._loader_batch_index < self.loader_batch_size: snake_case_ = self.loader_batch_item() snake_case_ = item.pop("""is_last""" ) accumulator.append(UpperCAmelCase_ ) if is_last: return accumulator else: snake_case_ = processed snake_case_ = item.pop("""is_last""" ) accumulator.append(UpperCAmelCase_ ) return accumulator class __A (snake_case__): def __init__( self : List[Any] , UpperCAmelCase_ : Dataset , UpperCAmelCase_ : str ) ->Tuple: """simple docstring""" snake_case_ = dataset snake_case_ = key def __len__( self : Union[str, Any] ) ->int: """simple docstring""" return len(self.dataset ) def __getitem__( self : Optional[Any] , UpperCAmelCase_ : Optional[Any] ) ->Dict: """simple docstring""" return self.dataset[i][self.key] class __A (snake_case__): def __init__( self : Any , UpperCAmelCase_ : Dataset , UpperCAmelCase_ : str , UpperCAmelCase_ : str ) ->Dict: """simple docstring""" snake_case_ = dataset snake_case_ = keya snake_case_ = keya def __len__( self : Dict ) ->List[str]: """simple docstring""" return len(self.dataset ) def __getitem__( self : Optional[Any] , UpperCAmelCase_ : Union[str, Any] ) ->Tuple: """simple docstring""" return {"text": self.dataset[i][self.keya], "text_pair": self.dataset[i][self.keya]}
711
"""simple docstring""" import secrets from random import shuffle from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation def _a ( _SCREAMING_SNAKE_CASE = 8 ) -> str: snake_case_ = ascii_letters + digits + punctuation return "".join(secrets.choice(_SCREAMING_SNAKE_CASE ) for _ in range(_SCREAMING_SNAKE_CASE ) ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: # Password Generator = full boot with random_number, random_letters, and # random_character FUNCTIONS # Put your code here... i -= len(_SCREAMING_SNAKE_CASE ) snake_case_ = i // 3 snake_case_ = i % 3 # chars = chars_incl + random_letters(ascii_letters, i / 3 + remainder) + # random_number(digits, i / 3) + random_characters(punctuation, i / 3) snake_case_ = ( chars_incl + random(_SCREAMING_SNAKE_CASE , quotient + remainder ) + random(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) + random(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) snake_case_ = list(_SCREAMING_SNAKE_CASE ) shuffle(_SCREAMING_SNAKE_CASE ) return "".join(_SCREAMING_SNAKE_CASE ) # random is a generalised function for letters, characters and numbers def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: return "".join(secrets.choice(_SCREAMING_SNAKE_CASE ) for _ in range(_SCREAMING_SNAKE_CASE ) ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: pass # Put your code here... def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[str]: pass # Put your code here... def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[int]: pass # Put your code here... def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 8 ) -> bool: if len(_SCREAMING_SNAKE_CASE ) < min_length: # Your Password must be at least 8 characters long return False snake_case_ = any(char in ascii_uppercase for char in password ) snake_case_ = any(char in ascii_lowercase for char in password ) snake_case_ = any(char in digits for char in password ) snake_case_ = any(char in punctuation for char in password ) return upper and lower and num and spec_char # Passwords should contain UPPERCASE, lowerase # numbers, and special characters def _a ( ) -> str: snake_case_ = int(input("""Please indicate the max length of your password: """ ).strip() ) snake_case_ = input( """Please indicate the characters that must be in your password: """ ).strip() print("""Password generated:""" , password_generator(_SCREAMING_SNAKE_CASE ) ) print( """Alternative Password generated:""" , alternative_password_generator(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) , ) print("""[If you are thinking of using this passsword, You better save it.]""" ) if __name__ == "__main__": main()
2
0
"""simple docstring""" import io import math from typing import Dict, Optional, Union import numpy as np from huggingface_hub import hf_hub_download from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import convert_to_rgb, normalize, to_channel_dimension_format, to_pil_image from ...image_utils import ( ChannelDimension, ImageInput, get_image_size, infer_channel_dimension_format, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_torch_available, is_vision_available, logging from ...utils.import_utils import requires_backends if is_vision_available(): import textwrap from PIL import Image, ImageDraw, ImageFont if is_torch_available(): import torch from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: __SCREAMING_SNAKE_CASE : Any = False __SCREAMING_SNAKE_CASE : List[str] = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Optional[Any] = 'ybelkada/fonts' def _a ( ) -> Union[str, Any]: if is_torch_available() and not is_torch_greater_or_equal_than_1_11: raise ImportError( f"""You are using torch=={torch.__version__}, but torch>=1.11.0 is required to use """ """Pix2StructImageProcessor. Please upgrade torch.""" ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple: requires_backends(_SCREAMING_SNAKE_CASE , ["""torch"""] ) _check_torch_version() snake_case_ = image_tensor.unsqueeze(0 ) snake_case_ = torch.nn.functional.unfold(_SCREAMING_SNAKE_CASE , (patch_height, patch_width) , stride=(patch_height, patch_width) ) snake_case_ = patches.reshape(image_tensor.size(0 ) , image_tensor.size(1 ) , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , -1 ) snake_case_ = patches.permute(0 , 4 , 2 , 3 , 1 ).reshape( image_tensor.size(2 ) // patch_height , image_tensor.size(3 ) // patch_width , image_tensor.size(1 ) * patch_height * patch_width , ) return patches.unsqueeze(0 ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 36 , _SCREAMING_SNAKE_CASE = "black" , _SCREAMING_SNAKE_CASE = "white" , _SCREAMING_SNAKE_CASE = 5 , _SCREAMING_SNAKE_CASE = 5 , _SCREAMING_SNAKE_CASE = 5 , _SCREAMING_SNAKE_CASE = 5 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , ) -> Image.Image: requires_backends(_SCREAMING_SNAKE_CASE , """vision""" ) # Add new lines so that each line is no more than 80 characters. snake_case_ = textwrap.TextWrapper(width=80 ) snake_case_ = wrapper.wrap(text=_SCREAMING_SNAKE_CASE ) snake_case_ = """\n""".join(_SCREAMING_SNAKE_CASE ) if font_bytes is not None and font_path is None: snake_case_ = io.BytesIO(_SCREAMING_SNAKE_CASE ) elif font_path is not None: snake_case_ = font_path else: snake_case_ = hf_hub_download(_SCREAMING_SNAKE_CASE , """Arial.TTF""" ) snake_case_ = ImageFont.truetype(_SCREAMING_SNAKE_CASE , encoding="""UTF-8""" , size=_SCREAMING_SNAKE_CASE ) # Use a temporary canvas to determine the width and height in pixels when # rendering the text. snake_case_ = ImageDraw.Draw(Image.new("""RGB""" , (1, 1) , _SCREAMING_SNAKE_CASE ) ) snake_case_ , snake_case_ , snake_case_ , snake_case_ = temp_draw.textbbox((0, 0) , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Create the actual image with a bit of padding around the text. snake_case_ = text_width + left_padding + right_padding snake_case_ = text_height + top_padding + bottom_padding snake_case_ = Image.new("""RGB""" , (image_width, image_height) , _SCREAMING_SNAKE_CASE ) snake_case_ = ImageDraw.Draw(_SCREAMING_SNAKE_CASE ) draw.text(xy=(left_padding, top_padding) , text=_SCREAMING_SNAKE_CASE , fill=_SCREAMING_SNAKE_CASE , font=_SCREAMING_SNAKE_CASE ) return image def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> Any: requires_backends(_SCREAMING_SNAKE_CASE , """vision""" ) # Convert to PIL image if necessary snake_case_ = to_pil_image(_SCREAMING_SNAKE_CASE ) snake_case_ = render_text(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) snake_case_ = max(header_image.width , image.width ) snake_case_ = int(image.height * (new_width / image.width) ) snake_case_ = int(header_image.height * (new_width / header_image.width) ) snake_case_ = Image.new("""RGB""" , (new_width, new_height + new_header_height) , """white""" ) new_image.paste(header_image.resize((new_width, new_header_height) ) , (0, 0) ) new_image.paste(image.resize((new_width, new_height) ) , (0, new_header_height) ) # Convert back to the original framework if necessary snake_case_ = to_numpy_array(_SCREAMING_SNAKE_CASE ) if infer_channel_dimension_format(_SCREAMING_SNAKE_CASE ) == ChannelDimension.LAST: snake_case_ = to_channel_dimension_format(_SCREAMING_SNAKE_CASE , ChannelDimension.LAST ) return new_image class __A (snake_case__): '''simple docstring''' __lowercase: Tuple = ["""flattened_patches"""] def __init__( self : Optional[Any] , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Dict[str, int] = None , UpperCAmelCase_ : int = 2_048 , UpperCAmelCase_ : bool = False , **UpperCAmelCase_ : Any , ) ->None: """simple docstring""" super().__init__(**UpperCAmelCase_ ) snake_case_ = patch_size if patch_size is not None else {"""height""": 16, """width""": 16} snake_case_ = do_normalize snake_case_ = do_convert_rgb snake_case_ = max_patches snake_case_ = is_vqa def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : np.ndarray , UpperCAmelCase_ : int , UpperCAmelCase_ : dict , **UpperCAmelCase_ : List[Any] ) ->np.ndarray: """simple docstring""" requires_backends(self.extract_flattened_patches , """torch""" ) _check_torch_version() # convert to torch snake_case_ = to_channel_dimension_format(UpperCAmelCase_ , ChannelDimension.FIRST ) snake_case_ = torch.from_numpy(UpperCAmelCase_ ) snake_case_ , snake_case_ = patch_size["""height"""], patch_size["""width"""] snake_case_ , snake_case_ = get_image_size(UpperCAmelCase_ ) # maximize scale s.t. snake_case_ = math.sqrt(max_patches * (patch_height / image_height) * (patch_width / image_width) ) snake_case_ = max(min(math.floor(scale * image_height / patch_height ) , UpperCAmelCase_ ) , 1 ) snake_case_ = max(min(math.floor(scale * image_width / patch_width ) , UpperCAmelCase_ ) , 1 ) snake_case_ = max(num_feasible_rows * patch_height , 1 ) snake_case_ = max(num_feasible_cols * patch_width , 1 ) snake_case_ = torch.nn.functional.interpolate( image.unsqueeze(0 ) , size=(resized_height, resized_width) , mode="""bilinear""" , align_corners=UpperCAmelCase_ , antialias=UpperCAmelCase_ , ).squeeze(0 ) # [1, rows, columns, patch_height * patch_width * image_channels] snake_case_ = torch_extract_patches(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = patches.shape snake_case_ = patches_shape[1] snake_case_ = patches_shape[2] snake_case_ = patches_shape[3] # [rows * columns, patch_height * patch_width * image_channels] snake_case_ = patches.reshape([rows * columns, depth] ) # [rows * columns, 1] snake_case_ = torch.arange(UpperCAmelCase_ ).reshape([rows, 1] ).repeat(1 , UpperCAmelCase_ ).reshape([rows * columns, 1] ) snake_case_ = torch.arange(UpperCAmelCase_ ).reshape([1, columns] ).repeat(UpperCAmelCase_ , 1 ).reshape([rows * columns, 1] ) # Offset by 1 so the ids do not contain zeros, which represent padding. row_ids += 1 col_ids += 1 # Prepare additional patch features. # [rows * columns, 1] snake_case_ = row_ids.to(torch.floataa ) snake_case_ = col_ids.to(torch.floataa ) # [rows * columns, 2 + patch_height * patch_width * image_channels] snake_case_ = torch.cat([row_ids, col_ids, patches] , -1 ) # [max_patches, 2 + patch_height * patch_width * image_channels] snake_case_ = torch.nn.functional.pad(UpperCAmelCase_ , [0, 0, 0, max_patches - (rows * columns)] ).float() snake_case_ = to_numpy_array(UpperCAmelCase_ ) return result def lowerCAmelCase ( self : Any , UpperCAmelCase_ : np.ndarray , UpperCAmelCase_ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase_ : Union[str, Any] ) ->np.ndarray: """simple docstring""" if image.dtype == np.uinta: snake_case_ = image.astype(np.floataa ) # take mean across the whole `image` snake_case_ = np.mean(UpperCAmelCase_ ) snake_case_ = np.std(UpperCAmelCase_ ) snake_case_ = max(UpperCAmelCase_ , 1.0 / math.sqrt(np.prod(image.shape ) ) ) return normalize(UpperCAmelCase_ , mean=UpperCAmelCase_ , std=UpperCAmelCase_ , **UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : ImageInput , UpperCAmelCase_ : Optional[str] = None , UpperCAmelCase_ : bool = None , UpperCAmelCase_ : Optional[bool] = None , UpperCAmelCase_ : Optional[int] = None , UpperCAmelCase_ : Optional[Dict[str, int]] = None , UpperCAmelCase_ : Optional[Union[str, TensorType]] = None , UpperCAmelCase_ : ChannelDimension = ChannelDimension.FIRST , **UpperCAmelCase_ : Union[str, Any] , ) ->ImageInput: """simple docstring""" snake_case_ = do_normalize if do_normalize is not None else self.do_normalize snake_case_ = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb snake_case_ = patch_size if patch_size is not None else self.patch_size snake_case_ = max_patches if max_patches is not None else self.max_patches snake_case_ = self.is_vqa if kwargs.get("""data_format""" , UpperCAmelCase_ ) is not None: raise ValueError("""data_format is not an accepted input as the outputs are """ ) snake_case_ = 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.""" ) # PIL RGBA images are converted to RGB if do_convert_rgb: snake_case_ = [convert_to_rgb(UpperCAmelCase_ ) for image in images] # All transformations expect numpy arrays. snake_case_ = [to_numpy_array(UpperCAmelCase_ ) for image in images] if is_vqa: if header_text is None: raise ValueError("""A header text must be provided for VQA models.""" ) snake_case_ = kwargs.pop("""font_bytes""" , UpperCAmelCase_ ) snake_case_ = kwargs.pop("""font_path""" , UpperCAmelCase_ ) if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): snake_case_ = [header_text] * len(UpperCAmelCase_ ) snake_case_ = [ render_header(UpperCAmelCase_ , header_text[i] , font_bytes=UpperCAmelCase_ , font_path=UpperCAmelCase_ ) for i, image in enumerate(UpperCAmelCase_ ) ] if do_normalize: snake_case_ = [self.normalize(image=UpperCAmelCase_ ) for image in images] # convert to torch tensor and permute snake_case_ = [ self.extract_flattened_patches(image=UpperCAmelCase_ , max_patches=UpperCAmelCase_ , patch_size=UpperCAmelCase_ ) for image in images ] # create attention mask in numpy snake_case_ = [(image.sum(axis=-1 ) != 0).astype(np.floataa ) for image in images] snake_case_ = BatchFeature( data={"""flattened_patches""": images, """attention_mask""": attention_masks} , tensor_type=UpperCAmelCase_ ) return encoded_outputs
712
"""simple docstring""" import json import os import tempfile import unittest import numpy as np from datasets import load_dataset 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 if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ImageGPTImageProcessor class __A (unittest.TestCase): '''simple docstring''' def __init__( self : int , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Tuple=7 , UpperCAmelCase_ : Dict=3 , UpperCAmelCase_ : Tuple=18 , UpperCAmelCase_ : Optional[Any]=30 , UpperCAmelCase_ : str=400 , UpperCAmelCase_ : int=True , UpperCAmelCase_ : Optional[int]=None , UpperCAmelCase_ : Optional[Any]=True , ) ->Optional[Any]: """simple docstring""" snake_case_ = size if size is not None else {"""height""": 18, """width""": 18} snake_case_ = parent snake_case_ = batch_size snake_case_ = num_channels snake_case_ = image_size snake_case_ = min_resolution snake_case_ = max_resolution snake_case_ = do_resize snake_case_ = size snake_case_ = do_normalize def lowerCAmelCase ( self : List[str] ) ->Optional[Any]: """simple docstring""" return { # here we create 2 clusters for the sake of simplicity "clusters": np.asarray( [ [0.8_866_443_634_033_203, 0.6_618_829_369_544_983, 0.3_891_746_401_786_804], [-0.6_042_559_146_881_104, -0.02_295_008_860_528_469, 0.5_423_797_369_003_296], ] ), "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, } @require_torch @require_vision class __A (snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: List[Any] = ImageGPTImageProcessor if is_vision_available() else None def lowerCAmelCase ( self : Optional[int] ) ->Optional[int]: """simple docstring""" snake_case_ = ImageGPTImageProcessingTester(self ) @property def lowerCAmelCase ( self : Tuple ) ->List[Any]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(UpperCAmelCase_ , """clusters""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """do_resize""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """size""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """do_normalize""" ) ) def lowerCAmelCase ( self : Optional[int] ) ->Optional[Any]: """simple docstring""" snake_case_ = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""height""": 18, """width""": 18} ) snake_case_ = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {"""height""": 42, """width""": 42} ) def lowerCAmelCase ( self : Any ) ->List[Any]: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) snake_case_ = json.loads(image_processor.to_json_string() ) for key, value in self.image_processor_dict.items(): if key == "clusters": self.assertTrue(np.array_equal(UpperCAmelCase_ , obj[key] ) ) else: self.assertEqual(obj[key] , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] ) ->Dict: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: snake_case_ = os.path.join(UpperCAmelCase_ , """image_processor.json""" ) image_processor_first.to_json_file(UpperCAmelCase_ ) snake_case_ = self.image_processing_class.from_json_file(UpperCAmelCase_ ).to_dict() snake_case_ = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(UpperCAmelCase_ , image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->List[Any]: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: image_processor_first.save_pretrained(UpperCAmelCase_ ) snake_case_ = self.image_processing_class.from_pretrained(UpperCAmelCase_ ).to_dict() snake_case_ = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(UpperCAmelCase_ , image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] , UpperCAmelCase_ ) @unittest.skip("""ImageGPT requires clusters at initialization""" ) def lowerCAmelCase ( self : List[Any] ) ->Tuple: """simple docstring""" pass def _a ( ) -> str: snake_case_ = load_dataset("""hf-internal-testing/fixtures_image_utils""" , split="""test""" ) snake_case_ = Image.open(dataset[4]["""file"""] ) snake_case_ = Image.open(dataset[5]["""file"""] ) snake_case_ = [imagea, imagea] return images @require_vision @require_torch class __A (unittest.TestCase): '''simple docstring''' @slow def lowerCAmelCase ( self : Tuple ) ->List[str]: """simple docstring""" snake_case_ = ImageGPTImageProcessor.from_pretrained("""openai/imagegpt-small""" ) snake_case_ = prepare_images() # test non-batched snake_case_ = image_processing(images[0] , return_tensors="""pt""" ) self.assertIsInstance(encoding.input_ids , torch.LongTensor ) self.assertEqual(encoding.input_ids.shape , (1, 1_024) ) snake_case_ = [306, 191, 191] self.assertEqual(encoding.input_ids[0, :3].tolist() , UpperCAmelCase_ ) # test batched snake_case_ = image_processing(UpperCAmelCase_ , return_tensors="""pt""" ) self.assertIsInstance(encoding.input_ids , torch.LongTensor ) self.assertEqual(encoding.input_ids.shape , (2, 1_024) ) snake_case_ = [303, 13, 13] self.assertEqual(encoding.input_ids[1, -3:].tolist() , UpperCAmelCase_ )
2
0
import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging __SCREAMING_SNAKE_CASE : Optional[Any] = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Tuple = { 'xlnet-base-cased': 'https://huggingface.co/xlnet-base-cased/resolve/main/config.json', 'xlnet-large-cased': 'https://huggingface.co/xlnet-large-cased/resolve/main/config.json', } class __A (snake_case__): '''simple docstring''' __lowercase: int = """xlnet""" __lowercase: Optional[Any] = ["""mems"""] __lowercase: List[Any] = { """n_token""": """vocab_size""", # Backward compatibility """hidden_size""": """d_model""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self : int , UpperCAmelCase_ : Tuple=32_000 , UpperCAmelCase_ : str=1_024 , UpperCAmelCase_ : Union[str, Any]=24 , UpperCAmelCase_ : Dict=16 , UpperCAmelCase_ : int=4_096 , UpperCAmelCase_ : str="gelu" , UpperCAmelCase_ : int=True , UpperCAmelCase_ : List[Any]="bi" , UpperCAmelCase_ : Union[str, Any]=0.02 , UpperCAmelCase_ : str=1E-12 , UpperCAmelCase_ : int=0.1 , UpperCAmelCase_ : Tuple=512 , UpperCAmelCase_ : Any=None , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : Tuple=False , UpperCAmelCase_ : List[Any]=False , UpperCAmelCase_ : List[Any]=-1 , UpperCAmelCase_ : Union[str, Any]=False , UpperCAmelCase_ : Optional[Any]="last" , UpperCAmelCase_ : List[str]=True , UpperCAmelCase_ : Tuple="tanh" , UpperCAmelCase_ : Union[str, Any]=0.1 , UpperCAmelCase_ : Tuple=5 , UpperCAmelCase_ : Optional[int]=5 , UpperCAmelCase_ : Optional[int]=5 , UpperCAmelCase_ : Any=1 , UpperCAmelCase_ : Any=2 , **UpperCAmelCase_ : int , ) ->List[str]: """simple docstring""" snake_case_ = vocab_size snake_case_ = d_model snake_case_ = n_layer snake_case_ = n_head if d_model % n_head != 0: raise ValueError(F"""'d_model % n_head' ({d_model % n_head}) should be equal to 0""" ) if "d_head" in kwargs: if kwargs["d_head"] != d_model // n_head: raise ValueError( F"""`d_head` ({kwargs["d_head"]}) should be equal to `d_model // n_head` ({d_model // n_head})""" ) snake_case_ = d_model // n_head snake_case_ = ff_activation snake_case_ = d_inner snake_case_ = untie_r snake_case_ = attn_type snake_case_ = initializer_range snake_case_ = layer_norm_eps snake_case_ = dropout snake_case_ = mem_len snake_case_ = reuse_len snake_case_ = bi_data snake_case_ = clamp_len snake_case_ = same_length snake_case_ = summary_type snake_case_ = summary_use_proj snake_case_ = summary_activation snake_case_ = summary_last_dropout snake_case_ = start_n_top snake_case_ = end_n_top snake_case_ = bos_token_id snake_case_ = pad_token_id snake_case_ = eos_token_id if "use_cache" in kwargs: warnings.warn( """The `use_cache` argument is deprecated and will be removed in a future version, use `use_mems_eval`""" """ instead.""" , UpperCAmelCase_ , ) snake_case_ = kwargs["""use_cache"""] snake_case_ = use_mems_eval snake_case_ = use_mems_train super().__init__(pad_token_id=UpperCAmelCase_ , bos_token_id=UpperCAmelCase_ , eos_token_id=UpperCAmelCase_ , **UpperCAmelCase_ ) @property def lowerCAmelCase ( self : Union[str, Any] ) ->Union[str, Any]: """simple docstring""" logger.info(F"""The model {self.model_type} is one of the few models that has no sequence length limit.""" ) return -1 @max_position_embeddings.setter def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : str ) ->str: """simple docstring""" raise NotImplementedError( F"""The model {self.model_type} is one of the few models that has no sequence length limit.""" )
713
"""simple docstring""" import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, ) from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST class __A : '''simple docstring''' def __init__( self : Optional[int] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[Any]=13 , UpperCAmelCase_ : Optional[int]=7 , UpperCAmelCase_ : List[str]=True , UpperCAmelCase_ : int=True , UpperCAmelCase_ : List[Any]=True , UpperCAmelCase_ : Optional[int]=True , UpperCAmelCase_ : List[str]=99 , UpperCAmelCase_ : Dict=24 , UpperCAmelCase_ : List[str]=2 , UpperCAmelCase_ : Optional[Any]=6 , UpperCAmelCase_ : int=37 , UpperCAmelCase_ : Optional[Any]="gelu" , UpperCAmelCase_ : Optional[Any]=0.1 , UpperCAmelCase_ : List[Any]=0.1 , UpperCAmelCase_ : Any=512 , UpperCAmelCase_ : str=16 , UpperCAmelCase_ : List[str]=2 , UpperCAmelCase_ : Optional[int]=0.02 , UpperCAmelCase_ : Tuple=3 , UpperCAmelCase_ : Union[str, Any]=None , UpperCAmelCase_ : Any=1_000 , ) ->Tuple: """simple docstring""" snake_case_ = parent snake_case_ = batch_size snake_case_ = seq_length snake_case_ = is_training snake_case_ = use_input_mask snake_case_ = use_token_type_ids snake_case_ = use_labels snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = max_position_embeddings snake_case_ = type_vocab_size snake_case_ = type_sequence_label_size snake_case_ = initializer_range snake_case_ = num_labels snake_case_ = scope snake_case_ = range_bbox def lowerCAmelCase ( self : Tuple ) ->int: """simple docstring""" snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case_ = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox ) # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: snake_case_ = bbox[i, j, 3] snake_case_ = bbox[i, j, 1] snake_case_ = t if bbox[i, j, 2] < bbox[i, j, 0]: snake_case_ = bbox[i, j, 2] snake_case_ = bbox[i, j, 0] snake_case_ = t snake_case_ = None if self.use_input_mask: snake_case_ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) snake_case_ = None if self.use_token_type_ids: snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) snake_case_ = None snake_case_ = None if self.use_labels: snake_case_ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) snake_case_ = self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def lowerCAmelCase ( self : int ) ->Optional[int]: """simple docstring""" return LiltConfig( 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 , ) def lowerCAmelCase ( self : Any , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Any , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[int] , ) ->str: """simple docstring""" snake_case_ = LiltModel(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ , bbox=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ ) snake_case_ = model(UpperCAmelCase_ , bbox=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ ) snake_case_ = model(UpperCAmelCase_ , bbox=UpperCAmelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def lowerCAmelCase ( self : int , UpperCAmelCase_ : str , UpperCAmelCase_ : Any , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : str , UpperCAmelCase_ : List[Any] , ) ->Dict: """simple docstring""" snake_case_ = self.num_labels snake_case_ = LiltForTokenClassification(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model( UpperCAmelCase_ , bbox=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowerCAmelCase ( self : Any , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : str , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : int , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : List[str] , ) ->Dict: """simple docstring""" snake_case_ = LiltForQuestionAnswering(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model( UpperCAmelCase_ , bbox=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , start_positions=UpperCAmelCase_ , end_positions=UpperCAmelCase_ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def lowerCAmelCase ( self : int ) ->Optional[int]: """simple docstring""" snake_case_ = self.prepare_config_and_inputs() ( ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ) = config_and_inputs snake_case_ = { """input_ids""": input_ids, """bbox""": bbox, """token_type_ids""": token_type_ids, """attention_mask""": input_mask, } return config, inputs_dict @require_torch class __A (snake_case__ , snake_case__ , snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Optional[int] = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) __lowercase: Optional[Any] = ( { """feature-extraction""": LiltModel, """question-answering""": LiltForQuestionAnswering, """text-classification""": LiltForSequenceClassification, """token-classification""": LiltForTokenClassification, """zero-shot""": LiltForSequenceClassification, } if is_torch_available() else {} ) __lowercase: Union[str, Any] = False __lowercase: List[str] = False def lowerCAmelCase ( self : str , UpperCAmelCase_ : int , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[int] ) ->Optional[int]: """simple docstring""" return True def lowerCAmelCase ( self : Dict ) ->Union[str, Any]: """simple docstring""" snake_case_ = LiltModelTester(self ) snake_case_ = ConfigTester(self , config_class=UpperCAmelCase_ , hidden_size=37 ) def lowerCAmelCase ( self : str ) ->List[Any]: """simple docstring""" self.config_tester.run_common_tests() def lowerCAmelCase ( self : List[str] ) ->int: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] ) ->List[str]: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: snake_case_ = type self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def lowerCAmelCase ( self : List[Any] ) ->Dict: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->Dict: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*UpperCAmelCase_ ) @slow def lowerCAmelCase ( self : Union[str, Any] ) ->Optional[int]: """simple docstring""" for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ = LiltModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) @require_torch @slow class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : Optional[int] ) ->Dict: """simple docstring""" snake_case_ = LiltModel.from_pretrained("""SCUT-DLVCLab/lilt-roberta-en-base""" ).to(UpperCAmelCase_ ) snake_case_ = torch.tensor([[1, 2]] , device=UpperCAmelCase_ ) snake_case_ = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=UpperCAmelCase_ ) # forward pass with torch.no_grad(): snake_case_ = model(input_ids=UpperCAmelCase_ , bbox=UpperCAmelCase_ ) snake_case_ = torch.Size([1, 2, 768] ) snake_case_ = torch.tensor( [[-0.0_653, 0.0_950, -0.0_061], [-0.0_545, 0.0_926, -0.0_324]] , device=UpperCAmelCase_ , ) self.assertTrue(outputs.last_hidden_state.shape , UpperCAmelCase_ ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , UpperCAmelCase_ , atol=1E-3 ) )
2
0
"""simple docstring""" import math import numpy as np import qiskit from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute def _a ( _SCREAMING_SNAKE_CASE = 3 ) -> qiskit.result.counts.Counts: if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): raise TypeError("""number of qubits must be a integer.""" ) if number_of_qubits <= 0: raise ValueError("""number of qubits must be > 0.""" ) if math.floor(_SCREAMING_SNAKE_CASE ) != number_of_qubits: raise ValueError("""number of qubits must be exact integer.""" ) if number_of_qubits > 10: raise ValueError("""number of qubits too large to simulate(>10).""" ) snake_case_ = QuantumRegister(_SCREAMING_SNAKE_CASE , """qr""" ) snake_case_ = ClassicalRegister(_SCREAMING_SNAKE_CASE , """cr""" ) snake_case_ = QuantumCircuit(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = number_of_qubits for i in range(_SCREAMING_SNAKE_CASE ): quantum_circuit.h(number_of_qubits - i - 1 ) counter -= 1 for j in range(_SCREAMING_SNAKE_CASE ): quantum_circuit.cp(np.pi / 2 ** (counter - j) , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for k in range(number_of_qubits // 2 ): quantum_circuit.swap(_SCREAMING_SNAKE_CASE , number_of_qubits - k - 1 ) # measure all the qubits quantum_circuit.measure(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # simulate with 10000 shots snake_case_ = Aer.get_backend("""qasm_simulator""" ) snake_case_ = execute(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , shots=10_000 ) return job.result().get_counts(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": print( f"""Total count for quantum fourier transform state is: \ {quantum_fourier_transform(3)}""" )
714
"""simple docstring""" from __future__ import annotations def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> list[int]: snake_case_ = 0 snake_case_ = len(_SCREAMING_SNAKE_CASE ) - 1 while i < j: if nums[i] + nums[j] == target: return [i, j] elif nums[i] + nums[j] < target: snake_case_ = i + 1 else: snake_case_ = j - 1 return [] if __name__ == "__main__": import doctest doctest.testmod() print(f"""{two_pointer([2, 7, 11, 15], 9) = }""")
2
0
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE ) -> int: snake_case_ = len(_SCREAMING_SNAKE_CASE ) snake_case_ = len(matrix[0] ) snake_case_ = min(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for row in range(_SCREAMING_SNAKE_CASE ): # Check if diagonal element is not zero if matrix[row][row] != 0: # Eliminate all the elements below the diagonal for col in range(row + 1 , _SCREAMING_SNAKE_CASE ): snake_case_ = matrix[col][row] / matrix[row][row] for i in range(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): matrix[col][i] -= multiplier * matrix[row][i] else: # Find a non-zero diagonal element to swap rows snake_case_ = True for i in range(row + 1 , _SCREAMING_SNAKE_CASE ): if matrix[i][row] != 0: snake_case_ , snake_case_ = matrix[i], matrix[row] snake_case_ = False break if reduce: rank -= 1 for i in range(_SCREAMING_SNAKE_CASE ): snake_case_ = matrix[i][rank] # Reduce the row pointer by one to stay on the same row row -= 1 return rank if __name__ == "__main__": import doctest doctest.testmod()
715
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __SCREAMING_SNAKE_CASE : Optional[Any] = { 'configuration_biogpt': ['BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BioGptConfig'], 'tokenization_biogpt': ['BioGptTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : Optional[Any] = [ 'BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST', 'BioGptForCausalLM', 'BioGptForTokenClassification', 'BioGptForSequenceClassification', 'BioGptModel', 'BioGptPreTrainedModel', ] if TYPE_CHECKING: from .configuration_biogpt import BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, BioGptConfig from .tokenization_biogpt import BioGptTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_biogpt import ( BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptPreTrainedModel, ) else: import sys __SCREAMING_SNAKE_CASE : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
2
0
"""simple docstring""" import argparse from pathlib import Path from typing import Dict, OrderedDict, Tuple import torch from audiocraft.models import MusicGen from transformers import ( AutoFeatureExtractor, AutoTokenizer, EncodecModel, MusicgenDecoderConfig, MusicgenForConditionalGeneration, MusicgenProcessor, TaEncoderModel, ) from transformers.models.musicgen.modeling_musicgen import MusicgenForCausalLM from transformers.utils import logging logging.set_verbosity_info() __SCREAMING_SNAKE_CASE : Union[str, Any] = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : int = ['model.decoder.embed_positions.weights'] def _a ( _SCREAMING_SNAKE_CASE ) -> str: if "emb" in name: snake_case_ = name.replace("""emb""" , """model.decoder.embed_tokens""" ) if "transformer" in name: snake_case_ = name.replace("""transformer""" , """model.decoder""" ) if "cross_attention" in name: snake_case_ = name.replace("""cross_attention""" , """encoder_attn""" ) if "linear1" in name: snake_case_ = name.replace("""linear1""" , """fc1""" ) if "linear2" in name: snake_case_ = name.replace("""linear2""" , """fc2""" ) if "norm1" in name: snake_case_ = name.replace("""norm1""" , """self_attn_layer_norm""" ) if "norm_cross" in name: snake_case_ = name.replace("""norm_cross""" , """encoder_attn_layer_norm""" ) if "norm2" in name: snake_case_ = name.replace("""norm2""" , """final_layer_norm""" ) if "out_norm" in name: snake_case_ = name.replace("""out_norm""" , """model.decoder.layer_norm""" ) if "linears" in name: snake_case_ = name.replace("""linears""" , """lm_heads""" ) if "condition_provider.conditioners.description.output_proj" in name: snake_case_ = name.replace("""condition_provider.conditioners.description.output_proj""" , """enc_to_dec_proj""" ) return name def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple[Dict, Dict]: snake_case_ = list(state_dict.keys() ) snake_case_ = {} for key in keys: snake_case_ = state_dict.pop(_SCREAMING_SNAKE_CASE ) snake_case_ = rename_keys(_SCREAMING_SNAKE_CASE ) if "in_proj_weight" in key: # split fused qkv proj snake_case_ = val[:hidden_size, :] snake_case_ = val[hidden_size : 2 * hidden_size, :] snake_case_ = val[-hidden_size:, :] elif "enc_to_dec_proj" in key: snake_case_ = val else: snake_case_ = val return state_dict, enc_dec_proj_state_dict def _a ( _SCREAMING_SNAKE_CASE ) -> MusicgenDecoderConfig: if checkpoint == "small": # default config values snake_case_ = 1_024 snake_case_ = 24 snake_case_ = 16 elif checkpoint == "medium": snake_case_ = 1_536 snake_case_ = 48 snake_case_ = 24 elif checkpoint == "large": snake_case_ = 2_048 snake_case_ = 48 snake_case_ = 32 else: raise ValueError(f"""Checkpoint should be one of `['small', 'medium', 'large']`, got {checkpoint}.""" ) snake_case_ = MusicgenDecoderConfig( hidden_size=_SCREAMING_SNAKE_CASE , ffn_dim=hidden_size * 4 , num_hidden_layers=_SCREAMING_SNAKE_CASE , num_attention_heads=_SCREAMING_SNAKE_CASE , ) return config @torch.no_grad() def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE="cpu" ) -> Tuple: snake_case_ = MusicGen.get_pretrained(_SCREAMING_SNAKE_CASE , device=_SCREAMING_SNAKE_CASE ) snake_case_ = decoder_config_from_checkpoint(_SCREAMING_SNAKE_CASE ) snake_case_ = fairseq_model.lm.state_dict() snake_case_ , snake_case_ = rename_state_dict( _SCREAMING_SNAKE_CASE , hidden_size=decoder_config.hidden_size ) snake_case_ = TaEncoderModel.from_pretrained("""t5-base""" ) snake_case_ = EncodecModel.from_pretrained("""facebook/encodec_32khz""" ) snake_case_ = MusicgenForCausalLM(_SCREAMING_SNAKE_CASE ).eval() # load all decoder weights - expect that we'll be missing embeddings and enc-dec projection snake_case_ , snake_case_ = decoder.load_state_dict(_SCREAMING_SNAKE_CASE , strict=_SCREAMING_SNAKE_CASE ) for key in missing_keys.copy(): if key.startswith(("""text_encoder""", """audio_encoder""") ) or key in EXPECTED_MISSING_KEYS: missing_keys.remove(_SCREAMING_SNAKE_CASE ) if len(_SCREAMING_SNAKE_CASE ) > 0: raise ValueError(f"""Missing key(s) in state_dict: {missing_keys}""" ) if len(_SCREAMING_SNAKE_CASE ) > 0: raise ValueError(f"""Unexpected key(s) in state_dict: {unexpected_keys}""" ) # init the composite model snake_case_ = MusicgenForConditionalGeneration(text_encoder=_SCREAMING_SNAKE_CASE , audio_encoder=_SCREAMING_SNAKE_CASE , decoder=_SCREAMING_SNAKE_CASE ) # load the pre-trained enc-dec projection (from the decoder state dict) model.enc_to_dec_proj.load_state_dict(_SCREAMING_SNAKE_CASE ) # check we can do a forward pass snake_case_ = torch.arange(0 , 8 , dtype=torch.long ).reshape(2 , -1 ) snake_case_ = input_ids.reshape(2 * 4 , -1 ) with torch.no_grad(): snake_case_ = model(input_ids=_SCREAMING_SNAKE_CASE , decoder_input_ids=_SCREAMING_SNAKE_CASE ).logits if logits.shape != (8, 1, 2_048): raise ValueError("""Incorrect shape for logits""" ) # now construct the processor snake_case_ = AutoTokenizer.from_pretrained("""t5-base""" ) snake_case_ = AutoFeatureExtractor.from_pretrained("""facebook/encodec_32khz""" , padding_side="""left""" ) snake_case_ = MusicgenProcessor(feature_extractor=_SCREAMING_SNAKE_CASE , tokenizer=_SCREAMING_SNAKE_CASE ) # set the appropriate bos/pad token ids snake_case_ = 2_048 snake_case_ = 2_048 # set other default generation config params snake_case_ = int(30 * audio_encoder.config.frame_rate ) snake_case_ = True snake_case_ = 3.0 if pytorch_dump_folder is not None: Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) logger.info(f"""Saving model {checkpoint} to {pytorch_dump_folder}""" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) processor.save_pretrained(_SCREAMING_SNAKE_CASE ) if repo_id: logger.info(f"""Pushing model {checkpoint} to {repo_id}""" ) model.push_to_hub(_SCREAMING_SNAKE_CASE ) processor.push_to_hub(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( '--checkpoint', default='small', type=str, help='Checkpoint size of the MusicGen model you\'d like to convert. Can be one of: `[\'small\', \'medium\', \'large\']`.', ) parser.add_argument( '--pytorch_dump_folder', required=True, default=None, type=str, help='Path to the output PyTorch model directory.', ) parser.add_argument( '--push_to_hub', default=None, type=str, help='Where to upload the converted model on the 🤗 hub.' ) parser.add_argument( '--device', default='cpu', type=str, help='Torch device to run the conversion, either cpu or cuda.' ) __SCREAMING_SNAKE_CASE : int = parser.parse_args() convert_musicgen_checkpoint(args.checkpoint, args.pytorch_dump_folder, args.push_to_hub)
716
"""simple docstring""" __SCREAMING_SNAKE_CASE : str = 'Input must be a string of 8 numbers plus letter' __SCREAMING_SNAKE_CASE : Dict = 'TRWAGMYFPDXBNJZSQVHLCKE' def _a ( _SCREAMING_SNAKE_CASE ) -> bool: if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): snake_case_ = f"""Expected string as input, found {type(_SCREAMING_SNAKE_CASE ).__name__}""" raise TypeError(_SCREAMING_SNAKE_CASE ) snake_case_ = spanish_id.replace("""-""" , """""" ).upper() if len(_SCREAMING_SNAKE_CASE ) != 9: raise ValueError(_SCREAMING_SNAKE_CASE ) try: snake_case_ = int(spanish_id_clean[0:8] ) snake_case_ = spanish_id_clean[8] except ValueError as ex: raise ValueError(_SCREAMING_SNAKE_CASE ) from ex if letter.isdigit(): raise ValueError(_SCREAMING_SNAKE_CASE ) return letter == LOOKUP_LETTERS[number % 23] if __name__ == "__main__": import doctest doctest.testmod()
2
0
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class __A (unittest.TestCase): '''simple docstring''' def __init__( self : Any , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Any=7 , UpperCAmelCase_ : int=3 , UpperCAmelCase_ : List[Any]=18 , UpperCAmelCase_ : str=30 , UpperCAmelCase_ : Tuple=400 , UpperCAmelCase_ : Optional[Any]=True , UpperCAmelCase_ : str=None , UpperCAmelCase_ : str=True , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : int=True , ) ->List[str]: """simple docstring""" snake_case_ = size if size is not None else {"""shortest_edge""": 20} snake_case_ = crop_size if crop_size is not None else {"""height""": 18, """width""": 18} snake_case_ = parent snake_case_ = batch_size snake_case_ = num_channels snake_case_ = image_size snake_case_ = min_resolution snake_case_ = max_resolution snake_case_ = do_resize snake_case_ = size snake_case_ = do_center_crop snake_case_ = crop_size snake_case_ = do_flip_channel_order def lowerCAmelCase ( self : Any ) ->List[str]: """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_flip_channel_order": self.do_flip_channel_order, } @require_torch @require_vision class __A (snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Tuple = MobileViTImageProcessor if is_vision_available() else None def lowerCAmelCase ( self : int ) ->Dict: """simple docstring""" snake_case_ = MobileViTImageProcessingTester(self ) @property def lowerCAmelCase ( self : str ) ->Optional[Any]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def lowerCAmelCase ( self : int ) ->Union[str, Any]: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(UpperCAmelCase_ , """do_resize""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """size""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """do_center_crop""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """center_crop""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """do_flip_channel_order""" ) ) def lowerCAmelCase ( self : Any ) ->int: """simple docstring""" snake_case_ = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""shortest_edge""": 20} ) self.assertEqual(image_processor.crop_size , {"""height""": 18, """width""": 18} ) snake_case_ = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {"""shortest_edge""": 42} ) self.assertEqual(image_processor.crop_size , {"""height""": 84, """width""": 84} ) def lowerCAmelCase ( self : Union[str, Any] ) ->Dict: """simple docstring""" pass def lowerCAmelCase ( self : Union[str, Any] ) ->Optional[int]: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) # create random PIL images snake_case_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase_ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase_ , Image.Image ) # Test not batched input snake_case_ = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched snake_case_ = image_processing(UpperCAmelCase_ , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) def lowerCAmelCase ( self : Tuple ) ->int: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors snake_case_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase_ , numpify=UpperCAmelCase_ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase_ , np.ndarray ) # Test not batched input snake_case_ = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched snake_case_ = image_processing(UpperCAmelCase_ , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) def lowerCAmelCase ( self : str ) ->str: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors snake_case_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase_ , torchify=UpperCAmelCase_ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase_ , torch.Tensor ) # Test not batched input snake_case_ = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched snake_case_ = image_processing(UpperCAmelCase_ , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , )
717
"""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 logging __SCREAMING_SNAKE_CASE : List[str] = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Optional[int] = {'vocab_file': 'spiece.model'} __SCREAMING_SNAKE_CASE : List[str] = { 'vocab_file': { 'albert-base-v1': 'https://huggingface.co/albert-base-v1/resolve/main/spiece.model', 'albert-large-v1': 'https://huggingface.co/albert-large-v1/resolve/main/spiece.model', 'albert-xlarge-v1': 'https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model', 'albert-xxlarge-v1': 'https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model', 'albert-base-v2': 'https://huggingface.co/albert-base-v2/resolve/main/spiece.model', 'albert-large-v2': 'https://huggingface.co/albert-large-v2/resolve/main/spiece.model', 'albert-xlarge-v2': 'https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model', 'albert-xxlarge-v2': 'https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model', } } __SCREAMING_SNAKE_CASE : List[str] = { 'albert-base-v1': 512, 'albert-large-v1': 512, 'albert-xlarge-v1': 512, 'albert-xxlarge-v1': 512, 'albert-base-v2': 512, 'albert-large-v2': 512, 'albert-xlarge-v2': 512, 'albert-xxlarge-v2': 512, } __SCREAMING_SNAKE_CASE : int = '▁' class __A (snake_case__): '''simple docstring''' __lowercase: Optional[Any] = VOCAB_FILES_NAMES __lowercase: Optional[int] = PRETRAINED_VOCAB_FILES_MAP __lowercase: Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : int , UpperCAmelCase_ : Any , UpperCAmelCase_ : Dict=True , UpperCAmelCase_ : Dict=True , UpperCAmelCase_ : List[str]=False , UpperCAmelCase_ : List[Any]="[CLS]" , UpperCAmelCase_ : Any="[SEP]" , UpperCAmelCase_ : str="<unk>" , UpperCAmelCase_ : str="[SEP]" , UpperCAmelCase_ : Optional[Any]="<pad>" , UpperCAmelCase_ : Optional[int]="[CLS]" , UpperCAmelCase_ : int="[MASK]" , UpperCAmelCase_ : Optional[Dict[str, Any]] = None , **UpperCAmelCase_ : Union[str, Any] , ) ->None: """simple docstring""" snake_case_ = ( AddedToken(UpperCAmelCase_ , lstrip=UpperCAmelCase_ , rstrip=UpperCAmelCase_ , normalized=UpperCAmelCase_ ) if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) else mask_token ) snake_case_ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=UpperCAmelCase_ , remove_space=UpperCAmelCase_ , keep_accents=UpperCAmelCase_ , bos_token=UpperCAmelCase_ , eos_token=UpperCAmelCase_ , unk_token=UpperCAmelCase_ , sep_token=UpperCAmelCase_ , pad_token=UpperCAmelCase_ , cls_token=UpperCAmelCase_ , mask_token=UpperCAmelCase_ , sp_model_kwargs=self.sp_model_kwargs , **UpperCAmelCase_ , ) snake_case_ = do_lower_case snake_case_ = remove_space snake_case_ = keep_accents snake_case_ = vocab_file snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(UpperCAmelCase_ ) @property def lowerCAmelCase ( self : List[Any] ) ->Dict: """simple docstring""" return len(self.sp_model ) def lowerCAmelCase ( self : str ) ->List[Any]: """simple docstring""" snake_case_ = {self.convert_ids_to_tokens(UpperCAmelCase_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Dict ) ->List[str]: """simple docstring""" snake_case_ = self.__dict__.copy() snake_case_ = None return state def __setstate__( self : Tuple , UpperCAmelCase_ : Optional[int] ) ->Optional[int]: """simple docstring""" snake_case_ = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): snake_case_ = {} snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : Any ) ->str: """simple docstring""" if self.remove_space: snake_case_ = """ """.join(inputs.strip().split() ) else: snake_case_ = inputs snake_case_ = outputs.replace("""``""" , """\"""" ).replace("""''""" , """\"""" ) if not self.keep_accents: snake_case_ = unicodedata.normalize("""NFKD""" , UpperCAmelCase_ ) snake_case_ = """""".join([c for c in outputs if not unicodedata.combining(UpperCAmelCase_ )] ) if self.do_lower_case: snake_case_ = outputs.lower() return outputs def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : str ) ->List[str]: """simple docstring""" snake_case_ = self.preprocess_text(UpperCAmelCase_ ) snake_case_ = self.sp_model.encode(UpperCAmelCase_ , out_type=UpperCAmelCase_ ) snake_case_ = [] for piece in pieces: if len(UpperCAmelCase_ ) > 1 and piece[-1] == str(""",""" ) and piece[-2].isdigit(): snake_case_ = self.sp_model.EncodeAsPieces(piece[:-1].replace(UpperCAmelCase_ , """""" ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: snake_case_ = cur_pieces[1:] else: snake_case_ = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(UpperCAmelCase_ ) else: new_pieces.append(UpperCAmelCase_ ) return new_pieces def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : Optional[int] ) ->Dict: """simple docstring""" return self.sp_model.PieceToId(UpperCAmelCase_ ) def lowerCAmelCase ( self : str , UpperCAmelCase_ : Union[str, Any] ) ->Optional[int]: """simple docstring""" return self.sp_model.IdToPiece(UpperCAmelCase_ ) def lowerCAmelCase ( self : str , UpperCAmelCase_ : Dict ) ->Any: """simple docstring""" snake_case_ = [] snake_case_ = """""" snake_case_ = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(UpperCAmelCase_ ) + token snake_case_ = True snake_case_ = [] else: current_sub_tokens.append(UpperCAmelCase_ ) snake_case_ = False out_string += self.sp_model.decode(UpperCAmelCase_ ) return out_string.strip() def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ) ->List[int]: """simple docstring""" snake_case_ = [self.sep_token_id] snake_case_ = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None , UpperCAmelCase_ : bool = False ) ->List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=UpperCAmelCase_ , token_ids_a=UpperCAmelCase_ , already_has_special_tokens=UpperCAmelCase_ ) if token_ids_a is not None: return [1] + ([0] * len(UpperCAmelCase_ )) + [1] + ([0] * len(UpperCAmelCase_ )) + [1] return [1] + ([0] * len(UpperCAmelCase_ )) + [1] def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ) ->List[int]: """simple docstring""" snake_case_ = [self.sep_token_id] snake_case_ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def lowerCAmelCase ( self : str , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None ) ->Tuple[str]: """simple docstring""" if not os.path.isdir(UpperCAmelCase_ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return snake_case_ = os.path.join( UpperCAmelCase_ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCAmelCase_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , UpperCAmelCase_ ) elif not os.path.isfile(self.vocab_file ): with open(UpperCAmelCase_ , """wb""" ) as fi: snake_case_ = self.sp_model.serialized_model_proto() fi.write(UpperCAmelCase_ ) return (out_vocab_file,)
2
0
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging __SCREAMING_SNAKE_CASE : Optional[int] = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Union[str, Any] = '▁' __SCREAMING_SNAKE_CASE : int = {'vocab_file': 'sentencepiece.bpe.model', 'monolingual_vocab_file': 'dict.txt'} __SCREAMING_SNAKE_CASE : Any = { 'vocab_file': { 'vinai/bartpho-syllable': 'https://huggingface.co/vinai/bartpho-syllable/resolve/main/sentencepiece.bpe.model', }, 'monolingual_vocab_file': { 'vinai/bartpho-syllable': 'https://huggingface.co/vinai/bartpho-syllable/resolve/main/dict.txt', }, } __SCREAMING_SNAKE_CASE : Any = {'vinai/bartpho-syllable': 1_024} class __A (snake_case__): '''simple docstring''' __lowercase: Dict = VOCAB_FILES_NAMES __lowercase: str = PRETRAINED_VOCAB_FILES_MAP __lowercase: Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowercase: Tuple = ["""input_ids""", """attention_mask"""] def __init__( self : Dict , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : str="<s>" , UpperCAmelCase_ : str="</s>" , UpperCAmelCase_ : Dict="</s>" , UpperCAmelCase_ : int="<s>" , UpperCAmelCase_ : Tuple="<unk>" , UpperCAmelCase_ : Union[str, Any]="<pad>" , UpperCAmelCase_ : Optional[int]="<mask>" , UpperCAmelCase_ : Optional[Dict[str, Any]] = None , **UpperCAmelCase_ : List[Any] , ) ->None: """simple docstring""" snake_case_ = AddedToken(UpperCAmelCase_ , lstrip=UpperCAmelCase_ , rstrip=UpperCAmelCase_ ) if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) else mask_token snake_case_ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=UpperCAmelCase_ , eos_token=UpperCAmelCase_ , unk_token=UpperCAmelCase_ , sep_token=UpperCAmelCase_ , cls_token=UpperCAmelCase_ , pad_token=UpperCAmelCase_ , mask_token=UpperCAmelCase_ , sp_model_kwargs=self.sp_model_kwargs , **UpperCAmelCase_ , ) snake_case_ = vocab_file snake_case_ = monolingual_vocab_file snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(UpperCAmelCase_ ) ) # Load the reduced vocab # Keep order of special tokens for backward compatibility snake_case_ = {} snake_case_ = 0 for token in [bos_token, pad_token, eos_token, unk_token, sep_token, cls_token]: if str(UpperCAmelCase_ ) not in self.fairseq_tokens_to_ids: snake_case_ = cnt cnt += 1 with open(UpperCAmelCase_ , """r""" , encoding="""utf-8""" ) as f: for line in f.readlines(): snake_case_ = line.strip().split()[0] snake_case_ = len(self.fairseq_tokens_to_ids ) if str(UpperCAmelCase_ ) not in self.fairseq_tokens_to_ids: snake_case_ = len(self.fairseq_tokens_to_ids ) snake_case_ = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self : List[Any] ) ->List[str]: """simple docstring""" snake_case_ = self.__dict__.copy() snake_case_ = None snake_case_ = self.sp_model.serialized_model_proto() return state def __setstate__( self : int , UpperCAmelCase_ : List[Any] ) ->Dict: """simple docstring""" snake_case_ = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): snake_case_ = {} snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ) ->List[int]: """simple docstring""" if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] snake_case_ = [self.cls_token_id] snake_case_ = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def lowerCAmelCase ( self : Optional[Any] , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None , UpperCAmelCase_ : bool = False ) ->List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=UpperCAmelCase_ , token_ids_a=UpperCAmelCase_ , already_has_special_tokens=UpperCAmelCase_ ) if token_ids_a is None: return [1] + ([0] * len(UpperCAmelCase_ )) + [1] return [1] + ([0] * len(UpperCAmelCase_ )) + [1, 1] + ([0] * len(UpperCAmelCase_ )) + [1] def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ) ->List[int]: """simple docstring""" snake_case_ = [self.sep_token_id] snake_case_ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def lowerCAmelCase ( self : Dict ) ->Tuple: """simple docstring""" return len(self.fairseq_ids_to_tokens ) def lowerCAmelCase ( self : Tuple ) ->Tuple: """simple docstring""" snake_case_ = {self.convert_ids_to_tokens(UpperCAmelCase_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def lowerCAmelCase ( self : Optional[Any] , UpperCAmelCase_ : str ) ->List[str]: """simple docstring""" return self.sp_model.encode(UpperCAmelCase_ , out_type=UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : Optional[int] ) ->Optional[int]: """simple docstring""" if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] else: return self.unk_token_id def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : Optional[Any] ) ->Any: """simple docstring""" return self.fairseq_ids_to_tokens[index] def lowerCAmelCase ( self : str , UpperCAmelCase_ : List[Any] ) ->List[str]: """simple docstring""" snake_case_ = """""".join(UpperCAmelCase_ ).replace(UpperCAmelCase_ , """ """ ).strip() return out_string def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None ) ->Tuple[str]: """simple docstring""" if not os.path.isdir(UpperCAmelCase_ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return snake_case_ = os.path.join( UpperCAmelCase_ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) snake_case_ = os.path.join( UpperCAmelCase_ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""monolingual_vocab_file"""] , ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCAmelCase_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , UpperCAmelCase_ ) elif not os.path.isfile(self.vocab_file ): with open(UpperCAmelCase_ , """wb""" ) as fi: snake_case_ = self.sp_model.serialized_model_proto() fi.write(UpperCAmelCase_ ) if os.path.abspath(self.monolingual_vocab_file ) != os.path.abspath( UpperCAmelCase_ ) and os.path.isfile(self.monolingual_vocab_file ): copyfile(self.monolingual_vocab_file , UpperCAmelCase_ ) elif not os.path.isfile(self.monolingual_vocab_file ): with open(UpperCAmelCase_ , """w""" , encoding="""utf-8""" ) as fp: for token in self.fairseq_tokens_to_ids: if token not in self.all_special_tokens: fp.write(F"""{str(UpperCAmelCase_ )} \n""" ) return out_vocab_file, out_monolingual_vocab_file
718
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE ) -> list: # bit count represents no. of bits in the gray code if bit_count < 0: raise ValueError("""The given input must be positive""" ) # get the generated string sequence snake_case_ = gray_code_sequence_string(_SCREAMING_SNAKE_CASE ) # # convert them to integers for i in range(len(_SCREAMING_SNAKE_CASE ) ): snake_case_ = int(sequence[i] , 2 ) return sequence def _a ( _SCREAMING_SNAKE_CASE ) -> list: # The approach is a recursive one # Base case achieved when either n = 0 or n=1 if bit_count == 0: return ["0"] if bit_count == 1: return ["0", "1"] snake_case_ = 1 << bit_count # defines the length of the sequence # 1<< n is equivalent to 2^n # recursive answer will generate answer for n-1 bits snake_case_ = gray_code_sequence_string(bit_count - 1 ) snake_case_ = [] # append 0 to first half of the smaller sequence generated for i in range(seq_len // 2 ): snake_case_ = """0""" + smaller_sequence[i] sequence.append(_SCREAMING_SNAKE_CASE ) # append 1 to second half ... start from the end of the list for i in reversed(range(seq_len // 2 ) ): snake_case_ = """1""" + smaller_sequence[i] sequence.append(_SCREAMING_SNAKE_CASE ) return sequence if __name__ == "__main__": import doctest doctest.testmod()
2
0
import logging import os from dataclasses import dataclass, field from typing import Dict, Optional import datasets import numpy as np import tensorflow as tf from transformers import ( AutoConfig, AutoTokenizer, EvalPrediction, HfArgumentParser, PreTrainedTokenizer, TFAutoModelForSequenceClassification, TFTrainer, TFTrainingArguments, ) from transformers.utils import logging as hf_logging hf_logging.set_verbosity_info() hf_logging.enable_default_handler() hf_logging.enable_explicit_format() def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , ) -> Union[str, Any]: snake_case_ = {} if train_file is not None: snake_case_ = [train_file] if eval_file is not None: snake_case_ = [eval_file] if test_file is not None: snake_case_ = [test_file] snake_case_ = datasets.load_dataset("""csv""" , data_files=_SCREAMING_SNAKE_CASE ) snake_case_ = list(ds[list(files.keys() )[0]].features.keys() ) snake_case_ = features_name.pop(_SCREAMING_SNAKE_CASE ) snake_case_ = list(set(ds[list(files.keys() )[0]][label_name] ) ) snake_case_ = {label: i for i, label in enumerate(_SCREAMING_SNAKE_CASE )} snake_case_ = tokenizer.model_input_names snake_case_ = {} if len(_SCREAMING_SNAKE_CASE ) == 1: for k in files.keys(): snake_case_ = ds[k].map( lambda _SCREAMING_SNAKE_CASE : tokenizer.batch_encode_plus( example[features_name[0]] , truncation=_SCREAMING_SNAKE_CASE , max_length=_SCREAMING_SNAKE_CASE , padding="""max_length""" ) , batched=_SCREAMING_SNAKE_CASE , ) elif len(_SCREAMING_SNAKE_CASE ) == 2: for k in files.keys(): snake_case_ = ds[k].map( lambda _SCREAMING_SNAKE_CASE : tokenizer.batch_encode_plus( (example[features_name[0]], example[features_name[1]]) , truncation=_SCREAMING_SNAKE_CASE , max_length=_SCREAMING_SNAKE_CASE , padding="""max_length""" , ) , batched=_SCREAMING_SNAKE_CASE , ) def gen_train(): for ex in transformed_ds[datasets.Split.TRAIN]: snake_case_ = {k: v for k, v in ex.items() if k in input_names} snake_case_ = labelaid[ex[label_name]] yield (d, label) def gen_val(): for ex in transformed_ds[datasets.Split.VALIDATION]: snake_case_ = {k: v for k, v in ex.items() if k in input_names} snake_case_ = labelaid[ex[label_name]] yield (d, label) def gen_test(): for ex in transformed_ds[datasets.Split.TEST]: snake_case_ = {k: v for k, v in ex.items() if k in input_names} snake_case_ = labelaid[ex[label_name]] yield (d, label) snake_case_ = ( tf.data.Dataset.from_generator( _SCREAMING_SNAKE_CASE , ({k: tf.intaa for k in input_names}, tf.intaa) , ({k: tf.TensorShape([None] ) for k in input_names}, tf.TensorShape([] )) , ) if datasets.Split.TRAIN in transformed_ds else None ) if train_ds is not None: snake_case_ = train_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.TRAIN] ) ) ) snake_case_ = ( tf.data.Dataset.from_generator( _SCREAMING_SNAKE_CASE , ({k: tf.intaa for k in input_names}, tf.intaa) , ({k: tf.TensorShape([None] ) for k in input_names}, tf.TensorShape([] )) , ) if datasets.Split.VALIDATION in transformed_ds else None ) if val_ds is not None: snake_case_ = val_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.VALIDATION] ) ) ) snake_case_ = ( tf.data.Dataset.from_generator( _SCREAMING_SNAKE_CASE , ({k: tf.intaa for k in input_names}, tf.intaa) , ({k: tf.TensorShape([None] ) for k in input_names}, tf.TensorShape([] )) , ) if datasets.Split.TEST in transformed_ds else None ) if test_ds is not None: snake_case_ = test_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.TEST] ) ) ) return train_ds, val_ds, test_ds, labelaid __SCREAMING_SNAKE_CASE : Optional[Any] = logging.getLogger(__name__) @dataclass class __A : '''simple docstring''' __lowercase: int = field(metadata={"""help""": """Which column contains the label"""}) __lowercase: str = field(default=snake_case__ , metadata={"""help""": """The path of the training file"""}) __lowercase: Optional[str] = field(default=snake_case__ , metadata={"""help""": """The path of the development file"""}) __lowercase: Optional[str] = field(default=snake_case__ , metadata={"""help""": """The path of the test file"""}) __lowercase: int = field( default=1_28 , metadata={ """help""": ( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) __lowercase: bool = field( default=snake_case__ , metadata={"""help""": """Overwrite the cached training and evaluation sets"""}) @dataclass class __A : '''simple docstring''' __lowercase: str = field( metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""}) __lowercase: Optional[str] = field( default=snake_case__ , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""}) __lowercase: Optional[str] = field( default=snake_case__ , metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""}) __lowercase: bool = field(default=snake_case__ , metadata={"""help""": """Set this flag to use fast tokenization."""}) # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script, # or just modify its tokenizer_config.json. __lowercase: Optional[str] = field( default=snake_case__ , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} , ) def _a ( ) -> Union[str, Any]: # 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. snake_case_ = HfArgumentParser((ModelArguments, DataTrainingArguments, TFTrainingArguments) ) snake_case_ , snake_case_ , snake_case_ = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( f"""Output directory ({training_args.output_dir}) already exists and is not empty. Use""" """ --overwrite_output_dir to overcome.""" ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , level=logging.INFO , ) logger.info( f"""n_replicas: {training_args.n_replicas}, distributed training: {bool(training_args.n_replicas > 1 )}, """ f"""16-bits training: {training_args.fpaa}""" ) logger.info(f"""Training/evaluation parameters {training_args}""" ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. snake_case_ = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) snake_case_ , snake_case_ , snake_case_ , snake_case_ = get_tfds( train_file=data_args.train_file , eval_file=data_args.dev_file , test_file=data_args.test_file , tokenizer=_SCREAMING_SNAKE_CASE , label_column_id=data_args.label_column_id , max_seq_length=data_args.max_seq_length , ) snake_case_ = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=len(_SCREAMING_SNAKE_CASE ) , labelaid=_SCREAMING_SNAKE_CASE , idalabel={id: label for label, id in labelaid.items()} , finetuning_task="""text-classification""" , cache_dir=model_args.cache_dir , ) with training_args.strategy.scope(): snake_case_ = TFAutoModelForSequenceClassification.from_pretrained( model_args.model_name_or_path , from_pt=bool(""".bin""" in model_args.model_name_or_path ) , config=_SCREAMING_SNAKE_CASE , cache_dir=model_args.cache_dir , ) def compute_metrics(_SCREAMING_SNAKE_CASE ) -> Dict: snake_case_ = np.argmax(p.predictions , axis=1 ) return {"acc": (preds == p.label_ids).mean()} # Initialize our Trainer snake_case_ = TFTrainer( model=_SCREAMING_SNAKE_CASE , args=_SCREAMING_SNAKE_CASE , train_dataset=_SCREAMING_SNAKE_CASE , eval_dataset=_SCREAMING_SNAKE_CASE , compute_metrics=_SCREAMING_SNAKE_CASE , ) # Training if training_args.do_train: trainer.train() trainer.save_model() tokenizer.save_pretrained(training_args.output_dir ) # Evaluation snake_case_ = {} if training_args.do_eval: logger.info("""*** Evaluate ***""" ) snake_case_ = trainer.evaluate() snake_case_ = os.path.join(training_args.output_dir , """eval_results.txt""" ) with open(_SCREAMING_SNAKE_CASE , """w""" ) as writer: logger.info("""***** Eval results *****""" ) for key, value in result.items(): logger.info(f""" {key} = {value}""" ) writer.write(f"""{key} = {value}\n""" ) results.update(_SCREAMING_SNAKE_CASE ) return results if __name__ == "__main__": main()
719
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __SCREAMING_SNAKE_CASE : Optional[Any] = { 'configuration_megatron_bert': ['MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MegatronBertConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : Tuple = [ 'MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'MegatronBertForCausalLM', 'MegatronBertForMaskedLM', 'MegatronBertForMultipleChoice', 'MegatronBertForNextSentencePrediction', 'MegatronBertForPreTraining', 'MegatronBertForQuestionAnswering', 'MegatronBertForSequenceClassification', 'MegatronBertForTokenClassification', 'MegatronBertModel', 'MegatronBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_megatron_bert import MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MegatronBertConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_megatron_bert import ( MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, MegatronBertPreTrainedModel, ) else: import sys __SCREAMING_SNAKE_CASE : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
2
0
"""simple docstring""" from typing import List, Optional, Union import numpy as np import PIL import torch from PIL import Image from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) __SCREAMING_SNAKE_CASE : Any = logging.get_logger(__name__) # pylint: disable=invalid-name __SCREAMING_SNAKE_CASE : str = '\n Examples:\n ```py\n >>> from diffusers import KandinskyV22Img2ImgPipeline, KandinskyV22PriorPipeline\n >>> from diffusers.utils import load_image\n >>> import torch\n\n >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\n ... "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16\n ... )\n >>> pipe_prior.to("cuda")\n\n >>> prompt = "A red cartoon frog, 4k"\n >>> image_emb, zero_image_emb = pipe_prior(prompt, return_dict=False)\n\n >>> pipe = KandinskyV22Img2ImgPipeline.from_pretrained(\n ... "kandinsky-community/kandinsky-2-2-decoder", torch_dtype=torch.float16\n ... )\n >>> pipe.to("cuda")\n\n >>> init_image = load_image(\n ... "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"\n ... "/kandinsky/frog.png"\n ... )\n\n >>> image = pipe(\n ... image=init_image,\n ... image_embeds=image_emb,\n ... negative_image_embeds=zero_image_emb,\n ... height=768,\n ... width=768,\n ... num_inference_steps=100,\n ... strength=0.2,\n ... ).images\n\n >>> image[0].save("red_frog.png")\n ```\n' def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=8 ) -> List[str]: snake_case_ = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 snake_case_ = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=512 , _SCREAMING_SNAKE_CASE=512 ) -> List[Any]: snake_case_ = pil_image.resize((w, h) , resample=Image.BICUBIC , reducing_gap=1 ) snake_case_ = np.array(pil_image.convert("""RGB""" ) ) snake_case_ = arr.astype(np.floataa ) / 127.5 - 1 snake_case_ = np.transpose(_SCREAMING_SNAKE_CASE , [2, 0, 1] ) snake_case_ = torch.from_numpy(_SCREAMING_SNAKE_CASE ).unsqueeze(0 ) return image class __A (snake_case__): '''simple docstring''' def __init__( self : Tuple , UpperCAmelCase_ : UNetaDConditionModel , UpperCAmelCase_ : DDPMScheduler , UpperCAmelCase_ : VQModel , ) ->Tuple: """simple docstring""" super().__init__() self.register_modules( unet=UpperCAmelCase_ , scheduler=UpperCAmelCase_ , movq=UpperCAmelCase_ , ) snake_case_ = 2 ** (len(self.movq.config.block_out_channels ) - 1) def lowerCAmelCase ( self : int , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Dict ) ->Optional[int]: """simple docstring""" snake_case_ = min(int(num_inference_steps * strength ) , UpperCAmelCase_ ) snake_case_ = max(num_inference_steps - init_timestep , 0 ) snake_case_ = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : int , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : Any=None ) ->Optional[Any]: """simple docstring""" if not isinstance(UpperCAmelCase_ , (torch.Tensor, PIL.Image.Image, list) ): raise ValueError( F"""`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(UpperCAmelCase_ )}""" ) snake_case_ = image.to(device=UpperCAmelCase_ , dtype=UpperCAmelCase_ ) snake_case_ = batch_size * num_images_per_prompt if image.shape[1] == 4: snake_case_ = image else: if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) and len(UpperCAmelCase_ ) != batch_size: raise ValueError( F"""You have passed a list of generators of length {len(UpperCAmelCase_ )}, but requested an effective batch""" F""" size of {batch_size}. Make sure the batch size matches the length of the generators.""" ) elif isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): snake_case_ = [ self.movq.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(UpperCAmelCase_ ) ] snake_case_ = torch.cat(UpperCAmelCase_ , dim=0 ) else: snake_case_ = self.movq.encode(UpperCAmelCase_ ).latent_dist.sample(UpperCAmelCase_ ) snake_case_ = self.movq.config.scaling_factor * init_latents snake_case_ = torch.cat([init_latents] , dim=0 ) snake_case_ = init_latents.shape snake_case_ = randn_tensor(UpperCAmelCase_ , generator=UpperCAmelCase_ , device=UpperCAmelCase_ , dtype=UpperCAmelCase_ ) # get latents snake_case_ = self.scheduler.add_noise(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = init_latents return latents def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : List[Any]=0 ) ->Any: """simple docstring""" if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("""Please install accelerate via `pip install accelerate`""" ) snake_case_ = torch.device(F"""cuda:{gpu_id}""" ) snake_case_ = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : List[Any] , UpperCAmelCase_ : Dict=0 ) ->int: """simple docstring""" if is_accelerate_available() and is_accelerate_version(""">=""" , """0.17.0.dev0""" ): from accelerate import cpu_offload_with_hook else: raise ImportError("""`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.""" ) snake_case_ = torch.device(F"""cuda:{gpu_id}""" ) if self.device.type != "cpu": self.to("""cpu""" , silence_dtype_warnings=UpperCAmelCase_ ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) snake_case_ = None for cpu_offloaded_model in [self.unet, self.movq]: snake_case_ , snake_case_ = cpu_offload_with_hook(UpperCAmelCase_ , UpperCAmelCase_ , prev_module_hook=UpperCAmelCase_ ) # We'll offload the last model manually. snake_case_ = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def lowerCAmelCase ( self : Optional[Any] ) ->str: """simple docstring""" if not hasattr(self.unet , """_hf_hook""" ): return self.device for module in self.unet.modules(): if ( hasattr(UpperCAmelCase_ , """_hf_hook""" ) and hasattr(module._hf_hook , """execution_device""" ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(UpperCAmelCase_ ) def __call__( self : str , UpperCAmelCase_ : Union[torch.FloatTensor, List[torch.FloatTensor]] , UpperCAmelCase_ : Union[torch.FloatTensor, PIL.Image.Image, List[torch.FloatTensor], List[PIL.Image.Image]] , UpperCAmelCase_ : Union[torch.FloatTensor, List[torch.FloatTensor]] , UpperCAmelCase_ : int = 512 , UpperCAmelCase_ : int = 512 , UpperCAmelCase_ : int = 100 , UpperCAmelCase_ : float = 4.0 , UpperCAmelCase_ : float = 0.3 , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCAmelCase_ : Optional[str] = "pil" , UpperCAmelCase_ : bool = True , ) ->List[str]: """simple docstring""" snake_case_ = self._execution_device snake_case_ = guidance_scale > 1.0 if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): snake_case_ = torch.cat(UpperCAmelCase_ , dim=0 ) snake_case_ = image_embeds.shape[0] if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): snake_case_ = torch.cat(UpperCAmelCase_ , dim=0 ) if do_classifier_free_guidance: snake_case_ = image_embeds.repeat_interleave(UpperCAmelCase_ , dim=0 ) snake_case_ = negative_image_embeds.repeat_interleave(UpperCAmelCase_ , dim=0 ) snake_case_ = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=UpperCAmelCase_ ) if not isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): snake_case_ = [image] if not all(isinstance(UpperCAmelCase_ , (PIL.Image.Image, torch.Tensor) ) for i in image ): raise ValueError( F"""Input is in incorrect format: {[type(UpperCAmelCase_ ) for i in image]}. Currently, we only support PIL image and pytorch tensor""" ) snake_case_ = torch.cat([prepare_image(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) for i in image] , dim=0 ) snake_case_ = image.to(dtype=image_embeds.dtype , device=UpperCAmelCase_ ) snake_case_ = self.movq.encode(UpperCAmelCase_ )["""latents"""] snake_case_ = latents.repeat_interleave(UpperCAmelCase_ , dim=0 ) self.scheduler.set_timesteps(UpperCAmelCase_ , device=UpperCAmelCase_ ) snake_case_ , snake_case_ = self.get_timesteps(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = timesteps[:1].repeat(batch_size * num_images_per_prompt ) snake_case_ , snake_case_ = downscale_height_and_width(UpperCAmelCase_ , UpperCAmelCase_ , self.movq_scale_factor ) snake_case_ = self.prepare_latents( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , image_embeds.dtype , UpperCAmelCase_ , UpperCAmelCase_ ) for i, t in enumerate(self.progress_bar(UpperCAmelCase_ ) ): # expand the latents if we are doing classifier free guidance snake_case_ = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents snake_case_ = {"""image_embeds""": image_embeds} snake_case_ = self.unet( sample=UpperCAmelCase_ , timestep=UpperCAmelCase_ , encoder_hidden_states=UpperCAmelCase_ , added_cond_kwargs=UpperCAmelCase_ , return_dict=UpperCAmelCase_ , )[0] if do_classifier_free_guidance: snake_case_ , snake_case_ = noise_pred.split(latents.shape[1] , dim=1 ) snake_case_ , snake_case_ = noise_pred.chunk(2 ) snake_case_ , snake_case_ = variance_pred.chunk(2 ) snake_case_ = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) snake_case_ = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , """variance_type""" ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): snake_case_ , snake_case_ = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 snake_case_ = self.scheduler.step( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , generator=UpperCAmelCase_ , )[0] # post-processing snake_case_ = self.movq.decode(UpperCAmelCase_ , force_not_quantize=UpperCAmelCase_ )["""sample"""] if output_type not in ["pt", "np", "pil"]: raise ValueError(F"""Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}""" ) if output_type in ["np", "pil"]: snake_case_ = image * 0.5 + 0.5 snake_case_ = image.clamp(0 , 1 ) snake_case_ = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": snake_case_ = self.numpy_to_pil(UpperCAmelCase_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=UpperCAmelCase_ )
720
"""simple docstring""" import argparse import json import os from pathlib import Path import requests import torch from transformers import JukeboxConfig, JukeboxModel from transformers.utils import logging logging.set_verbosity_info() __SCREAMING_SNAKE_CASE : str = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Optional[int] = 'https://openaipublic.azureedge.net/jukebox/models/' __SCREAMING_SNAKE_CASE : List[Any] = { 'jukebox-1b-lyrics': [ '5b/vqvae.pth.tar', '5b/prior_level_0.pth.tar', '5b/prior_level_1.pth.tar', '1b_lyrics/prior_level_2.pth.tar', ], 'jukebox-5b-lyrics': [ '5b/vqvae.pth.tar', '5b/prior_level_0.pth.tar', '5b/prior_level_1.pth.tar', '5b_lyrics/prior_level_2.pth.tar', ], } def _a ( _SCREAMING_SNAKE_CASE ) -> int: if key.endswith(""".model.1.bias""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.1.bias""" , """.conv1d_1.bias""" ) elif key.endswith(""".model.1.weight""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.1.weight""" , """.conv1d_1.weight""" ) elif key.endswith(""".model.3.bias""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.3.bias""" , """.conv1d_2.bias""" ) elif key.endswith(""".model.3.weight""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.3.weight""" , """.conv1d_2.weight""" ) if "conditioner_blocks.0." in key: snake_case_ = key.replace("""conditioner_blocks.0""" , """conditioner_blocks""" ) if "prime_prior" in key: snake_case_ = key.replace("""prime_prior""" , """encoder""" ) if ".emb." in key and "total" not in key and "absolute" not in key and "relative" not in key: snake_case_ = key.replace(""".emb.""" , """.""" ) if key.endswith("""k""" ): # replace vqvae.X.k with vqvae.X.codebook return key.replace(""".k""" , """.codebook""" ) if "y_emb." in key: return key.replace("""y_emb.""" , """metadata_embedding.""" ) if "x_emb.emb." in key: snake_case_ = key.replace("""0.x_emb.emb""" , """embed_tokens""" ) if "prime_state_ln" in key: return key.replace("""prime_state_ln""" , """encoder.final_layer_norm""" ) if ".ln" in key: return key.replace(""".ln""" , """.layer_norm""" ) if "_ln" in key: return key.replace("""_ln""" , """_layer_norm""" ) if "prime_state_proj" in key: return key.replace("""prime_state_proj""" , """encoder.proj_in""" ) if "prime_x_out" in key: return key.replace("""prime_x_out""" , """encoder.lm_head""" ) if "prior.x_out" in key: return key.replace("""x_out""" , """fc_proj_out""" ) if "x_emb" in key: return key.replace("""x_emb""" , """embed_tokens""" ) return key def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: snake_case_ = {} import re snake_case_ = re.compile(r"""encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)""" ) snake_case_ = re.compile( r"""encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""encoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)""" ) snake_case_ = re.compile( r"""decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""decoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""conditioner_blocks.(\d*).cond.model.(\d*).(\d).(bias|weight)""" ) snake_case_ = re.compile( r"""conditioner_blocks.(\d*).cond.model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""conditioner_blocks.(\d*).cond.model.(\d*).(bias|weight)""" ) for original_key, value in state_dict.items(): # rename vqvae.encoder keys if re_encoder_block_conv_in.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_encoder_block_conv_in.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) snake_case_ = f"""encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.{groups[-1]}""" snake_case_ = re_encoder_block_conv_in.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_encoder_block_resnet.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_encoder_block_resnet.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) snake_case_ = {"""1""": 1, """3""": 2}[groups[-2]] snake_case_ = f"""encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.""" snake_case_ = f"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}""" snake_case_ = prefix + resnet_block snake_case_ = re_encoder_block_resnet.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_encoder_block_proj_out.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_encoder_block_proj_out.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = f"""encoders.{groups[0]}.level_blocks.{groups[1]}.proj_out.{groups[-1]}""" snake_case_ = re_encoder_block_proj_out.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # rename vqvae.decoder keys elif re_decoder_block_conv_out.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_decoder_block_conv_out.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) - 2 snake_case_ = f"""decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.{groups[-1]}""" snake_case_ = re_decoder_block_conv_out.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_decoder_block_resnet.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_decoder_block_resnet.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) - 2 snake_case_ = {"""1""": 1, """3""": 2}[groups[-2]] snake_case_ = f"""decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.""" snake_case_ = f"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}""" snake_case_ = prefix + resnet_block snake_case_ = re_decoder_block_resnet.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_decoder_block_proj_in.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_decoder_block_proj_in.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = f"""decoders.{groups[0]}.level_blocks.{groups[1]}.proj_in.{groups[-1]}""" snake_case_ = re_decoder_block_proj_in.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # rename prior cond.model to upsampler.upsample_block and resnet elif re_prior_cond_conv_out.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_prior_cond_conv_out.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[1] ) * 2 + int(groups[2] ) - 2 snake_case_ = f"""conditioner_blocks.upsampler.upsample_block.{block_index}.{groups[-1]}""" snake_case_ = re_prior_cond_conv_out.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_prior_cond_resnet.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_prior_cond_resnet.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[1] ) * 2 + int(groups[2] ) - 2 snake_case_ = {"""1""": 1, """3""": 2}[groups[-2]] snake_case_ = f"""conditioner_blocks.upsampler.upsample_block.{block_index}.""" snake_case_ = f"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}""" snake_case_ = prefix + resnet_block snake_case_ = re_prior_cond_resnet.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_prior_cond_proj_in.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_prior_cond_proj_in.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = f"""conditioner_blocks.upsampler.proj_in.{groups[-1]}""" snake_case_ = re_prior_cond_proj_in.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # keep original key else: snake_case_ = original_key snake_case_ = replace_key(_SCREAMING_SNAKE_CASE ) if f"""{key_prefix}.{key}""" not in model_state_dict or key is None: print(f"""failed converting {original_key} to {key}, does not match""" ) # handle missmatched shape elif value.shape != model_state_dict[f"""{key_prefix}.{key}"""].shape: snake_case_ = model_state_dict[f"""{key_prefix}.{key}"""] print(f"""{original_key}-> {key} : \nshape {val.shape} and { value.shape}, do not match""" ) snake_case_ = original_key snake_case_ = original_key snake_case_ = value return new_dict @torch.no_grad() def _a ( _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> Optional[int]: for file in MODEL_MAPPING[model_name]: if not os.path.isfile(f"""{pytorch_dump_folder_path}/{file.split("/" )[-1]}""" ): snake_case_ = requests.get(f"""{PREFIX}{file}""" , allow_redirects=_SCREAMING_SNAKE_CASE ) os.makedirs(f"""{pytorch_dump_folder_path}/""" , exist_ok=_SCREAMING_SNAKE_CASE ) open(f"""{pytorch_dump_folder_path}/{file.split("/" )[-1]}""" , """wb""" ).write(r.content ) snake_case_ = MODEL_MAPPING[model_name.split("""/""" )[-1]] snake_case_ = JukeboxConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) snake_case_ = JukeboxModel(_SCREAMING_SNAKE_CASE ) snake_case_ = [] snake_case_ = {} for i, dict_name in enumerate(_SCREAMING_SNAKE_CASE ): snake_case_ = torch.load(f"""{pytorch_dump_folder_path}/{dict_name.split("/" )[-1]}""" )["""model"""] snake_case_ = {} for k in old_dic.keys(): if k.endswith(""".b""" ): snake_case_ = old_dic[k] elif k.endswith(""".w""" ): snake_case_ = old_dic[k] elif "level_2" not in dict_name and "cond.model." in k: snake_case_ = old_dic[k] else: snake_case_ = old_dic[k] snake_case_ = """vqvae""" if i == 0 else f"""priors.{3 - i}""" snake_case_ = fix_jukebox_keys(_SCREAMING_SNAKE_CASE , model.state_dict() , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) weight_dict.append(_SCREAMING_SNAKE_CASE ) snake_case_ = weight_dict.pop(0 ) model.vqvae.load_state_dict(_SCREAMING_SNAKE_CASE ) for i in range(len(_SCREAMING_SNAKE_CASE ) ): model.priors[i].load_state_dict(weight_dict[2 - i] ) Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) with open(f"""{pytorch_dump_folder_path}/mapping.json""" , """w""" ) as txtfile: json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) print(f"""Saving model {model_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) return weight_dict if __name__ == "__main__": __SCREAMING_SNAKE_CASE : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='jukebox-5b-lyrics', type=str, help='Name of the model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default='jukebox-5b-lyrics-converted', type=str, help='Path to the output PyTorch model directory.', ) __SCREAMING_SNAKE_CASE : str = parser.parse_args() convert_openai_checkpoint(args.model_name, args.pytorch_dump_folder_path)
2
0
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE ) -> list: snake_case_ = int(_SCREAMING_SNAKE_CASE ) if n_element < 1: snake_case_ = ValueError("""a should be a positive number""" ) raise my_error snake_case_ = [1] snake_case_ , snake_case_ , snake_case_ = (0, 0, 0) snake_case_ = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2 , hamming_list[j] * 3 , hamming_list[k] * 5 ) ) index += 1 return hamming_list if __name__ == "__main__": __SCREAMING_SNAKE_CASE : str = input('Enter the last number (nth term) of the Hamming Number Series: ') print('Formula of Hamming Number Series => 2^i * 3^j * 5^k') __SCREAMING_SNAKE_CASE : str = hamming(int(n)) print('-----------------------------------------------------') print(f"""The list with nth numbers is: {hamming_numbers}""") print('-----------------------------------------------------')
721
"""simple docstring""" # XXX: we want transformers master here - in the absense of conftest manipulating sys.path: # hack it in for now: import sys from pathlib import Path __SCREAMING_SNAKE_CASE : Union[str, Any] = Path(__file__).resolve().parents[3] / 'src' sys.path.insert(1, str(git_repo_path)) import dataclasses # noqa import io # noqa import itertools # noqa import json # noqa import os # noqa import unittest # noqa from copy import deepcopy # noqa from parameterized import parameterized # noqa from transformers import TrainingArguments, is_torch_available # noqa from transformers.deepspeed import is_deepspeed_available # noqa from transformers.file_utils import WEIGHTS_NAME # noqa from transformers.testing_utils import ( # noqa CaptureLogger, ExtendSysPath, TestCasePlus, execute_subprocess_async, get_gpu_count, mockenv_context, require_deepspeed, require_torch_gpu, require_torch_multi_gpu, slow, ) from transformers.trainer_utils import set_seed # noqa set_seed(42) __SCREAMING_SNAKE_CASE : Dict = {'base': 'patrickvonplaten/wav2vec2_tiny_random', 'robust': 'patrickvonplaten/wav2vec2_tiny_random_robust'} __SCREAMING_SNAKE_CASE : Dict = 'zero2' __SCREAMING_SNAKE_CASE : List[Any] = 'zero3' __SCREAMING_SNAKE_CASE : int = [ZEROa, ZEROa] def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: # customize the test name generator function as we want both params to appear in the sub-test # name, as by default it shows only the first param snake_case_ = parameterized.to_safe_name("""_""".join(str(_SCREAMING_SNAKE_CASE ) for x in param.args ) ) return f"""{func.__name__}_{param_based_name}""" # Cartesian-product of zero stages with models to test __SCREAMING_SNAKE_CASE : Dict = list(itertools.product(stages, models.keys())) @slow @require_deepspeed @require_torch_gpu class __A (snake_case__): '''simple docstring''' @parameterized.expand(UpperCAmelCase_ , name_func=UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Union[str, Any] ) ->Any: """simple docstring""" self.run_and_check( stage=UpperCAmelCase_ , model=UpperCAmelCase_ , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) @require_torch_multi_gpu @parameterized.expand(UpperCAmelCase_ , name_func=UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[Any] ) ->Optional[Any]: """simple docstring""" self.run_and_check( stage=UpperCAmelCase_ , model=UpperCAmelCase_ , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) @parameterized.expand(UpperCAmelCase_ , name_func=UpperCAmelCase_ ) def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[int] ) ->List[str]: """simple docstring""" self.run_and_check( stage=UpperCAmelCase_ , model=UpperCAmelCase_ , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) @require_torch_multi_gpu @parameterized.expand(UpperCAmelCase_ , name_func=UpperCAmelCase_ ) def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : str , UpperCAmelCase_ : List[Any] ) ->Optional[int]: """simple docstring""" self.run_and_check( stage=UpperCAmelCase_ , model=UpperCAmelCase_ , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : Union[str, Any] ) ->Optional[int]: """simple docstring""" pass def lowerCAmelCase ( self : Any , UpperCAmelCase_ : str , UpperCAmelCase_ : str , UpperCAmelCase_ : int = 10 , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : bool = True , ) ->List[str]: """simple docstring""" snake_case_ = models[model] snake_case_ = self.run_trainer( stage=UpperCAmelCase_ , model_name=UpperCAmelCase_ , eval_steps=UpperCAmelCase_ , num_train_epochs=1 , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) self.do_checks(UpperCAmelCase_ ) return output_dir def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : str , UpperCAmelCase_ : int = 10 , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : bool = True , ) ->List[str]: """simple docstring""" snake_case_ = self.get_auto_remove_tmp_dir("""./xxx""" , after=UpperCAmelCase_ ) snake_case_ = F""" --model_name_or_path {model_name} --dataset_name hf-internal-testing/librispeech_asr_dummy --dataset_config_name clean --train_split_name validation --validation_split_name validation --output_dir {output_dir} --num_train_epochs {str(UpperCAmelCase_ )} --per_device_train_batch_size 2 --per_device_eval_batch_size 2 --evaluation_strategy steps --learning_rate 5e-4 --warmup_steps 8 --orthography timit --preprocessing_num_workers 1 --group_by_length --freeze_feature_extractor --report_to none --save_steps 0 --eval_steps {eval_steps} --report_to none """.split() if fpaa: args.extend(["""--fp16"""] ) # currently ds_config_wav2vec2_zero.json requires "zero_optimization.find_unused_parameters": true, # hence the separate config files snake_case_ = F"""--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json""".split() snake_case_ = [F"""{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py"""] snake_case_ = self.get_launcher(UpperCAmelCase_ ) snake_case_ = launcher + script + args + ds_args # keep for quick debug # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die execute_subprocess_async(UpperCAmelCase_ , env=self.get_env() ) return output_dir def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : Any=False ) ->Tuple: """simple docstring""" snake_case_ = min(2 , get_gpu_count() ) if distributed else 1 return F"""deepspeed --num_nodes 1 --num_gpus {num_gpus}""".split()
2
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __SCREAMING_SNAKE_CASE : Optional[int] = { 'configuration_conditional_detr': [ 'CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ConditionalDetrConfig', 'ConditionalDetrOnnxConfig', ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : Union[str, Any] = ['ConditionalDetrFeatureExtractor'] __SCREAMING_SNAKE_CASE : Dict = ['ConditionalDetrImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : Tuple = [ 'CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST', 'ConditionalDetrForObjectDetection', 'ConditionalDetrForSegmentation', 'ConditionalDetrModel', 'ConditionalDetrPreTrainedModel', ] if TYPE_CHECKING: from .configuration_conditional_detr import ( CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP, ConditionalDetrConfig, ConditionalDetrOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_conditional_detr import ConditionalDetrFeatureExtractor from .image_processing_conditional_detr import ConditionalDetrImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_conditional_detr import ( CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST, ConditionalDetrForObjectDetection, ConditionalDetrForSegmentation, ConditionalDetrModel, ConditionalDetrPreTrainedModel, ) else: import sys __SCREAMING_SNAKE_CASE : Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
700
"""simple docstring""" import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, Features, Value from .base import TaskTemplate @dataclass(frozen=snake_case__) class __A (snake_case__): '''simple docstring''' __lowercase: str = field(default="""automatic-speech-recognition""" , metadata={"""include_in_asdict_even_if_is_default""": True}) __lowercase: ClassVar[Features] = Features({"""audio""": Audio()}) __lowercase: ClassVar[Features] = Features({"""transcription""": Value("""string""")}) __lowercase: str = "audio" __lowercase: str = "transcription" def lowerCAmelCase ( self : List[Any] , UpperCAmelCase_ : Any ) ->int: """simple docstring""" if self.audio_column not in features: raise ValueError(F"""Column {self.audio_column} is not present in features.""" ) if not isinstance(features[self.audio_column] , UpperCAmelCase_ ): raise ValueError(F"""Column {self.audio_column} is not an Audio type.""" ) snake_case_ = copy.deepcopy(self ) snake_case_ = self.input_schema.copy() snake_case_ = features[self.audio_column] snake_case_ = input_schema return task_template @property def lowerCAmelCase ( self : List[str] ) ->Dict[str, str]: """simple docstring""" return {self.audio_column: "audio", self.transcription_column: "transcription"}
2
0
"""simple docstring""" from __future__ import annotations def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> list[int]: snake_case_ = 0 snake_case_ = len(_SCREAMING_SNAKE_CASE ) - 1 while i < j: if nums[i] + nums[j] == target: return [i, j] elif nums[i] + nums[j] < target: snake_case_ = i + 1 else: snake_case_ = j - 1 return [] if __name__ == "__main__": import doctest doctest.testmod() print(f"""{two_pointer([2, 7, 11, 15], 9) = }""")
701
"""simple docstring""" from functools import reduce __SCREAMING_SNAKE_CASE : Tuple = ( '73167176531330624919225119674426574742355349194934' '96983520312774506326239578318016984801869478851843' '85861560789112949495459501737958331952853208805511' '12540698747158523863050715693290963295227443043557' '66896648950445244523161731856403098711121722383113' '62229893423380308135336276614282806444486645238749' '30358907296290491560440772390713810515859307960866' '70172427121883998797908792274921901699720888093776' '65727333001053367881220235421809751254540594752243' '52584907711670556013604839586446706324415722155397' '53697817977846174064955149290862569321978468622482' '83972241375657056057490261407972968652414535100474' '82166370484403199890008895243450658541227588666881' '16427171479924442928230863465674813919123162824586' '17866458359124566529476545682848912883142607690042' '24219022671055626321111109370544217506941658960408' '07198403850962455444362981230987879927244284909188' '84580156166097919133875499200524063689912560717606' '05886116467109405077541002256983155200055935729725' '71636269561882670428252483600823257530420752963450' ) def _a ( _SCREAMING_SNAKE_CASE = N ) -> int: return max( # mypy cannot properly interpret reduce int(reduce(lambda _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : str(int(_SCREAMING_SNAKE_CASE ) * int(_SCREAMING_SNAKE_CASE ) ) , n[i : i + 13] ) ) for i in range(len(_SCREAMING_SNAKE_CASE ) - 12 ) ) if __name__ == "__main__": print(f"""{solution() = }""")
2
0
"""simple docstring""" from __future__ import annotations __SCREAMING_SNAKE_CASE : Dict = [ [-1, 0], # left [0, -1], # down [1, 0], # right [0, 1], # up ] def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , ) -> tuple[list[list[int]], list[list[int]]]: snake_case_ = [ [0 for col in range(len(grid[0] ) )] for row in range(len(_SCREAMING_SNAKE_CASE ) ) ] # the reference grid snake_case_ = 1 snake_case_ = [ [0 for col in range(len(grid[0] ) )] for row in range(len(_SCREAMING_SNAKE_CASE ) ) ] # the action grid snake_case_ = init[0] snake_case_ = init[1] snake_case_ = 0 snake_case_ = g + heuristic[x][y] # cost from starting cell to destination cell snake_case_ = [[f, g, x, y]] snake_case_ = False # flag that is set when search is complete snake_case_ = False # flag set if we can't find expand while not found and not resign: if len(_SCREAMING_SNAKE_CASE ) == 0: raise ValueError("""Algorithm is unable to find solution""" ) else: # to choose the least costliest action so as to move closer to the goal cell.sort() cell.reverse() snake_case_ = cell.pop() snake_case_ = next_cell[2] snake_case_ = next_cell[3] snake_case_ = next_cell[1] if x == goal[0] and y == goal[1]: snake_case_ = True else: for i in range(len(_SCREAMING_SNAKE_CASE ) ): # to try out different valid actions snake_case_ = x + DIRECTIONS[i][0] snake_case_ = y + DIRECTIONS[i][1] if xa >= 0 and xa < len(_SCREAMING_SNAKE_CASE ) and ya >= 0 and ya < len(grid[0] ): if closed[xa][ya] == 0 and grid[xa][ya] == 0: snake_case_ = g + cost snake_case_ = ga + heuristic[xa][ya] cell.append([fa, ga, xa, ya] ) snake_case_ = 1 snake_case_ = i snake_case_ = [] snake_case_ = goal[0] snake_case_ = goal[1] invpath.append([x, y] ) # we get the reverse path from here while x != init[0] or y != init[1]: snake_case_ = x - DIRECTIONS[action[x][y]][0] snake_case_ = y - DIRECTIONS[action[x][y]][1] snake_case_ = xa snake_case_ = ya invpath.append([x, y] ) snake_case_ = [] for i in range(len(_SCREAMING_SNAKE_CASE ) ): path.append(invpath[len(_SCREAMING_SNAKE_CASE ) - 1 - i] ) return path, action if __name__ == "__main__": __SCREAMING_SNAKE_CASE : List[str] = [ [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0], [0, 0, 0, 0, 1, 0], ] __SCREAMING_SNAKE_CASE : List[str] = [0, 0] # all coordinates are given in format [y,x] __SCREAMING_SNAKE_CASE : Any = [len(grid) - 1, len(grid[0]) - 1] __SCREAMING_SNAKE_CASE : Optional[Any] = 1 # the cost map which pushes the path closer to the goal __SCREAMING_SNAKE_CASE : Dict = [[0 for row in range(len(grid[0]))] for col in range(len(grid))] for i in range(len(grid)): for j in range(len(grid[0])): __SCREAMING_SNAKE_CASE : Tuple = abs(i - goal[0]) + abs(j - goal[1]) if grid[i][j] == 1: # added extra penalty in the heuristic map __SCREAMING_SNAKE_CASE : Optional[int] = 99 __SCREAMING_SNAKE_CASE : Optional[Any] = search(grid, init, goal, cost, heuristic) print('ACTION MAP') for i in range(len(action)): print(action[i]) for i in range(len(path)): print(path[i])
702
"""simple docstring""" from ....configuration_utils import PretrainedConfig from ....utils import logging __SCREAMING_SNAKE_CASE : str = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : str = { 'speechbrain/m-ctc-t-large': 'https://huggingface.co/speechbrain/m-ctc-t-large/resolve/main/config.json', # See all M-CTC-T models at https://huggingface.co/models?filter=mctct } class __A (snake_case__): '''simple docstring''' __lowercase: Any = """mctct""" def __init__( self : Dict , UpperCAmelCase_ : List[Any]=8_065 , UpperCAmelCase_ : Tuple=1_536 , UpperCAmelCase_ : Optional[Any]=36 , UpperCAmelCase_ : int=6_144 , UpperCAmelCase_ : Dict=4 , UpperCAmelCase_ : Any=384 , UpperCAmelCase_ : List[str]=920 , UpperCAmelCase_ : Any=1E-5 , UpperCAmelCase_ : Any=0.3 , UpperCAmelCase_ : Tuple="relu" , UpperCAmelCase_ : Union[str, Any]=0.02 , UpperCAmelCase_ : Dict=0.3 , UpperCAmelCase_ : str=0.3 , UpperCAmelCase_ : Any=1 , UpperCAmelCase_ : Any=0 , UpperCAmelCase_ : int=2 , UpperCAmelCase_ : str=1 , UpperCAmelCase_ : Tuple=0.3 , UpperCAmelCase_ : Optional[Any]=1 , UpperCAmelCase_ : Optional[Any]=(7,) , UpperCAmelCase_ : Optional[Any]=(3,) , UpperCAmelCase_ : List[str]=80 , UpperCAmelCase_ : Tuple=1 , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : List[str]="sum" , UpperCAmelCase_ : Union[str, Any]=False , **UpperCAmelCase_ : Any , ) ->Dict: """simple docstring""" super().__init__(**UpperCAmelCase_ , pad_token_id=UpperCAmelCase_ , bos_token_id=UpperCAmelCase_ , eos_token_id=UpperCAmelCase_ ) snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = intermediate_size snake_case_ = num_attention_heads snake_case_ = attention_head_dim snake_case_ = max_position_embeddings snake_case_ = layer_norm_eps snake_case_ = layerdrop snake_case_ = hidden_act snake_case_ = initializer_range snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = pad_token_id snake_case_ = bos_token_id snake_case_ = eos_token_id snake_case_ = conv_glu_dim snake_case_ = conv_dropout snake_case_ = num_conv_layers snake_case_ = input_feat_per_channel snake_case_ = input_channels snake_case_ = conv_channels snake_case_ = ctc_loss_reduction snake_case_ = ctc_zero_infinity # prevents config testing fail with exporting to json snake_case_ = list(UpperCAmelCase_ ) snake_case_ = list(UpperCAmelCase_ ) if len(self.conv_kernel ) != self.num_conv_layers: raise ValueError( """Configuration for convolutional module is incorrect. """ """It is required that `len(config.conv_kernel)` == `config.num_conv_layers` """ F"""but is `len(config.conv_kernel) = {len(self.conv_kernel )}`, """ F"""`config.num_conv_layers = {self.num_conv_layers}`.""" )
2
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __SCREAMING_SNAKE_CASE : Optional[Any] = { 'configuration_megatron_bert': ['MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MegatronBertConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : Tuple = [ 'MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'MegatronBertForCausalLM', 'MegatronBertForMaskedLM', 'MegatronBertForMultipleChoice', 'MegatronBertForNextSentencePrediction', 'MegatronBertForPreTraining', 'MegatronBertForQuestionAnswering', 'MegatronBertForSequenceClassification', 'MegatronBertForTokenClassification', 'MegatronBertModel', 'MegatronBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_megatron_bert import MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MegatronBertConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_megatron_bert import ( MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, MegatronBertPreTrainedModel, ) else: import sys __SCREAMING_SNAKE_CASE : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
703
"""simple docstring""" from math import factorial def _a ( _SCREAMING_SNAKE_CASE = 100 ) -> int: return sum(int(_SCREAMING_SNAKE_CASE ) for x in str(factorial(_SCREAMING_SNAKE_CASE ) ) ) if __name__ == "__main__": print(solution(int(input('Enter the Number: ').strip())))
2
0
"""simple docstring""" from operator import delitem, getitem, setitem import pytest from data_structures.hashing.hash_map import HashMap def _a ( _SCREAMING_SNAKE_CASE ) -> str: '''simple docstring''' return getitem, k def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[Any]: '''simple docstring''' return setitem, k, v def _a ( _SCREAMING_SNAKE_CASE ) -> Optional[int]: '''simple docstring''' return delitem, k def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , *_SCREAMING_SNAKE_CASE ) -> Any: '''simple docstring''' try: return fun(_SCREAMING_SNAKE_CASE , *_SCREAMING_SNAKE_CASE ), None except Exception as e: return None, e __SCREAMING_SNAKE_CASE : str = ( _set('key_a', 'val_a'), _set('key_b', 'val_b'), ) __SCREAMING_SNAKE_CASE : int = [ _set('key_a', 'val_a'), _set('key_a', 'val_b'), ] __SCREAMING_SNAKE_CASE : int = [ _set('key_a', 'val_a'), _set('key_b', 'val_b'), _del('key_a'), _del('key_b'), _set('key_a', 'val_a'), _del('key_a'), ] __SCREAMING_SNAKE_CASE : Union[str, Any] = [ _get('key_a'), _del('key_a'), _set('key_a', 'val_a'), _del('key_a'), _del('key_a'), _get('key_a'), ] __SCREAMING_SNAKE_CASE : int = [ *[_set(x, x) for x in range(5)], # guaranteed upsize ] __SCREAMING_SNAKE_CASE : List[str] = [ *[_set(x, x) for x in range(5)], # guaranteed upsize *[_del(x) for x in range(5)], _set('key_a', 'val_b'), ] @pytest.mark.parametrize( """operations""" , ( pytest.param(_add_items , id="""add items""" ), pytest.param(_overwrite_items , id="""overwrite items""" ), pytest.param(_delete_items , id="""delete items""" ), pytest.param(_access_absent_items , id="""access absent items""" ), pytest.param(_add_with_resize_up , id="""add with resize up""" ), pytest.param(_add_with_resize_down , id="""add with resize down""" ), ) , ) def _a ( _SCREAMING_SNAKE_CASE ) -> Optional[int]: '''simple docstring''' snake_case_ = HashMap(initial_block_size=4 ) snake_case_ = {} for _, (fun, *args) in enumerate(_SCREAMING_SNAKE_CASE ): snake_case_ , snake_case_ = _run_operation(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , *_SCREAMING_SNAKE_CASE ) snake_case_ , snake_case_ = _run_operation(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , *_SCREAMING_SNAKE_CASE ) assert my_res == py_res assert str(_SCREAMING_SNAKE_CASE ) == str(_SCREAMING_SNAKE_CASE ) assert set(_SCREAMING_SNAKE_CASE ) == set(_SCREAMING_SNAKE_CASE ) assert len(_SCREAMING_SNAKE_CASE ) == len(_SCREAMING_SNAKE_CASE ) assert set(my.items() ) == set(py.items() ) def _a ( ) -> Dict: '''simple docstring''' def is_public(_SCREAMING_SNAKE_CASE ) -> bool: return not name.startswith("""_""" ) snake_case_ = {name for name in dir({} ) if is_public(_SCREAMING_SNAKE_CASE )} snake_case_ = {name for name in dir(HashMap() ) if is_public(_SCREAMING_SNAKE_CASE )} assert dict_public_names > hash_public_names
704
"""simple docstring""" import unittest import torch from diffusers import VQModel from diffusers.utils import floats_tensor, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class __A (snake_case__ , snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: str = VQModel __lowercase: Union[str, Any] = """sample""" @property def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : List[str]=(32, 32) ) ->Tuple: """simple docstring""" snake_case_ = 4 snake_case_ = 3 snake_case_ = floats_tensor((batch_size, num_channels) + sizes ).to(UpperCAmelCase_ ) return {"sample": image} @property def lowerCAmelCase ( self : Tuple ) ->str: """simple docstring""" return (3, 32, 32) @property def lowerCAmelCase ( self : List[Any] ) ->Any: """simple docstring""" return (3, 32, 32) def lowerCAmelCase ( self : Optional[int] ) ->Dict: """simple docstring""" snake_case_ = { """block_out_channels""": [32, 64], """in_channels""": 3, """out_channels""": 3, """down_block_types""": ["""DownEncoderBlock2D""", """DownEncoderBlock2D"""], """up_block_types""": ["""UpDecoderBlock2D""", """UpDecoderBlock2D"""], """latent_channels""": 3, } snake_case_ = self.dummy_input return init_dict, inputs_dict def lowerCAmelCase ( self : List[str] ) ->Dict: """simple docstring""" pass def lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" pass def lowerCAmelCase ( self : Any ) ->Union[str, Any]: """simple docstring""" snake_case_ , snake_case_ = VQModel.from_pretrained("""fusing/vqgan-dummy""" , output_loading_info=UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) self.assertEqual(len(loading_info["""missing_keys"""] ) , 0 ) model.to(UpperCAmelCase_ ) snake_case_ = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def lowerCAmelCase ( self : Tuple ) ->Optional[Any]: """simple docstring""" snake_case_ = VQModel.from_pretrained("""fusing/vqgan-dummy""" ) model.to(UpperCAmelCase_ ).eval() torch.manual_seed(0 ) if torch.cuda.is_available(): torch.cuda.manual_seed_all(0 ) snake_case_ = torch.randn(1 , model.config.in_channels , model.config.sample_size , model.config.sample_size ) snake_case_ = image.to(UpperCAmelCase_ ) with torch.no_grad(): snake_case_ = model(UpperCAmelCase_ ).sample snake_case_ = output[0, -1, -3:, -3:].flatten().cpu() # fmt: off snake_case_ = torch.tensor([-0.0_153, -0.4_044, -0.1_880, -0.5_161, -0.2_418, -0.4_072, -0.1_612, -0.0_633, -0.0_143] ) # fmt: on self.assertTrue(torch.allclose(UpperCAmelCase_ , UpperCAmelCase_ , atol=1E-3 ) )
2
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __SCREAMING_SNAKE_CASE : Optional[int] = {'configuration_wavlm': ['WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP', 'WavLMConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : int = [ 'WAVLM_PRETRAINED_MODEL_ARCHIVE_LIST', 'WavLMForAudioFrameClassification', 'WavLMForCTC', 'WavLMForSequenceClassification', 'WavLMForXVector', 'WavLMModel', 'WavLMPreTrainedModel', ] if TYPE_CHECKING: from .configuration_wavlm import WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP, WavLMConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_wavlm import ( WAVLM_PRETRAINED_MODEL_ARCHIVE_LIST, WavLMForAudioFrameClassification, WavLMForCTC, WavLMForSequenceClassification, WavLMForXVector, WavLMModel, WavLMPreTrainedModel, ) else: import sys __SCREAMING_SNAKE_CASE : List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
705
"""simple docstring""" import gc import random import unittest import numpy as np import torch from diffusers import ( DDIMScheduler, KandinskyVaaControlnetPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) 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 from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class __A (snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Dict = KandinskyVaaControlnetPipeline __lowercase: str = ["""image_embeds""", """negative_image_embeds""", """hint"""] __lowercase: List[str] = ["""image_embeds""", """negative_image_embeds""", """hint"""] __lowercase: Union[str, Any] = [ """generator""", """height""", """width""", """latents""", """guidance_scale""", """num_inference_steps""", """return_dict""", """guidance_scale""", """num_images_per_prompt""", """output_type""", """return_dict""", ] __lowercase: Tuple = False @property def lowerCAmelCase ( self : Any ) ->Union[str, Any]: """simple docstring""" return 32 @property def lowerCAmelCase ( self : Optional[Any] ) ->Union[str, Any]: """simple docstring""" return 32 @property def lowerCAmelCase ( self : int ) ->List[str]: """simple docstring""" return self.time_input_dim @property def lowerCAmelCase ( self : Union[str, Any] ) ->Union[str, Any]: """simple docstring""" return self.time_input_dim * 4 @property def lowerCAmelCase ( self : Dict ) ->Optional[int]: """simple docstring""" return 100 @property def lowerCAmelCase ( self : str ) ->List[Any]: """simple docstring""" torch.manual_seed(0 ) snake_case_ = { """in_channels""": 8, # Out channels is double in channels because predicts mean and variance """out_channels""": 8, """addition_embed_type""": """image_hint""", """down_block_types""": ("""ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D"""), """up_block_types""": ("""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""), """mid_block_type""": """UNetMidBlock2DSimpleCrossAttn""", """block_out_channels""": (self.block_out_channels_a, self.block_out_channels_a * 2), """layers_per_block""": 1, """encoder_hid_dim""": self.text_embedder_hidden_size, """encoder_hid_dim_type""": """image_proj""", """cross_attention_dim""": self.cross_attention_dim, """attention_head_dim""": 4, """resnet_time_scale_shift""": """scale_shift""", """class_embed_type""": None, } snake_case_ = UNetaDConditionModel(**UpperCAmelCase_ ) return model @property def lowerCAmelCase ( self : Any ) ->Optional[Any]: """simple docstring""" return { "block_out_channels": [32, 32, 64, 64], "down_block_types": [ "DownEncoderBlock2D", "DownEncoderBlock2D", "DownEncoderBlock2D", "AttnDownEncoderBlock2D", ], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": ["AttnUpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"], "vq_embed_dim": 4, } @property def lowerCAmelCase ( self : Any ) ->int: """simple docstring""" torch.manual_seed(0 ) snake_case_ = VQModel(**self.dummy_movq_kwargs ) return model def lowerCAmelCase ( self : Dict ) ->str: """simple docstring""" snake_case_ = self.dummy_unet snake_case_ = self.dummy_movq snake_case_ = DDIMScheduler( num_train_timesteps=1_000 , beta_schedule="""linear""" , beta_start=0.00_085 , beta_end=0.012 , clip_sample=UpperCAmelCase_ , set_alpha_to_one=UpperCAmelCase_ , steps_offset=1 , prediction_type="""epsilon""" , thresholding=UpperCAmelCase_ , ) snake_case_ = { """unet""": unet, """scheduler""": scheduler, """movq""": movq, } return components def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[Any]=0 ) ->List[str]: """simple docstring""" snake_case_ = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(UpperCAmelCase_ ) ).to(UpperCAmelCase_ ) snake_case_ = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( UpperCAmelCase_ ) # create hint snake_case_ = floats_tensor((1, 3, 64, 64) , rng=random.Random(UpperCAmelCase_ ) ).to(UpperCAmelCase_ ) if str(UpperCAmelCase_ ).startswith("""mps""" ): snake_case_ = torch.manual_seed(UpperCAmelCase_ ) else: snake_case_ = torch.Generator(device=UpperCAmelCase_ ).manual_seed(UpperCAmelCase_ ) snake_case_ = { """image_embeds""": image_embeds, """negative_image_embeds""": negative_image_embeds, """hint""": hint, """generator""": generator, """height""": 64, """width""": 64, """guidance_scale""": 4.0, """num_inference_steps""": 2, """output_type""": """np""", } return inputs def lowerCAmelCase ( self : List[str] ) ->List[Any]: """simple docstring""" snake_case_ = """cpu""" snake_case_ = self.get_dummy_components() snake_case_ = self.pipeline_class(**UpperCAmelCase_ ) snake_case_ = pipe.to(UpperCAmelCase_ ) pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) snake_case_ = pipe(**self.get_dummy_inputs(UpperCAmelCase_ ) ) snake_case_ = output.images snake_case_ = pipe( **self.get_dummy_inputs(UpperCAmelCase_ ) , return_dict=UpperCAmelCase_ , )[0] snake_case_ = image[0, -3:, -3:, -1] snake_case_ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) snake_case_ = np.array( [0.6_959_826, 0.868_279, 0.7_558_092, 0.68_769_467, 0.85_805_804, 0.65_977_496, 0.44_885_302, 0.5_959_111, 0.4_251_595] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 ), F""" expected_slice {expected_slice}, but got {image_slice.flatten()}""" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 ), F""" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}""" @slow @require_torch_gpu class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : List[Any] ) ->Union[str, Any]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCAmelCase ( self : List[str] ) ->List[str]: """simple docstring""" snake_case_ = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinskyv22/kandinskyv22_controlnet_robotcat_fp16.npy""" ) snake_case_ = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinskyv22/hint_image_cat.png""" ) snake_case_ = torch.from_numpy(np.array(UpperCAmelCase_ ) ).float() / 255.0 snake_case_ = hint.permute(2 , 0 , 1 ).unsqueeze(0 ) snake_case_ = KandinskyVaaPriorPipeline.from_pretrained( """kandinsky-community/kandinsky-2-2-prior""" , torch_dtype=torch.floataa ) pipe_prior.to(UpperCAmelCase_ ) snake_case_ = KandinskyVaaControlnetPipeline.from_pretrained( """kandinsky-community/kandinsky-2-2-controlnet-depth""" , torch_dtype=torch.floataa ) snake_case_ = pipeline.to(UpperCAmelCase_ ) pipeline.set_progress_bar_config(disable=UpperCAmelCase_ ) snake_case_ = """A robot, 4k photo""" snake_case_ = torch.Generator(device="""cuda""" ).manual_seed(0 ) snake_case_ , snake_case_ = pipe_prior( UpperCAmelCase_ , generator=UpperCAmelCase_ , num_inference_steps=5 , negative_prompt="""""" , ).to_tuple() snake_case_ = torch.Generator(device="""cuda""" ).manual_seed(0 ) snake_case_ = pipeline( image_embeds=UpperCAmelCase_ , negative_image_embeds=UpperCAmelCase_ , hint=UpperCAmelCase_ , generator=UpperCAmelCase_ , num_inference_steps=100 , output_type="""np""" , ) snake_case_ = output.images[0] assert image.shape == (512, 512, 3) assert_mean_pixel_difference(UpperCAmelCase_ , UpperCAmelCase_ )
2
0
"""simple docstring""" 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 __SCREAMING_SNAKE_CASE : Union[str, Any] = pytest.mark.integration __SCREAMING_SNAKE_CASE : Optional[int] = {'comet'} __SCREAMING_SNAKE_CASE : Union[str, Any] = importlib.util.find_spec('fairseq') is not None __SCREAMING_SNAKE_CASE : Dict = {'code_eval'} __SCREAMING_SNAKE_CASE : str = os.name == 'nt' __SCREAMING_SNAKE_CASE : Union[str, Any] = {'bertscore', 'frugalscore', 'perplexity'} __SCREAMING_SNAKE_CASE : Any = importlib.util.find_spec('transformers') is not None def _a ( _SCREAMING_SNAKE_CASE ) -> str: @wraps(_SCREAMING_SNAKE_CASE ) def wrapper(self , _SCREAMING_SNAKE_CASE ): if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ: self.skipTest("""\"test requires Fairseq\"""" ) else: test_case(self , _SCREAMING_SNAKE_CASE ) return wrapper def _a ( _SCREAMING_SNAKE_CASE ) -> Optional[int]: @wraps(_SCREAMING_SNAKE_CASE ) def wrapper(self , _SCREAMING_SNAKE_CASE ): if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS: self.skipTest("""\"test requires transformers\"""" ) else: test_case(self , _SCREAMING_SNAKE_CASE ) return wrapper def _a ( _SCREAMING_SNAKE_CASE ) -> str: @wraps(_SCREAMING_SNAKE_CASE ) def wrapper(self , _SCREAMING_SNAKE_CASE ): if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS: self.skipTest("""\"test not supported on Windows\"""" ) else: test_case(self , _SCREAMING_SNAKE_CASE ) return wrapper def _a ( ) -> List[str]: snake_case_ = [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( snake_case__ , snake_case__ , snake_case__) @local class __A (parameterized.TestCase): '''simple docstring''' __lowercase: Tuple = {} __lowercase: Tuple = None @pytest.mark.filterwarnings("""ignore:metric_module_factory is deprecated:FutureWarning""" ) @pytest.mark.filterwarnings("""ignore:load_metric is deprecated:FutureWarning""" ) def lowerCAmelCase ( self : Any , UpperCAmelCase_ : List[str] ) ->Optional[Any]: """simple docstring""" snake_case_ = """[...]""" snake_case_ = importlib.import_module( datasets.load.metric_module_factory(os.path.join("""metrics""" , UpperCAmelCase_ ) ).module_path ) snake_case_ = datasets.load.import_main_class(metric_module.__name__ , dataset=UpperCAmelCase_ ) # check parameters snake_case_ = 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(UpperCAmelCase_ , metric_module.__name__ ): with self.use_local_metrics(): try: snake_case_ = doctest.testmod(UpperCAmelCase_ , verbose=UpperCAmelCase_ , raise_on_error=UpperCAmelCase_ ) 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 lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : List[str] ) ->Any: """simple docstring""" snake_case_ = """[...]""" snake_case_ = importlib.import_module( datasets.load.metric_module_factory(os.path.join("""metrics""" , UpperCAmelCase_ ) ).module_path ) # run doctest with self.use_local_metrics(): snake_case_ = doctest.testmod(UpperCAmelCase_ , verbose=UpperCAmelCase_ , raise_on_error=UpperCAmelCase_ ) self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @contextmanager def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[int] ) ->int: """simple docstring""" if metric_name in self.INTENSIVE_CALLS_PATCHER: with self.INTENSIVE_CALLS_PATCHER[metric_name](UpperCAmelCase_ ): yield else: yield @contextmanager def lowerCAmelCase ( self : List[Any] ) ->Optional[Any]: """simple docstring""" def load_local_metric(UpperCAmelCase_ : Optional[Any] , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : str ): return load_metric(os.path.join("""metrics""" , UpperCAmelCase_ ) , *UpperCAmelCase_ , **UpperCAmelCase_ ) with patch("""datasets.load_metric""" ) as mock_load_metric: snake_case_ = load_local_metric yield @classmethod def lowerCAmelCase ( cls : Any , UpperCAmelCase_ : Dict ) ->List[Any]: """simple docstring""" def wrapper(UpperCAmelCase_ : Optional[int] ): snake_case_ = contextmanager(UpperCAmelCase_ ) snake_case_ = patcher return patcher return wrapper @LocalMetricTest.register_intensive_calls_patcher("""bleurt""" ) def _a ( _SCREAMING_SNAKE_CASE ) -> str: import tensorflow.compat.va as tf from bleurt.score import Predictor tf.flags.DEFINE_string("""sv""" , """""" , """""" ) # handle pytest cli flags class __A (snake_case__): '''simple docstring''' def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : str ) ->List[str]: """simple docstring""" 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: snake_case_ = MockedPredictor() yield @LocalMetricTest.register_intensive_calls_patcher("""bertscore""" ) def _a ( _SCREAMING_SNAKE_CASE ) -> Optional[Any]: import torch def bert_cos_score_idf(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ): return torch.tensor([[1.0, 1.0, 1.0]] * len(_SCREAMING_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: snake_case_ = bert_cos_score_idf yield @LocalMetricTest.register_intensive_calls_patcher("""comet""" ) def _a ( _SCREAMING_SNAKE_CASE ) -> Any: def load_from_checkpoint(_SCREAMING_SNAKE_CASE ): class __A : '''simple docstring''' def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : Union[str, Any] , *UpperCAmelCase_ : Optional[int] , **UpperCAmelCase_ : str ) ->Any: """simple docstring""" assert len(UpperCAmelCase_ ) == 2 snake_case_ = [0.19, 0.92] return scores, sum(UpperCAmelCase_ ) / len(UpperCAmelCase_ ) 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: snake_case_ = None with patch("""comet.load_from_checkpoint""" ) as mock_load_from_checkpoint: snake_case_ = load_from_checkpoint yield def _a ( ) -> List[str]: snake_case_ = load_metric(os.path.join("""metrics""" , """seqeval""" ) ) snake_case_ = """ERROR""" snake_case_ = f"""Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}""" with pytest.raises(_SCREAMING_SNAKE_CASE , match=re.escape(_SCREAMING_SNAKE_CASE ) ): metric.compute(predictions=[] , references=[] , scheme=_SCREAMING_SNAKE_CASE )
706
"""simple docstring""" from __future__ import annotations from collections import deque class __A : '''simple docstring''' def __init__( self : List[Any] , UpperCAmelCase_ : list[str] ) ->List[Any]: """simple docstring""" snake_case_ = [] self.adlist.append( {"""value""": """""", """next_states""": [], """fail_state""": 0, """output""": []} ) for keyword in keywords: self.add_keyword(UpperCAmelCase_ ) self.set_fail_transitions() def lowerCAmelCase ( self : int , UpperCAmelCase_ : int , UpperCAmelCase_ : str ) ->int | None: """simple docstring""" for state in self.adlist[current_state]["next_states"]: if char == self.adlist[state]["value"]: return state return None def lowerCAmelCase ( self : int , UpperCAmelCase_ : str ) ->None: """simple docstring""" snake_case_ = 0 for character in keyword: snake_case_ = self.find_next_state(UpperCAmelCase_ , UpperCAmelCase_ ) if next_state is None: self.adlist.append( { """value""": character, """next_states""": [], """fail_state""": 0, """output""": [], } ) self.adlist[current_state]["next_states"].append(len(self.adlist ) - 1 ) snake_case_ = len(self.adlist ) - 1 else: snake_case_ = next_state self.adlist[current_state]["output"].append(UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->None: """simple docstring""" snake_case_ = deque() for node in self.adlist[0]["next_states"]: q.append(UpperCAmelCase_ ) snake_case_ = 0 while q: snake_case_ = q.popleft() for child in self.adlist[r]["next_states"]: q.append(UpperCAmelCase_ ) snake_case_ = self.adlist[r]["""fail_state"""] while ( self.find_next_state(UpperCAmelCase_ , self.adlist[child]["""value"""] ) is None and state != 0 ): snake_case_ = self.adlist[state]["""fail_state"""] snake_case_ = self.find_next_state( UpperCAmelCase_ , self.adlist[child]["""value"""] ) if self.adlist[child]["fail_state"] is None: snake_case_ = 0 snake_case_ = ( self.adlist[child]["""output"""] + self.adlist[self.adlist[child]["""fail_state"""]]["""output"""] ) def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : str ) ->dict[str, list[int]]: """simple docstring""" snake_case_ = {} # returns a dict with keywords and list of its occurrences snake_case_ = 0 for i in range(len(UpperCAmelCase_ ) ): while ( self.find_next_state(UpperCAmelCase_ , string[i] ) is None and current_state != 0 ): snake_case_ = self.adlist[current_state]["""fail_state"""] snake_case_ = self.find_next_state(UpperCAmelCase_ , string[i] ) if next_state is None: snake_case_ = 0 else: snake_case_ = next_state for key in self.adlist[current_state]["output"]: if key not in result: snake_case_ = [] result[key].append(i - len(UpperCAmelCase_ ) + 1 ) return result if __name__ == "__main__": import doctest doctest.testmod()
2
0
"""simple docstring""" import importlib import os import sys # This is required to make the module import works (when the python process is running from the root of the repo) sys.path.append('.') def _a ( _SCREAMING_SNAKE_CASE ) -> Any: snake_case_ = test_file.split(os.path.sep ) if components[0:2] != ["tests", "models"]: raise ValueError( """`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got """ f"""{test_file} instead.""" ) snake_case_ = components[-1] if not test_fn.endswith("""py""" ): raise ValueError(f"""`test_file` should be a python file. Got {test_fn} instead.""" ) if not test_fn.startswith("""test_modeling_""" ): raise ValueError( f"""`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead.""" ) snake_case_ = components[:-1] + [test_fn.replace(""".py""" , """""" )] snake_case_ = """.""".join(_SCREAMING_SNAKE_CASE ) return test_module_path def _a ( _SCREAMING_SNAKE_CASE ) -> Any: snake_case_ = get_module_path(_SCREAMING_SNAKE_CASE ) snake_case_ = importlib.import_module(_SCREAMING_SNAKE_CASE ) return test_module def _a ( _SCREAMING_SNAKE_CASE ) -> List[str]: snake_case_ = [] snake_case_ = get_test_module(_SCREAMING_SNAKE_CASE ) for attr in dir(_SCREAMING_SNAKE_CASE ): if attr.endswith("""ModelTester""" ): tester_classes.append(getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) # sort with class names return sorted(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : x.__name__ ) def _a ( _SCREAMING_SNAKE_CASE ) -> Optional[Any]: snake_case_ = [] snake_case_ = get_test_module(_SCREAMING_SNAKE_CASE ) for attr in dir(_SCREAMING_SNAKE_CASE ): snake_case_ = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking # `all_model_classes` is not empty (which also excludes other special classes). snake_case_ = getattr(_SCREAMING_SNAKE_CASE , """all_model_classes""" , [] ) if len(_SCREAMING_SNAKE_CASE ) > 0: test_classes.append(_SCREAMING_SNAKE_CASE ) # sort with class names return sorted(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : x.__name__ ) def _a ( _SCREAMING_SNAKE_CASE ) -> Any: snake_case_ = get_test_classes(_SCREAMING_SNAKE_CASE ) snake_case_ = set() for test_class in test_classes: model_classes.update(test_class.all_model_classes ) # sort with class names return sorted(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : x.__name__ ) def _a ( _SCREAMING_SNAKE_CASE ) -> Any: snake_case_ = test_class() if hasattr(_SCREAMING_SNAKE_CASE , """setUp""" ): test.setUp() snake_case_ = None if hasattr(_SCREAMING_SNAKE_CASE , """model_tester""" ): # `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case. if test.model_tester is not None: snake_case_ = test.model_tester.__class__ return model_tester def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple: snake_case_ = get_test_classes(_SCREAMING_SNAKE_CASE ) snake_case_ = [] for test_class in test_classes: if model_class in test_class.all_model_classes: target_test_classes.append(_SCREAMING_SNAKE_CASE ) # sort with class names return sorted(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : x.__name__ ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> int: snake_case_ = get_test_classes_for_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = [] for test_class in test_classes: snake_case_ = get_model_tester_from_test_class(_SCREAMING_SNAKE_CASE ) if tester_class is not None: tester_classes.append(_SCREAMING_SNAKE_CASE ) # sort with class names return sorted(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : x.__name__ ) def _a ( _SCREAMING_SNAKE_CASE ) -> Dict: snake_case_ = get_test_classes(_SCREAMING_SNAKE_CASE ) snake_case_ = {test_class: get_model_tester_from_test_class(_SCREAMING_SNAKE_CASE ) for test_class in test_classes} return test_tester_mapping def _a ( _SCREAMING_SNAKE_CASE ) -> List[Any]: snake_case_ = get_model_classes(_SCREAMING_SNAKE_CASE ) snake_case_ = { model_class: get_test_classes_for_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for model_class in model_classes } return model_test_mapping def _a ( _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: snake_case_ = get_model_classes(_SCREAMING_SNAKE_CASE ) snake_case_ = { model_class: get_tester_classes_for_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for model_class in model_classes } return model_to_tester_mapping def _a ( _SCREAMING_SNAKE_CASE ) -> Any: if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): return o elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): return o.__name__ elif isinstance(_SCREAMING_SNAKE_CASE , (list, tuple) ): return [to_json(_SCREAMING_SNAKE_CASE ) for x in o] elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): return {to_json(_SCREAMING_SNAKE_CASE ): to_json(_SCREAMING_SNAKE_CASE ) for k, v in o.items()} else: return o
707
"""simple docstring""" import inspect import unittest from transformers import ConvNextVaConfig from transformers.models.auto import get_values from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES 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 transformers import ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __A : '''simple docstring''' def __init__( self : Optional[int] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[int]=13 , UpperCAmelCase_ : str=32 , UpperCAmelCase_ : List[Any]=3 , UpperCAmelCase_ : Optional[Any]=4 , UpperCAmelCase_ : Dict=[10, 20, 30, 40] , UpperCAmelCase_ : List[Any]=[2, 2, 3, 2] , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : Any=37 , UpperCAmelCase_ : str="gelu" , UpperCAmelCase_ : Optional[int]=10 , UpperCAmelCase_ : Dict=0.02 , UpperCAmelCase_ : int=["stage2", "stage3", "stage4"] , UpperCAmelCase_ : Optional[int]=[2, 3, 4] , UpperCAmelCase_ : List[str]=None , ) ->Union[str, Any]: """simple docstring""" snake_case_ = parent snake_case_ = batch_size snake_case_ = image_size snake_case_ = num_channels snake_case_ = num_stages snake_case_ = hidden_sizes snake_case_ = depths snake_case_ = is_training snake_case_ = use_labels snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = num_labels snake_case_ = initializer_range snake_case_ = out_features snake_case_ = out_indices snake_case_ = scope def lowerCAmelCase ( self : List[str] ) ->str: """simple docstring""" snake_case_ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case_ = None if self.use_labels: snake_case_ = ids_tensor([self.batch_size] , self.num_labels ) snake_case_ = self.get_config() return config, pixel_values, labels def lowerCAmelCase ( self : Dict ) ->Optional[int]: """simple docstring""" return ConvNextVaConfig( num_channels=self.num_channels , hidden_sizes=self.hidden_sizes , depths=self.depths , num_stages=self.num_stages , hidden_act=self.hidden_act , is_decoder=UpperCAmelCase_ , initializer_range=self.initializer_range , out_features=self.out_features , out_indices=self.out_indices , num_labels=self.num_labels , ) def lowerCAmelCase ( self : List[Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Optional[Any] ) ->List[Any]: """simple docstring""" snake_case_ = ConvNextVaModel(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[Any] ) ->Any: """simple docstring""" snake_case_ = ConvNextVaForImageClassification(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCAmelCase ( self : Optional[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Union[str, Any] ) ->Tuple: """simple docstring""" snake_case_ = ConvNextVaBackbone(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ ) # verify hidden states self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:] ) # verify backbone works with out_features=None snake_case_ = None snake_case_ = ConvNextVaBackbone(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" snake_case_ = self.prepare_config_and_inputs() snake_case_ , snake_case_ , snake_case_ = config_and_inputs snake_case_ = {"""pixel_values""": pixel_values} return config, inputs_dict def lowerCAmelCase ( self : List[str] ) ->Union[str, Any]: """simple docstring""" snake_case_ = self.prepare_config_and_inputs() snake_case_ , snake_case_ , snake_case_ = config_and_inputs snake_case_ = {"""pixel_values""": pixel_values, """labels""": labels} return config, inputs_dict @require_torch class __A (snake_case__ , snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Optional[Any] = ( ( ConvNextVaModel, ConvNextVaForImageClassification, ConvNextVaBackbone, ) if is_torch_available() else () ) __lowercase: Union[str, Any] = ( {"""feature-extraction""": ConvNextVaModel, """image-classification""": ConvNextVaForImageClassification} if is_torch_available() else {} ) __lowercase: Union[str, Any] = False __lowercase: Optional[Any] = False __lowercase: Any = False __lowercase: Union[str, Any] = False __lowercase: Dict = False def lowerCAmelCase ( self : Union[str, Any] ) ->Tuple: """simple docstring""" snake_case_ = ConvNextVaModelTester(self ) snake_case_ = ConfigTester(self , config_class=UpperCAmelCase_ , has_text_modality=UpperCAmelCase_ , hidden_size=37 ) def lowerCAmelCase ( self : List[Any] ) ->Optional[Any]: """simple docstring""" 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 lowerCAmelCase ( self : str ) ->Optional[Any]: """simple docstring""" return @unittest.skip(reason="""ConvNextV2 does not use inputs_embeds""" ) def lowerCAmelCase ( self : Optional[int] ) ->Union[str, Any]: """simple docstring""" pass @unittest.skip(reason="""ConvNextV2 does not support input and output embeddings""" ) def lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" pass @unittest.skip(reason="""ConvNextV2 does not use feedforward chunking""" ) def lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" pass def lowerCAmelCase ( self : Dict ) ->Optional[int]: """simple docstring""" if not self.model_tester.is_training: return for model_class in self.all_model_classes: snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_with_labels() snake_case_ = True if model_class.__name__ in [ *get_values(UpperCAmelCase_ ), *get_values(UpperCAmelCase_ ), ]: continue snake_case_ = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.train() snake_case_ = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ , return_labels=UpperCAmelCase_ ) snake_case_ = model(**UpperCAmelCase_ ).loss loss.backward() def lowerCAmelCase ( self : Optional[int] ) ->Any: """simple docstring""" if not self.model_tester.is_training: return for model_class in self.all_model_classes: snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_with_labels() snake_case_ = False snake_case_ = True if ( model_class.__name__ in [*get_values(UpperCAmelCase_ ), *get_values(UpperCAmelCase_ )] or not model_class.supports_gradient_checkpointing ): continue snake_case_ = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.gradient_checkpointing_enable() model.train() snake_case_ = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ , return_labels=UpperCAmelCase_ ) snake_case_ = model(**UpperCAmelCase_ ).loss loss.backward() def lowerCAmelCase ( self : List[Any] ) ->Union[str, Any]: """simple docstring""" snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ = model_class(UpperCAmelCase_ ) snake_case_ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case_ = [*signature.parameters.keys()] snake_case_ = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] ) ->Union[str, Any]: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->Dict: """simple docstring""" def check_hidden_states_output(UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : str ): snake_case_ = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() with torch.no_grad(): snake_case_ = model(**self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) ) snake_case_ = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states snake_case_ = self.model_tester.num_stages self.assertEqual(len(UpperCAmelCase_ ) , expected_num_stages + 1 ) # ConvNextV2's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ = True check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] snake_case_ = True check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] ) ->Dict: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_ ) @slow def lowerCAmelCase ( self : Tuple ) ->str: """simple docstring""" for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ = ConvNextVaModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) def _a ( ) -> str: snake_case_ = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class __A (unittest.TestCase): '''simple docstring''' @cached_property def lowerCAmelCase ( self : Union[str, Any] ) ->Optional[int]: """simple docstring""" return AutoImageProcessor.from_pretrained("""facebook/convnextv2-tiny-1k-224""" ) if is_vision_available() else None @slow def lowerCAmelCase ( self : Tuple ) ->int: """simple docstring""" snake_case_ = ConvNextVaForImageClassification.from_pretrained("""facebook/convnextv2-tiny-1k-224""" ).to(UpperCAmelCase_ ) snake_case_ = self.default_image_processor snake_case_ = prepare_img() snake_case_ = preprocessor(images=UpperCAmelCase_ , return_tensors="""pt""" ).to(UpperCAmelCase_ ) # forward pass with torch.no_grad(): snake_case_ = model(**UpperCAmelCase_ ) # verify the logits snake_case_ = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape , UpperCAmelCase_ ) snake_case_ = torch.tensor([0.9_996, 0.1_966, -0.4_386] ).to(UpperCAmelCase_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCAmelCase_ , atol=1E-4 ) )
2
0
"""simple docstring""" import shutil import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_tf_cross_test, require_tf, require_torch, require_torchvision, require_vision, ) from transformers.utils import is_tf_available, is_torch_available, is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, SamImageProcessor, SamProcessor if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf @require_vision @require_torchvision class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : int ) ->str: """simple docstring""" snake_case_ = tempfile.mkdtemp() snake_case_ = SamImageProcessor() snake_case_ = SamProcessor(UpperCAmelCase_ ) processor.save_pretrained(self.tmpdirname ) def lowerCAmelCase ( self : List[Any] , **UpperCAmelCase_ : Any ) ->Tuple: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ).image_processor def lowerCAmelCase ( self : List[str] ) ->Dict: """simple docstring""" shutil.rmtree(self.tmpdirname ) def lowerCAmelCase ( self : Dict ) ->Optional[int]: """simple docstring""" snake_case_ = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] snake_case_ = [Image.fromarray(np.moveaxis(UpperCAmelCase_ , 0 , -1 ) ) for x in image_inputs] return image_inputs def lowerCAmelCase ( self : Any ) ->str: """simple docstring""" snake_case_ = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) snake_case_ = self.get_image_processor(do_normalize=UpperCAmelCase_ , padding_value=1.0 ) snake_case_ = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=UpperCAmelCase_ , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] ) ->Dict: """simple docstring""" snake_case_ = self.get_image_processor() snake_case_ = SamProcessor(image_processor=UpperCAmelCase_ ) snake_case_ = self.prepare_image_inputs() snake_case_ = image_processor(UpperCAmelCase_ , return_tensors="""np""" ) snake_case_ = processor(images=UpperCAmelCase_ , return_tensors="""np""" ) input_feat_extract.pop("""original_sizes""" ) # pop original_sizes as it is popped in the processor input_feat_extract.pop("""reshaped_input_sizes""" ) # pop original_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_torch def lowerCAmelCase ( self : Optional[Any] ) ->int: """simple docstring""" snake_case_ = self.get_image_processor() snake_case_ = SamProcessor(image_processor=UpperCAmelCase_ ) snake_case_ = [torch.ones((1, 3, 5, 5) )] snake_case_ = [[1_764, 2_646]] snake_case_ = [[683, 1_024]] snake_case_ = processor.post_process_masks(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) snake_case_ = processor.post_process_masks( UpperCAmelCase_ , torch.tensor(UpperCAmelCase_ ) , torch.tensor(UpperCAmelCase_ ) ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) # should also work with np snake_case_ = [np.ones((1, 3, 5, 5) )] snake_case_ = processor.post_process_masks(UpperCAmelCase_ , np.array(UpperCAmelCase_ ) , np.array(UpperCAmelCase_ ) ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) snake_case_ = [[1, 0], [0, 1]] with self.assertRaises(UpperCAmelCase_ ): snake_case_ = processor.post_process_masks(UpperCAmelCase_ , np.array(UpperCAmelCase_ ) , np.array(UpperCAmelCase_ ) ) @require_vision @require_tf class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : Optional[int] ) ->List[Any]: """simple docstring""" snake_case_ = tempfile.mkdtemp() snake_case_ = SamImageProcessor() snake_case_ = SamProcessor(UpperCAmelCase_ ) processor.save_pretrained(self.tmpdirname ) def lowerCAmelCase ( self : Optional[Any] , **UpperCAmelCase_ : Tuple ) ->Dict: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ).image_processor def lowerCAmelCase ( self : List[str] ) ->List[str]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def lowerCAmelCase ( self : Dict ) ->List[Any]: """simple docstring""" snake_case_ = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] snake_case_ = [Image.fromarray(np.moveaxis(UpperCAmelCase_ , 0 , -1 ) ) for x in image_inputs] return image_inputs def lowerCAmelCase ( self : Optional[Any] ) ->Union[str, Any]: """simple docstring""" snake_case_ = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) snake_case_ = self.get_image_processor(do_normalize=UpperCAmelCase_ , padding_value=1.0 ) snake_case_ = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=UpperCAmelCase_ , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] ) ->Tuple: """simple docstring""" snake_case_ = self.get_image_processor() snake_case_ = SamProcessor(image_processor=UpperCAmelCase_ ) snake_case_ = self.prepare_image_inputs() snake_case_ = image_processor(UpperCAmelCase_ , return_tensors="""np""" ) snake_case_ = processor(images=UpperCAmelCase_ , return_tensors="""np""" ) input_feat_extract.pop("""original_sizes""" ) # pop original_sizes as it is popped in the processor input_feat_extract.pop("""reshaped_input_sizes""" ) # pop reshaped_input_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_tf def lowerCAmelCase ( self : List[Any] ) ->List[Any]: """simple docstring""" snake_case_ = self.get_image_processor() snake_case_ = SamProcessor(image_processor=UpperCAmelCase_ ) snake_case_ = [tf.ones((1, 3, 5, 5) )] snake_case_ = [[1_764, 2_646]] snake_case_ = [[683, 1_024]] snake_case_ = processor.post_process_masks(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , return_tensors="""tf""" ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) snake_case_ = processor.post_process_masks( UpperCAmelCase_ , tf.convert_to_tensor(UpperCAmelCase_ ) , tf.convert_to_tensor(UpperCAmelCase_ ) , return_tensors="""tf""" , ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) # should also work with np snake_case_ = [np.ones((1, 3, 5, 5) )] snake_case_ = processor.post_process_masks( UpperCAmelCase_ , np.array(UpperCAmelCase_ ) , np.array(UpperCAmelCase_ ) , return_tensors="""tf""" ) self.assertEqual(masks[0].shape , (1, 3, 1_764, 2_646) ) snake_case_ = [[1, 0], [0, 1]] with self.assertRaises(tf.errors.InvalidArgumentError ): snake_case_ = processor.post_process_masks( UpperCAmelCase_ , np.array(UpperCAmelCase_ ) , np.array(UpperCAmelCase_ ) , return_tensors="""tf""" ) @require_vision @require_torchvision class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : int ) ->Any: """simple docstring""" snake_case_ = tempfile.mkdtemp() snake_case_ = SamImageProcessor() snake_case_ = SamProcessor(UpperCAmelCase_ ) processor.save_pretrained(self.tmpdirname ) def lowerCAmelCase ( self : Dict , **UpperCAmelCase_ : List[Any] ) ->str: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ).image_processor def lowerCAmelCase ( self : int ) ->Tuple: """simple docstring""" shutil.rmtree(self.tmpdirname ) def lowerCAmelCase ( self : int ) ->Dict: """simple docstring""" snake_case_ = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] snake_case_ = [Image.fromarray(np.moveaxis(UpperCAmelCase_ , 0 , -1 ) ) for x in image_inputs] return image_inputs @is_pt_tf_cross_test def lowerCAmelCase ( self : str ) ->Optional[int]: """simple docstring""" snake_case_ = self.get_image_processor() snake_case_ = SamProcessor(image_processor=UpperCAmelCase_ ) snake_case_ = np.random.randint(0 , 2 , size=(1, 3, 5, 5) ).astype(np.floataa ) snake_case_ = [tf.convert_to_tensor(UpperCAmelCase_ )] snake_case_ = [torch.tensor(UpperCAmelCase_ )] snake_case_ = [[1_764, 2_646]] snake_case_ = [[683, 1_024]] snake_case_ = processor.post_process_masks( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , return_tensors="""tf""" ) snake_case_ = processor.post_process_masks( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , return_tensors="""pt""" ) self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy() ) ) @is_pt_tf_cross_test def lowerCAmelCase ( self : Optional[Any] ) ->int: """simple docstring""" snake_case_ = self.get_image_processor() snake_case_ = SamProcessor(image_processor=UpperCAmelCase_ ) snake_case_ = self.prepare_image_inputs() snake_case_ = image_processor(UpperCAmelCase_ , return_tensors="""pt""" )["""pixel_values"""].numpy() snake_case_ = processor(images=UpperCAmelCase_ , return_tensors="""pt""" )["""pixel_values"""].numpy() snake_case_ = image_processor(UpperCAmelCase_ , return_tensors="""tf""" )["""pixel_values"""].numpy() snake_case_ = processor(images=UpperCAmelCase_ , return_tensors="""tf""" )["""pixel_values"""].numpy() self.assertTrue(np.allclose(UpperCAmelCase_ , UpperCAmelCase_ ) ) self.assertTrue(np.allclose(UpperCAmelCase_ , UpperCAmelCase_ ) ) self.assertTrue(np.allclose(UpperCAmelCase_ , UpperCAmelCase_ ) )
708
"""simple docstring""" import argparse from pathlib import Path from typing import Dict, OrderedDict, Tuple import torch from audiocraft.models import MusicGen from transformers import ( AutoFeatureExtractor, AutoTokenizer, EncodecModel, MusicgenDecoderConfig, MusicgenForConditionalGeneration, MusicgenProcessor, TaEncoderModel, ) from transformers.models.musicgen.modeling_musicgen import MusicgenForCausalLM from transformers.utils import logging logging.set_verbosity_info() __SCREAMING_SNAKE_CASE : Union[str, Any] = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : int = ['model.decoder.embed_positions.weights'] def _a ( _SCREAMING_SNAKE_CASE ) -> str: if "emb" in name: snake_case_ = name.replace("""emb""" , """model.decoder.embed_tokens""" ) if "transformer" in name: snake_case_ = name.replace("""transformer""" , """model.decoder""" ) if "cross_attention" in name: snake_case_ = name.replace("""cross_attention""" , """encoder_attn""" ) if "linear1" in name: snake_case_ = name.replace("""linear1""" , """fc1""" ) if "linear2" in name: snake_case_ = name.replace("""linear2""" , """fc2""" ) if "norm1" in name: snake_case_ = name.replace("""norm1""" , """self_attn_layer_norm""" ) if "norm_cross" in name: snake_case_ = name.replace("""norm_cross""" , """encoder_attn_layer_norm""" ) if "norm2" in name: snake_case_ = name.replace("""norm2""" , """final_layer_norm""" ) if "out_norm" in name: snake_case_ = name.replace("""out_norm""" , """model.decoder.layer_norm""" ) if "linears" in name: snake_case_ = name.replace("""linears""" , """lm_heads""" ) if "condition_provider.conditioners.description.output_proj" in name: snake_case_ = name.replace("""condition_provider.conditioners.description.output_proj""" , """enc_to_dec_proj""" ) return name def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple[Dict, Dict]: snake_case_ = list(state_dict.keys() ) snake_case_ = {} for key in keys: snake_case_ = state_dict.pop(_SCREAMING_SNAKE_CASE ) snake_case_ = rename_keys(_SCREAMING_SNAKE_CASE ) if "in_proj_weight" in key: # split fused qkv proj snake_case_ = val[:hidden_size, :] snake_case_ = val[hidden_size : 2 * hidden_size, :] snake_case_ = val[-hidden_size:, :] elif "enc_to_dec_proj" in key: snake_case_ = val else: snake_case_ = val return state_dict, enc_dec_proj_state_dict def _a ( _SCREAMING_SNAKE_CASE ) -> MusicgenDecoderConfig: if checkpoint == "small": # default config values snake_case_ = 1_024 snake_case_ = 24 snake_case_ = 16 elif checkpoint == "medium": snake_case_ = 1_536 snake_case_ = 48 snake_case_ = 24 elif checkpoint == "large": snake_case_ = 2_048 snake_case_ = 48 snake_case_ = 32 else: raise ValueError(f"""Checkpoint should be one of `['small', 'medium', 'large']`, got {checkpoint}.""" ) snake_case_ = MusicgenDecoderConfig( hidden_size=_SCREAMING_SNAKE_CASE , ffn_dim=hidden_size * 4 , num_hidden_layers=_SCREAMING_SNAKE_CASE , num_attention_heads=_SCREAMING_SNAKE_CASE , ) return config @torch.no_grad() def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE="cpu" ) -> Tuple: snake_case_ = MusicGen.get_pretrained(_SCREAMING_SNAKE_CASE , device=_SCREAMING_SNAKE_CASE ) snake_case_ = decoder_config_from_checkpoint(_SCREAMING_SNAKE_CASE ) snake_case_ = fairseq_model.lm.state_dict() snake_case_ , snake_case_ = rename_state_dict( _SCREAMING_SNAKE_CASE , hidden_size=decoder_config.hidden_size ) snake_case_ = TaEncoderModel.from_pretrained("""t5-base""" ) snake_case_ = EncodecModel.from_pretrained("""facebook/encodec_32khz""" ) snake_case_ = MusicgenForCausalLM(_SCREAMING_SNAKE_CASE ).eval() # load all decoder weights - expect that we'll be missing embeddings and enc-dec projection snake_case_ , snake_case_ = decoder.load_state_dict(_SCREAMING_SNAKE_CASE , strict=_SCREAMING_SNAKE_CASE ) for key in missing_keys.copy(): if key.startswith(("""text_encoder""", """audio_encoder""") ) or key in EXPECTED_MISSING_KEYS: missing_keys.remove(_SCREAMING_SNAKE_CASE ) if len(_SCREAMING_SNAKE_CASE ) > 0: raise ValueError(f"""Missing key(s) in state_dict: {missing_keys}""" ) if len(_SCREAMING_SNAKE_CASE ) > 0: raise ValueError(f"""Unexpected key(s) in state_dict: {unexpected_keys}""" ) # init the composite model snake_case_ = MusicgenForConditionalGeneration(text_encoder=_SCREAMING_SNAKE_CASE , audio_encoder=_SCREAMING_SNAKE_CASE , decoder=_SCREAMING_SNAKE_CASE ) # load the pre-trained enc-dec projection (from the decoder state dict) model.enc_to_dec_proj.load_state_dict(_SCREAMING_SNAKE_CASE ) # check we can do a forward pass snake_case_ = torch.arange(0 , 8 , dtype=torch.long ).reshape(2 , -1 ) snake_case_ = input_ids.reshape(2 * 4 , -1 ) with torch.no_grad(): snake_case_ = model(input_ids=_SCREAMING_SNAKE_CASE , decoder_input_ids=_SCREAMING_SNAKE_CASE ).logits if logits.shape != (8, 1, 2_048): raise ValueError("""Incorrect shape for logits""" ) # now construct the processor snake_case_ = AutoTokenizer.from_pretrained("""t5-base""" ) snake_case_ = AutoFeatureExtractor.from_pretrained("""facebook/encodec_32khz""" , padding_side="""left""" ) snake_case_ = MusicgenProcessor(feature_extractor=_SCREAMING_SNAKE_CASE , tokenizer=_SCREAMING_SNAKE_CASE ) # set the appropriate bos/pad token ids snake_case_ = 2_048 snake_case_ = 2_048 # set other default generation config params snake_case_ = int(30 * audio_encoder.config.frame_rate ) snake_case_ = True snake_case_ = 3.0 if pytorch_dump_folder is not None: Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) logger.info(f"""Saving model {checkpoint} to {pytorch_dump_folder}""" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) processor.save_pretrained(_SCREAMING_SNAKE_CASE ) if repo_id: logger.info(f"""Pushing model {checkpoint} to {repo_id}""" ) model.push_to_hub(_SCREAMING_SNAKE_CASE ) processor.push_to_hub(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( '--checkpoint', default='small', type=str, help='Checkpoint size of the MusicGen model you\'d like to convert. Can be one of: `[\'small\', \'medium\', \'large\']`.', ) parser.add_argument( '--pytorch_dump_folder', required=True, default=None, type=str, help='Path to the output PyTorch model directory.', ) parser.add_argument( '--push_to_hub', default=None, type=str, help='Where to upload the converted model on the 🤗 hub.' ) parser.add_argument( '--device', default='cpu', type=str, help='Torch device to run the conversion, either cpu or cuda.' ) __SCREAMING_SNAKE_CASE : int = parser.parse_args() convert_musicgen_checkpoint(args.checkpoint, args.pytorch_dump_folder, args.push_to_hub)
2
0
"""simple docstring""" from __future__ import annotations def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> bool: if len(_SCREAMING_SNAKE_CASE ) == 0: return False snake_case_ = len(_SCREAMING_SNAKE_CASE ) // 2 if a_list[midpoint] == item: return True if item < a_list[midpoint]: return binary_search(a_list[:midpoint] , _SCREAMING_SNAKE_CASE ) else: return binary_search(a_list[midpoint + 1 :] , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : List[str] = input('Enter numbers separated by comma:\n').strip() __SCREAMING_SNAKE_CASE : Tuple = [int(item.strip()) for item in user_input.split(',')] __SCREAMING_SNAKE_CASE : Union[str, Any] = int(input('Enter the number to be found in the list:\n').strip()) __SCREAMING_SNAKE_CASE : int = '' if binary_search(sequence, target) else 'not ' print(f"""{target} was {not_str}found in {sequence}""")
709
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> int: if index == number_of_items: return 0 snake_case_ = 0 snake_case_ = 0 snake_case_ = knapsack(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , index + 1 ) if weights[index] <= max_weight: snake_case_ = values[index] + knapsack( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , max_weight - weights[index] , index + 1 ) return max(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": import doctest doctest.testmod()
2
0
"""simple docstring""" import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ViTImageProcessor, ViTMSNConfig, ViTMSNModel from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD torch.set_grad_enabled(False) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) -> Tuple: snake_case_ = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f"""module.blocks.{i}.norm1.weight""", f"""vit.encoder.layer.{i}.layernorm_before.weight""") ) rename_keys.append((f"""module.blocks.{i}.norm1.bias""", f"""vit.encoder.layer.{i}.layernorm_before.bias""") ) rename_keys.append( (f"""module.blocks.{i}.attn.proj.weight""", f"""vit.encoder.layer.{i}.attention.output.dense.weight""") ) rename_keys.append((f"""module.blocks.{i}.attn.proj.bias""", f"""vit.encoder.layer.{i}.attention.output.dense.bias""") ) rename_keys.append((f"""module.blocks.{i}.norm2.weight""", f"""vit.encoder.layer.{i}.layernorm_after.weight""") ) rename_keys.append((f"""module.blocks.{i}.norm2.bias""", f"""vit.encoder.layer.{i}.layernorm_after.bias""") ) rename_keys.append((f"""module.blocks.{i}.mlp.fc1.weight""", f"""vit.encoder.layer.{i}.intermediate.dense.weight""") ) rename_keys.append((f"""module.blocks.{i}.mlp.fc1.bias""", f"""vit.encoder.layer.{i}.intermediate.dense.bias""") ) rename_keys.append((f"""module.blocks.{i}.mlp.fc2.weight""", f"""vit.encoder.layer.{i}.output.dense.weight""") ) rename_keys.append((f"""module.blocks.{i}.mlp.fc2.bias""", f"""vit.encoder.layer.{i}.output.dense.bias""") ) # projection layer + position embeddings rename_keys.extend( [ ("""module.cls_token""", """vit.embeddings.cls_token"""), ("""module.patch_embed.proj.weight""", """vit.embeddings.patch_embeddings.projection.weight"""), ("""module.patch_embed.proj.bias""", """vit.embeddings.patch_embeddings.projection.bias"""), ("""module.pos_embed""", """vit.embeddings.position_embeddings"""), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ("""module.norm.weight""", """layernorm.weight"""), ("""module.norm.bias""", """layernorm.bias"""), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" snake_case_ = [(pair[0], pair[1][4:]) if pair[1].startswith("""vit""" ) else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ("""norm.weight""", """vit.layernorm.weight"""), ("""norm.bias""", """vit.layernorm.bias"""), ("""head.weight""", """classifier.weight"""), ("""head.bias""", """classifier.bias"""), ] ) return rename_keys def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) -> int: for i in range(config.num_hidden_layers ): if base_model: snake_case_ = """""" else: snake_case_ = """vit.""" # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) snake_case_ = state_dict.pop(f"""module.blocks.{i}.attn.qkv.weight""" ) snake_case_ = state_dict.pop(f"""module.blocks.{i}.attn.qkv.bias""" ) # next, add query, keys and values (in that order) to the state dict snake_case_ = in_proj_weight[ : config.hidden_size, : ] snake_case_ = in_proj_bias[: config.hidden_size] snake_case_ = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] snake_case_ = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] snake_case_ = in_proj_weight[ -config.hidden_size :, : ] snake_case_ = in_proj_bias[-config.hidden_size :] def _a ( _SCREAMING_SNAKE_CASE ) -> List[str]: snake_case_ = ["""head.weight""", """head.bias"""] for k in ignore_keys: state_dict.pop(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE ) -> List[Any]: # projection head is used in the self-supervised pre-training in MSN, # for downstream task it's not needed. snake_case_ = [ """module.fc.fc1.weight""", """module.fc.fc1.bias""", """module.fc.bn1.weight""", """module.fc.bn1.bias""", """module.fc.bn1.running_mean""", """module.fc.bn1.running_var""", """module.fc.bn1.num_batches_tracked""", """module.fc.fc2.weight""", """module.fc.fc2.bias""", """module.fc.bn2.weight""", """module.fc.bn2.bias""", """module.fc.bn2.running_mean""", """module.fc.bn2.running_var""", """module.fc.bn2.num_batches_tracked""", """module.fc.fc3.weight""", """module.fc.fc3.bias""", ] for k in ignore_keys: state_dict.pop(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[int]: snake_case_ = dct.pop(_SCREAMING_SNAKE_CASE ) snake_case_ = val def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[str]: snake_case_ = ViTMSNConfig() snake_case_ = 1_000 snake_case_ = """datasets/huggingface/label-files""" snake_case_ = """imagenet-1k-id2label.json""" snake_case_ = json.load(open(hf_hub_download(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) , """r""" ) ) snake_case_ = {int(_SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()} snake_case_ = idalabel snake_case_ = {v: k for k, v in idalabel.items()} if "s16" in checkpoint_url: snake_case_ = 384 snake_case_ = 1_536 snake_case_ = 6 elif "l16" in checkpoint_url: snake_case_ = 1_024 snake_case_ = 4_096 snake_case_ = 24 snake_case_ = 16 snake_case_ = 0.1 elif "b4" in checkpoint_url: snake_case_ = 4 elif "l7" in checkpoint_url: snake_case_ = 7 snake_case_ = 1_024 snake_case_ = 4_096 snake_case_ = 24 snake_case_ = 16 snake_case_ = 0.1 snake_case_ = ViTMSNModel(_SCREAMING_SNAKE_CASE ) snake_case_ = torch.hub.load_state_dict_from_url(_SCREAMING_SNAKE_CASE , map_location="""cpu""" )["""target_encoder"""] snake_case_ = ViTImageProcessor(size=config.image_size ) remove_projection_head(_SCREAMING_SNAKE_CASE ) snake_case_ = create_rename_keys(_SCREAMING_SNAKE_CASE , base_model=_SCREAMING_SNAKE_CASE ) for src, dest in rename_keys: rename_key(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) read_in_q_k_v(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , base_model=_SCREAMING_SNAKE_CASE ) model.load_state_dict(_SCREAMING_SNAKE_CASE ) model.eval() snake_case_ = """http://images.cocodataset.org/val2017/000000039769.jpg""" snake_case_ = Image.open(requests.get(_SCREAMING_SNAKE_CASE , stream=_SCREAMING_SNAKE_CASE ).raw ) snake_case_ = ViTImageProcessor( size=config.image_size , image_mean=_SCREAMING_SNAKE_CASE , image_std=_SCREAMING_SNAKE_CASE ) snake_case_ = image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors="""pt""" ) # forward pass torch.manual_seed(2 ) snake_case_ = model(**_SCREAMING_SNAKE_CASE ) snake_case_ = outputs.last_hidden_state # The following Colab Notebook was used to generate these outputs: # https://colab.research.google.com/gist/sayakpaul/3672419a04f5997827503fd84079bdd1/scratchpad.ipynb if "s16" in checkpoint_url: snake_case_ = torch.tensor([[-1.0915, -1.4876, -1.1809]] ) elif "b16" in checkpoint_url: snake_case_ = torch.tensor([[14.2889, -18.9045, 11.7281]] ) elif "l16" in checkpoint_url: snake_case_ = torch.tensor([[41.5028, -22.8681, 45.6475]] ) elif "b4" in checkpoint_url: snake_case_ = torch.tensor([[-4.3868, 5.2932, -0.4137]] ) else: snake_case_ = torch.tensor([[-0.1792, -0.6465, 2.4263]] ) # verify logits assert torch.allclose(last_hidden_state[:, 0, :3] , _SCREAMING_SNAKE_CASE , atol=1E-4 ) print(f"""Saving model to {pytorch_dump_folder_path}""" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) print(f"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( '--checkpoint_url', default='https://dl.fbaipublicfiles.com/msn/vits16_800ep.pth.tar', 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.' ) __SCREAMING_SNAKE_CASE : Any = parser.parse_args() convert_vit_msn_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
710
"""simple docstring""" from math import factorial def _a ( _SCREAMING_SNAKE_CASE = 20 ) -> int: snake_case_ = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1, # 2, 3,... snake_case_ = n // 2 return int(factorial(_SCREAMING_SNAKE_CASE ) / (factorial(_SCREAMING_SNAKE_CASE ) * factorial(n - k )) ) if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution(20)) else: try: __SCREAMING_SNAKE_CASE : Optional[int] = int(sys.argv[1]) print(solution(n)) except ValueError: print('Invalid entry - please enter a number.')
2
0
"""simple docstring""" import sys from pathlib import Path __SCREAMING_SNAKE_CASE : Union[str, Any] = Path(__file__).resolve().parents[3] / 'src' sys.path.insert(1, str(git_repo_path)) import dataclasses # noqa import io # noqa import itertools # noqa import json # noqa import os # noqa import unittest # noqa from copy import deepcopy # noqa from parameterized import parameterized # noqa from transformers import TrainingArguments, is_torch_available # noqa from transformers.deepspeed import is_deepspeed_available # noqa from transformers.file_utils import WEIGHTS_NAME # noqa from transformers.testing_utils import ( # noqa CaptureLogger, ExtendSysPath, TestCasePlus, execute_subprocess_async, get_gpu_count, mockenv_context, require_deepspeed, require_torch_gpu, require_torch_multi_gpu, slow, ) from transformers.trainer_utils import set_seed # noqa set_seed(42) __SCREAMING_SNAKE_CASE : Dict = {'base': 'patrickvonplaten/wav2vec2_tiny_random', 'robust': 'patrickvonplaten/wav2vec2_tiny_random_robust'} __SCREAMING_SNAKE_CASE : Dict = 'zero2' __SCREAMING_SNAKE_CASE : List[Any] = 'zero3' __SCREAMING_SNAKE_CASE : int = [ZEROa, ZEROa] def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: # customize the test name generator function as we want both params to appear in the sub-test # name, as by default it shows only the first param snake_case_ = parameterized.to_safe_name("""_""".join(str(_SCREAMING_SNAKE_CASE ) for x in param.args ) ) return f"""{func.__name__}_{param_based_name}""" # Cartesian-product of zero stages with models to test __SCREAMING_SNAKE_CASE : Dict = list(itertools.product(stages, models.keys())) @slow @require_deepspeed @require_torch_gpu class __A (snake_case__): @parameterized.expand(UpperCAmelCase_ , name_func=UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Union[str, Any] ) ->Any: """simple docstring""" self.run_and_check( stage=UpperCAmelCase_ , model=UpperCAmelCase_ , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) @require_torch_multi_gpu @parameterized.expand(UpperCAmelCase_ , name_func=UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[Any] ) ->Optional[Any]: """simple docstring""" self.run_and_check( stage=UpperCAmelCase_ , model=UpperCAmelCase_ , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) @parameterized.expand(UpperCAmelCase_ , name_func=UpperCAmelCase_ ) def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[int] ) ->List[str]: """simple docstring""" self.run_and_check( stage=UpperCAmelCase_ , model=UpperCAmelCase_ , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) @require_torch_multi_gpu @parameterized.expand(UpperCAmelCase_ , name_func=UpperCAmelCase_ ) def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : str , UpperCAmelCase_ : List[Any] ) ->Optional[int]: """simple docstring""" self.run_and_check( stage=UpperCAmelCase_ , model=UpperCAmelCase_ , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : Union[str, Any] ) ->Optional[int]: """simple docstring""" pass def lowerCAmelCase ( self : Any , UpperCAmelCase_ : str , UpperCAmelCase_ : str , UpperCAmelCase_ : int = 10 , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : bool = True , ) ->List[str]: """simple docstring""" snake_case_ = models[model] snake_case_ = self.run_trainer( stage=UpperCAmelCase_ , model_name=UpperCAmelCase_ , eval_steps=UpperCAmelCase_ , num_train_epochs=1 , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) self.do_checks(UpperCAmelCase_ ) return output_dir def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : str , UpperCAmelCase_ : int = 10 , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : bool = True , ) ->List[str]: """simple docstring""" snake_case_ = self.get_auto_remove_tmp_dir("""./xxx""" , after=UpperCAmelCase_ ) snake_case_ = F""" --model_name_or_path {model_name} --dataset_name hf-internal-testing/librispeech_asr_dummy --dataset_config_name clean --train_split_name validation --validation_split_name validation --output_dir {output_dir} --num_train_epochs {str(UpperCAmelCase_ )} --per_device_train_batch_size 2 --per_device_eval_batch_size 2 --evaluation_strategy steps --learning_rate 5e-4 --warmup_steps 8 --orthography timit --preprocessing_num_workers 1 --group_by_length --freeze_feature_extractor --report_to none --save_steps 0 --eval_steps {eval_steps} --report_to none """.split() if fpaa: args.extend(["""--fp16"""] ) # currently ds_config_wav2vec2_zero.json requires "zero_optimization.find_unused_parameters": true, # hence the separate config files snake_case_ = F"""--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json""".split() snake_case_ = [F"""{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py"""] snake_case_ = self.get_launcher(UpperCAmelCase_ ) snake_case_ = launcher + script + args + ds_args # keep for quick debug # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die execute_subprocess_async(UpperCAmelCase_ , env=self.get_env() ) return output_dir def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : Any=False ) ->Tuple: """simple docstring""" snake_case_ = min(2 , get_gpu_count() ) if distributed else 1 return F"""deepspeed --num_nodes 1 --num_gpus {num_gpus}""".split()
711
"""simple docstring""" import secrets from random import shuffle from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation def _a ( _SCREAMING_SNAKE_CASE = 8 ) -> str: snake_case_ = ascii_letters + digits + punctuation return "".join(secrets.choice(_SCREAMING_SNAKE_CASE ) for _ in range(_SCREAMING_SNAKE_CASE ) ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: # Password Generator = full boot with random_number, random_letters, and # random_character FUNCTIONS # Put your code here... i -= len(_SCREAMING_SNAKE_CASE ) snake_case_ = i // 3 snake_case_ = i % 3 # chars = chars_incl + random_letters(ascii_letters, i / 3 + remainder) + # random_number(digits, i / 3) + random_characters(punctuation, i / 3) snake_case_ = ( chars_incl + random(_SCREAMING_SNAKE_CASE , quotient + remainder ) + random(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) + random(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) snake_case_ = list(_SCREAMING_SNAKE_CASE ) shuffle(_SCREAMING_SNAKE_CASE ) return "".join(_SCREAMING_SNAKE_CASE ) # random is a generalised function for letters, characters and numbers def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: return "".join(secrets.choice(_SCREAMING_SNAKE_CASE ) for _ in range(_SCREAMING_SNAKE_CASE ) ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: pass # Put your code here... def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[str]: pass # Put your code here... def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[int]: pass # Put your code here... def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 8 ) -> bool: if len(_SCREAMING_SNAKE_CASE ) < min_length: # Your Password must be at least 8 characters long return False snake_case_ = any(char in ascii_uppercase for char in password ) snake_case_ = any(char in ascii_lowercase for char in password ) snake_case_ = any(char in digits for char in password ) snake_case_ = any(char in punctuation for char in password ) return upper and lower and num and spec_char # Passwords should contain UPPERCASE, lowerase # numbers, and special characters def _a ( ) -> str: snake_case_ = int(input("""Please indicate the max length of your password: """ ).strip() ) snake_case_ = input( """Please indicate the characters that must be in your password: """ ).strip() print("""Password generated:""" , password_generator(_SCREAMING_SNAKE_CASE ) ) print( """Alternative Password generated:""" , alternative_password_generator(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) , ) print("""[If you are thinking of using this passsword, You better save it.]""" ) if __name__ == "__main__": main()
2
0
"""simple docstring""" import inspect from typing import Callable, List, Optional, Union import torch from transformers import ( CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, WhisperForConditionalGeneration, WhisperProcessor, ) from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.utils import logging __SCREAMING_SNAKE_CASE : Union[str, Any] = logging.get_logger(__name__) # pylint: disable=invalid-name class __A (snake_case__): '''simple docstring''' def __init__( self : Tuple , UpperCAmelCase_ : WhisperForConditionalGeneration , UpperCAmelCase_ : WhisperProcessor , UpperCAmelCase_ : AutoencoderKL , UpperCAmelCase_ : CLIPTextModel , UpperCAmelCase_ : CLIPTokenizer , UpperCAmelCase_ : UNetaDConditionModel , UpperCAmelCase_ : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , UpperCAmelCase_ : StableDiffusionSafetyChecker , UpperCAmelCase_ : CLIPImageProcessor , ) ->Any: """simple docstring""" super().__init__() if safety_checker is None: logger.warning( F"""You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure""" """ that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered""" """ results in services or applications open to the public. Both the diffusers team and Hugging Face""" """ strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling""" """ it only for use-cases that involve analyzing network behavior or auditing its results. For more""" """ information, please have a look at https://github.com/huggingface/diffusers/pull/254 .""" ) self.register_modules( speech_model=UpperCAmelCase_ , speech_processor=UpperCAmelCase_ , vae=UpperCAmelCase_ , text_encoder=UpperCAmelCase_ , tokenizer=UpperCAmelCase_ , unet=UpperCAmelCase_ , scheduler=UpperCAmelCase_ , feature_extractor=UpperCAmelCase_ , ) def lowerCAmelCase ( self : Optional[Any] , UpperCAmelCase_ : Optional[Union[str, int]] = "auto" ) ->Dict: """simple docstring""" if slice_size == "auto": snake_case_ = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(UpperCAmelCase_ ) def lowerCAmelCase ( self : str ) ->List[Any]: """simple docstring""" self.enable_attention_slicing(UpperCAmelCase_ ) @torch.no_grad() def __call__( self : str , UpperCAmelCase_ : int , UpperCAmelCase_ : Any=16_000 , UpperCAmelCase_ : int = 512 , UpperCAmelCase_ : int = 512 , UpperCAmelCase_ : int = 50 , UpperCAmelCase_ : float = 7.5 , UpperCAmelCase_ : Optional[Union[str, List[str]]] = None , UpperCAmelCase_ : Optional[int] = 1 , UpperCAmelCase_ : float = 0.0 , UpperCAmelCase_ : Optional[torch.Generator] = None , UpperCAmelCase_ : Optional[torch.FloatTensor] = None , UpperCAmelCase_ : Optional[str] = "pil" , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , UpperCAmelCase_ : int = 1 , **UpperCAmelCase_ : int , ) ->Optional[int]: """simple docstring""" snake_case_ = self.speech_processor.feature_extractor( UpperCAmelCase_ , return_tensors="""pt""" , sampling_rate=UpperCAmelCase_ ).input_features.to(self.device ) snake_case_ = self.speech_model.generate(UpperCAmelCase_ , max_length=480_000 ) snake_case_ = self.speech_processor.tokenizer.batch_decode(UpperCAmelCase_ , skip_special_tokens=UpperCAmelCase_ , normalize=UpperCAmelCase_ )[ 0 ] if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): snake_case_ = 1 elif isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): snake_case_ = len(UpperCAmelCase_ ) else: raise ValueError(F"""`prompt` has to be of type `str` or `list` but is {type(UpperCAmelCase_ )}""" ) 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 (callback_steps is None) or ( callback_steps is not None and (not isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) or callback_steps <= 0) ): raise ValueError( F"""`callback_steps` has to be a positive integer but is {callback_steps} of type""" F""" {type(UpperCAmelCase_ )}.""" ) # get prompt text embeddings snake_case_ = self.tokenizer( UpperCAmelCase_ , padding="""max_length""" , max_length=self.tokenizer.model_max_length , return_tensors="""pt""" , ) snake_case_ = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: snake_case_ = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] ) logger.warning( """The following part of your input was truncated because CLIP can only handle sequences up to""" F""" {self.tokenizer.model_max_length} tokens: {removed_text}""" ) snake_case_ = text_input_ids[:, : self.tokenizer.model_max_length] snake_case_ = self.text_encoder(text_input_ids.to(self.device ) )[0] # duplicate text embeddings for each generation per prompt, using mps friendly method snake_case_ , snake_case_ , snake_case_ = text_embeddings.shape snake_case_ = text_embeddings.repeat(1 , UpperCAmelCase_ , 1 ) snake_case_ = text_embeddings.view(bs_embed * num_images_per_prompt , UpperCAmelCase_ , -1 ) # 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. snake_case_ = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: snake_case_ = 42 if negative_prompt is None: snake_case_ = [""""""] * batch_size elif type(UpperCAmelCase_ ) is not type(UpperCAmelCase_ ): raise TypeError( F"""`negative_prompt` should be the same type to `prompt`, but got {type(UpperCAmelCase_ )} !=""" F""" {type(UpperCAmelCase_ )}.""" ) elif isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): snake_case_ = [negative_prompt] elif batch_size != len(UpperCAmelCase_ ): raise ValueError( F"""`negative_prompt`: {negative_prompt} has batch size {len(UpperCAmelCase_ )}, but `prompt`:""" F""" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches""" """ the batch size of `prompt`.""" ) else: snake_case_ = negative_prompt snake_case_ = text_input_ids.shape[-1] snake_case_ = self.tokenizer( UpperCAmelCase_ , padding="""max_length""" , max_length=UpperCAmelCase_ , truncation=UpperCAmelCase_ , return_tensors="""pt""" , ) snake_case_ = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt, using mps friendly method snake_case_ = uncond_embeddings.shape[1] snake_case_ = uncond_embeddings.repeat(1 , UpperCAmelCase_ , 1 ) snake_case_ = uncond_embeddings.view(batch_size * num_images_per_prompt , UpperCAmelCase_ , -1 ) # 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 snake_case_ = 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`. snake_case_ = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8) snake_case_ = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not exist on mps snake_case_ = torch.randn(UpperCAmelCase_ , generator=UpperCAmelCase_ , device="""cpu""" , dtype=UpperCAmelCase_ ).to( self.device ) else: snake_case_ = torch.randn(UpperCAmelCase_ , generator=UpperCAmelCase_ , device=self.device , dtype=UpperCAmelCase_ ) else: if latents.shape != latents_shape: raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {latents_shape}""" ) snake_case_ = latents.to(self.device ) # set timesteps self.scheduler.set_timesteps(UpperCAmelCase_ ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand snake_case_ = self.scheduler.timesteps.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler snake_case_ = 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] snake_case_ = """eta""" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) snake_case_ = {} if accepts_eta: snake_case_ = eta for i, t in enumerate(self.progress_bar(UpperCAmelCase_ ) ): # expand the latents if we are doing classifier free guidance snake_case_ = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents snake_case_ = self.scheduler.scale_model_input(UpperCAmelCase_ , UpperCAmelCase_ ) # predict the noise residual snake_case_ = self.unet(UpperCAmelCase_ , UpperCAmelCase_ , encoder_hidden_states=UpperCAmelCase_ ).sample # perform guidance if do_classifier_free_guidance: snake_case_ , snake_case_ = noise_pred.chunk(2 ) snake_case_ = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # compute the previous noisy sample x_t -> x_t-1 snake_case_ = self.scheduler.step(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , **UpperCAmelCase_ ).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = 1 / 0.18_215 * latents snake_case_ = self.vae.decode(UpperCAmelCase_ ).sample snake_case_ = (image / 2 + 0.5).clamp(0 , 1 ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 snake_case_ = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": snake_case_ = self.numpy_to_pil(UpperCAmelCase_ ) if not return_dict: return image return StableDiffusionPipelineOutput(images=UpperCAmelCase_ , nsfw_content_detected=UpperCAmelCase_ )
712
"""simple docstring""" import json import os import tempfile import unittest import numpy as np from datasets import load_dataset 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 if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ImageGPTImageProcessor class __A (unittest.TestCase): '''simple docstring''' def __init__( self : int , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Tuple=7 , UpperCAmelCase_ : Dict=3 , UpperCAmelCase_ : Tuple=18 , UpperCAmelCase_ : Optional[Any]=30 , UpperCAmelCase_ : str=400 , UpperCAmelCase_ : int=True , UpperCAmelCase_ : Optional[int]=None , UpperCAmelCase_ : Optional[Any]=True , ) ->Optional[Any]: """simple docstring""" snake_case_ = size if size is not None else {"""height""": 18, """width""": 18} snake_case_ = parent snake_case_ = batch_size snake_case_ = num_channels snake_case_ = image_size snake_case_ = min_resolution snake_case_ = max_resolution snake_case_ = do_resize snake_case_ = size snake_case_ = do_normalize def lowerCAmelCase ( self : List[str] ) ->Optional[Any]: """simple docstring""" return { # here we create 2 clusters for the sake of simplicity "clusters": np.asarray( [ [0.8_866_443_634_033_203, 0.6_618_829_369_544_983, 0.3_891_746_401_786_804], [-0.6_042_559_146_881_104, -0.02_295_008_860_528_469, 0.5_423_797_369_003_296], ] ), "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, } @require_torch @require_vision class __A (snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: List[Any] = ImageGPTImageProcessor if is_vision_available() else None def lowerCAmelCase ( self : Optional[int] ) ->Optional[int]: """simple docstring""" snake_case_ = ImageGPTImageProcessingTester(self ) @property def lowerCAmelCase ( self : Tuple ) ->List[Any]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(UpperCAmelCase_ , """clusters""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """do_resize""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """size""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """do_normalize""" ) ) def lowerCAmelCase ( self : Optional[int] ) ->Optional[Any]: """simple docstring""" snake_case_ = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""height""": 18, """width""": 18} ) snake_case_ = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {"""height""": 42, """width""": 42} ) def lowerCAmelCase ( self : Any ) ->List[Any]: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) snake_case_ = json.loads(image_processor.to_json_string() ) for key, value in self.image_processor_dict.items(): if key == "clusters": self.assertTrue(np.array_equal(UpperCAmelCase_ , obj[key] ) ) else: self.assertEqual(obj[key] , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] ) ->Dict: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: snake_case_ = os.path.join(UpperCAmelCase_ , """image_processor.json""" ) image_processor_first.to_json_file(UpperCAmelCase_ ) snake_case_ = self.image_processing_class.from_json_file(UpperCAmelCase_ ).to_dict() snake_case_ = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(UpperCAmelCase_ , image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->List[Any]: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: image_processor_first.save_pretrained(UpperCAmelCase_ ) snake_case_ = self.image_processing_class.from_pretrained(UpperCAmelCase_ ).to_dict() snake_case_ = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(UpperCAmelCase_ , image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] , UpperCAmelCase_ ) @unittest.skip("""ImageGPT requires clusters at initialization""" ) def lowerCAmelCase ( self : List[Any] ) ->Tuple: """simple docstring""" pass def _a ( ) -> str: snake_case_ = load_dataset("""hf-internal-testing/fixtures_image_utils""" , split="""test""" ) snake_case_ = Image.open(dataset[4]["""file"""] ) snake_case_ = Image.open(dataset[5]["""file"""] ) snake_case_ = [imagea, imagea] return images @require_vision @require_torch class __A (unittest.TestCase): '''simple docstring''' @slow def lowerCAmelCase ( self : Tuple ) ->List[str]: """simple docstring""" snake_case_ = ImageGPTImageProcessor.from_pretrained("""openai/imagegpt-small""" ) snake_case_ = prepare_images() # test non-batched snake_case_ = image_processing(images[0] , return_tensors="""pt""" ) self.assertIsInstance(encoding.input_ids , torch.LongTensor ) self.assertEqual(encoding.input_ids.shape , (1, 1_024) ) snake_case_ = [306, 191, 191] self.assertEqual(encoding.input_ids[0, :3].tolist() , UpperCAmelCase_ ) # test batched snake_case_ = image_processing(UpperCAmelCase_ , return_tensors="""pt""" ) self.assertIsInstance(encoding.input_ids , torch.LongTensor ) self.assertEqual(encoding.input_ids.shape , (2, 1_024) ) snake_case_ = [303, 13, 13] self.assertEqual(encoding.input_ids[1, -3:].tolist() , UpperCAmelCase_ )
2
0
def _a ( _SCREAMING_SNAKE_CASE ) -> int: snake_case_ = 1 snake_case_ = 2 while i * i <= n: snake_case_ = 0 while n % i == 0: n //= i multiplicity += 1 n_divisors *= multiplicity + 1 i += 1 if n > 1: n_divisors *= 2 return n_divisors def _a ( ) -> Tuple: snake_case_ = 1 snake_case_ = 1 while True: i += 1 t_num += i if count_divisors(_SCREAMING_SNAKE_CASE ) > 500: break return t_num if __name__ == "__main__": print(solution())
713
"""simple docstring""" import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, ) from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST class __A : '''simple docstring''' def __init__( self : Optional[int] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[Any]=13 , UpperCAmelCase_ : Optional[int]=7 , UpperCAmelCase_ : List[str]=True , UpperCAmelCase_ : int=True , UpperCAmelCase_ : List[Any]=True , UpperCAmelCase_ : Optional[int]=True , UpperCAmelCase_ : List[str]=99 , UpperCAmelCase_ : Dict=24 , UpperCAmelCase_ : List[str]=2 , UpperCAmelCase_ : Optional[Any]=6 , UpperCAmelCase_ : int=37 , UpperCAmelCase_ : Optional[Any]="gelu" , UpperCAmelCase_ : Optional[Any]=0.1 , UpperCAmelCase_ : List[Any]=0.1 , UpperCAmelCase_ : Any=512 , UpperCAmelCase_ : str=16 , UpperCAmelCase_ : List[str]=2 , UpperCAmelCase_ : Optional[int]=0.02 , UpperCAmelCase_ : Tuple=3 , UpperCAmelCase_ : Union[str, Any]=None , UpperCAmelCase_ : Any=1_000 , ) ->Tuple: """simple docstring""" snake_case_ = parent snake_case_ = batch_size snake_case_ = seq_length snake_case_ = is_training snake_case_ = use_input_mask snake_case_ = use_token_type_ids snake_case_ = use_labels snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = max_position_embeddings snake_case_ = type_vocab_size snake_case_ = type_sequence_label_size snake_case_ = initializer_range snake_case_ = num_labels snake_case_ = scope snake_case_ = range_bbox def lowerCAmelCase ( self : Tuple ) ->int: """simple docstring""" snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case_ = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox ) # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: snake_case_ = bbox[i, j, 3] snake_case_ = bbox[i, j, 1] snake_case_ = t if bbox[i, j, 2] < bbox[i, j, 0]: snake_case_ = bbox[i, j, 2] snake_case_ = bbox[i, j, 0] snake_case_ = t snake_case_ = None if self.use_input_mask: snake_case_ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) snake_case_ = None if self.use_token_type_ids: snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) snake_case_ = None snake_case_ = None if self.use_labels: snake_case_ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) snake_case_ = self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def lowerCAmelCase ( self : int ) ->Optional[int]: """simple docstring""" return LiltConfig( 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 , ) def lowerCAmelCase ( self : Any , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Any , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[int] , ) ->str: """simple docstring""" snake_case_ = LiltModel(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ , bbox=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ ) snake_case_ = model(UpperCAmelCase_ , bbox=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ ) snake_case_ = model(UpperCAmelCase_ , bbox=UpperCAmelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def lowerCAmelCase ( self : int , UpperCAmelCase_ : str , UpperCAmelCase_ : Any , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : str , UpperCAmelCase_ : List[Any] , ) ->Dict: """simple docstring""" snake_case_ = self.num_labels snake_case_ = LiltForTokenClassification(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model( UpperCAmelCase_ , bbox=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowerCAmelCase ( self : Any , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : str , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : int , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : List[str] , ) ->Dict: """simple docstring""" snake_case_ = LiltForQuestionAnswering(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model( UpperCAmelCase_ , bbox=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , start_positions=UpperCAmelCase_ , end_positions=UpperCAmelCase_ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def lowerCAmelCase ( self : int ) ->Optional[int]: """simple docstring""" snake_case_ = self.prepare_config_and_inputs() ( ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ) = config_and_inputs snake_case_ = { """input_ids""": input_ids, """bbox""": bbox, """token_type_ids""": token_type_ids, """attention_mask""": input_mask, } return config, inputs_dict @require_torch class __A (snake_case__ , snake_case__ , snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Optional[int] = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) __lowercase: Optional[Any] = ( { """feature-extraction""": LiltModel, """question-answering""": LiltForQuestionAnswering, """text-classification""": LiltForSequenceClassification, """token-classification""": LiltForTokenClassification, """zero-shot""": LiltForSequenceClassification, } if is_torch_available() else {} ) __lowercase: Union[str, Any] = False __lowercase: List[str] = False def lowerCAmelCase ( self : str , UpperCAmelCase_ : int , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[int] ) ->Optional[int]: """simple docstring""" return True def lowerCAmelCase ( self : Dict ) ->Union[str, Any]: """simple docstring""" snake_case_ = LiltModelTester(self ) snake_case_ = ConfigTester(self , config_class=UpperCAmelCase_ , hidden_size=37 ) def lowerCAmelCase ( self : str ) ->List[Any]: """simple docstring""" self.config_tester.run_common_tests() def lowerCAmelCase ( self : List[str] ) ->int: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] ) ->List[str]: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: snake_case_ = type self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def lowerCAmelCase ( self : List[Any] ) ->Dict: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->Dict: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*UpperCAmelCase_ ) @slow def lowerCAmelCase ( self : Union[str, Any] ) ->Optional[int]: """simple docstring""" for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ = LiltModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) @require_torch @slow class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : Optional[int] ) ->Dict: """simple docstring""" snake_case_ = LiltModel.from_pretrained("""SCUT-DLVCLab/lilt-roberta-en-base""" ).to(UpperCAmelCase_ ) snake_case_ = torch.tensor([[1, 2]] , device=UpperCAmelCase_ ) snake_case_ = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=UpperCAmelCase_ ) # forward pass with torch.no_grad(): snake_case_ = model(input_ids=UpperCAmelCase_ , bbox=UpperCAmelCase_ ) snake_case_ = torch.Size([1, 2, 768] ) snake_case_ = torch.tensor( [[-0.0_653, 0.0_950, -0.0_061], [-0.0_545, 0.0_926, -0.0_324]] , device=UpperCAmelCase_ , ) self.assertTrue(outputs.last_hidden_state.shape , UpperCAmelCase_ ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , UpperCAmelCase_ , atol=1E-3 ) )
2
0
"""simple docstring""" import argparse import torch from torch import nn from transformers import SpeechaTextConfig, SpeechaTextForConditionalGeneration def _a ( _SCREAMING_SNAKE_CASE ) -> Tuple: snake_case_ = [ """encoder.version""", """decoder.version""", """model.encoder.version""", """model.decoder.version""", """decoder.output_projection.weight""", """_float_tensor""", """encoder.embed_positions._float_tensor""", """decoder.embed_positions._float_tensor""", ] for k in ignore_keys: state_dict.pop(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE ) -> List[str]: snake_case_ = list(s_dict.keys() ) for key in keys: if "transformer_layers" in key: snake_case_ = s_dict.pop(_SCREAMING_SNAKE_CASE ) elif "subsample" in key: snake_case_ = s_dict.pop(_SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE ) -> Optional[Any]: snake_case_ , snake_case_ = emb.weight.shape snake_case_ = nn.Linear(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , bias=_SCREAMING_SNAKE_CASE ) snake_case_ = emb.weight.data return lin_layer def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: snake_case_ = torch.load(_SCREAMING_SNAKE_CASE , map_location="""cpu""" ) snake_case_ = mam_aaa["""args"""] snake_case_ = mam_aaa["""model"""] snake_case_ = state_dict["""decoder.output_projection.weight"""] remove_ignore_keys_(_SCREAMING_SNAKE_CASE ) rename_keys(_SCREAMING_SNAKE_CASE ) snake_case_ = state_dict["""decoder.embed_tokens.weight"""].shape[0] snake_case_ = args.share_decoder_input_output_embed snake_case_ = [int(_SCREAMING_SNAKE_CASE ) for i in args.conv_kernel_sizes.split(""",""" )] snake_case_ = SpeechaTextConfig( vocab_size=_SCREAMING_SNAKE_CASE , max_source_positions=args.max_source_positions , max_target_positions=args.max_target_positions , encoder_layers=args.encoder_layers , decoder_layers=args.decoder_layers , encoder_attention_heads=args.encoder_attention_heads , decoder_attention_heads=args.decoder_attention_heads , encoder_ffn_dim=args.encoder_ffn_embed_dim , decoder_ffn_dim=args.decoder_ffn_embed_dim , d_model=args.encoder_embed_dim , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function="""relu""" , num_conv_layers=len(_SCREAMING_SNAKE_CASE ) , conv_channels=args.conv_channels , conv_kernel_sizes=_SCREAMING_SNAKE_CASE , input_feat_per_channel=args.input_feat_per_channel , input_channels=args.input_channels , tie_word_embeddings=_SCREAMING_SNAKE_CASE , num_beams=5 , max_length=200 , use_cache=_SCREAMING_SNAKE_CASE , decoder_start_token_id=2 , early_stopping=_SCREAMING_SNAKE_CASE , ) snake_case_ = SpeechaTextForConditionalGeneration(_SCREAMING_SNAKE_CASE ) snake_case_ , snake_case_ = model.model.load_state_dict(_SCREAMING_SNAKE_CASE , strict=_SCREAMING_SNAKE_CASE ) if len(_SCREAMING_SNAKE_CASE ) > 0 and not set(_SCREAMING_SNAKE_CASE ) <= { "encoder.embed_positions.weights", "decoder.embed_positions.weights", }: raise ValueError( """Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights` are allowed to be missing,""" f""" but all the following weights are missing {missing}""" ) if tie_embeds: snake_case_ = make_linear_from_emb(model.model.decoder.embed_tokens ) else: snake_case_ = lm_head_weights model.save_pretrained(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : int = argparse.ArgumentParser() # Required parameters parser.add_argument('--fairseq_path', type=str, help='Path to the fairseq model (.pt) file.') parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') __SCREAMING_SNAKE_CASE : str = parser.parse_args() convert_fairseq_sat_checkpoint_to_tfms(args.fairseq_path, args.pytorch_dump_folder_path)
714
"""simple docstring""" from __future__ import annotations def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> list[int]: snake_case_ = 0 snake_case_ = len(_SCREAMING_SNAKE_CASE ) - 1 while i < j: if nums[i] + nums[j] == target: return [i, j] elif nums[i] + nums[j] < target: snake_case_ = i + 1 else: snake_case_ = j - 1 return [] if __name__ == "__main__": import doctest doctest.testmod() print(f"""{two_pointer([2, 7, 11, 15], 9) = }""")
2
0
"""simple docstring""" import logging import os import sys from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import SeqaSeqTrainer from seqaseq_training_args import SeqaSeqTrainingArguments import transformers from transformers import ( AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer, HfArgumentParser, MBartTokenizer, MBartTokenizerFast, set_seed, ) from transformers.trainer_utils import EvaluationStrategy, is_main_process from transformers.training_args import ParallelMode from utils import ( SeqaSeqDataCollator, SeqaSeqDataset, assert_all_frozen, build_compute_metrics_fn, check_output_dir, freeze_embeds, freeze_params, lmap, save_json, use_task_specific_params, write_txt_file, ) __SCREAMING_SNAKE_CASE : int = logging.getLogger(__name__) @dataclass class __A : '''simple docstring''' __lowercase: str = field( metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""}) __lowercase: Optional[str] = field( default=snake_case__ , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""}) __lowercase: Optional[str] = field( default=snake_case__ , metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""}) __lowercase: Optional[str] = field( default=snake_case__ , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} , ) __lowercase: bool = field(default=snake_case__ , metadata={"""help""": """Whether tp freeze the encoder."""}) __lowercase: bool = field(default=snake_case__ , metadata={"""help""": """Whether to freeze the embeddings."""}) @dataclass class __A : '''simple docstring''' __lowercase: str = field( metadata={"""help""": """The input data dir. Should contain the .tsv files (or other data files) for the task."""}) __lowercase: Optional[str] = field( default="""summarization""" , metadata={"""help""": """Task name, summarization (or summarization_{dataset} for pegasus) or translation"""} , ) __lowercase: Optional[int] = field( default=10_24 , metadata={ """help""": ( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) __lowercase: Optional[int] = field( default=1_28 , metadata={ """help""": ( """The maximum total sequence length for target text after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) __lowercase: Optional[int] = field( default=1_42 , metadata={ """help""": ( """The maximum total sequence length for validation target text after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded. """ """This argument is also used to override the ``max_length`` param of ``model.generate``, which is used """ """during ``evaluate`` and ``predict``.""" ) } , ) __lowercase: Optional[int] = field( default=1_42 , metadata={ """help""": ( """The maximum total sequence length for test target text after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) __lowercase: Optional[int] = field(default=-1 , metadata={"""help""": """# training examples. -1 means use all."""}) __lowercase: Optional[int] = field(default=-1 , metadata={"""help""": """# validation examples. -1 means use all."""}) __lowercase: Optional[int] = field(default=-1 , metadata={"""help""": """# test examples. -1 means use all."""}) __lowercase: Optional[str] = field(default=snake_case__ , metadata={"""help""": """Source language id for translation."""}) __lowercase: Optional[str] = field(default=snake_case__ , metadata={"""help""": """Target language id for translation."""}) __lowercase: Optional[int] = field(default=snake_case__ , metadata={"""help""": """# num_beams to use for evaluation."""}) __lowercase: bool = field( default=snake_case__ , metadata={"""help""": """If only pad tokens should be ignored. This assumes that `config.pad_token_id` is defined."""} , ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[int]: logger.info(f"""***** {split} metrics *****""" ) for key in sorted(metrics.keys() ): logger.info(f""" {key} = {metrics[key]}""" ) save_json(_SCREAMING_SNAKE_CASE , os.path.join(_SCREAMING_SNAKE_CASE , f"""{split}_results.json""" ) ) def _a ( ) -> Union[str, Any]: # 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. snake_case_ = HfArgumentParser((ModelArguments, DataTrainingArguments, SeqaSeqTrainingArguments) ) 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. snake_case_ , snake_case_ , snake_case_ = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: snake_case_ , snake_case_ , snake_case_ = parser.parse_args_into_dataclasses() check_output_dir(_SCREAMING_SNAKE_CASE ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( """Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s""" , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.parallel_mode == ParallelMode.DISTRIBUTED ) , training_args.fpaa , ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # 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() logger.info("""Training/evaluation parameters %s""" , _SCREAMING_SNAKE_CASE ) # Set seed set_seed(training_args.seed ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. snake_case_ = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) snake_case_ = ("""encoder_layerdrop""", """decoder_layerdrop""", """dropout""", """attention_dropout""") for p in extra_model_params: if getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): assert hasattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ), f"""({config.__class__.__name__}) doesn't have a `{p}` attribute""" setattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) snake_case_ = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) snake_case_ = AutoModelForSeqaSeqLM.from_pretrained( model_args.model_name_or_path , from_tf=""".ckpt""" in model_args.model_name_or_path , config=_SCREAMING_SNAKE_CASE , cache_dir=model_args.cache_dir , ) # use task specific params use_task_specific_params(_SCREAMING_SNAKE_CASE , data_args.task ) # set num_beams for evaluation if data_args.eval_beams is None: snake_case_ = model.config.num_beams # set decoder_start_token_id for MBart if model.config.decoder_start_token_id is None and isinstance(_SCREAMING_SNAKE_CASE , (MBartTokenizer, MBartTokenizerFast) ): assert ( data_args.tgt_lang is not None and data_args.src_lang is not None ), "mBart requires --tgt_lang and --src_lang" if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): snake_case_ = tokenizer.lang_code_to_id[data_args.tgt_lang] else: snake_case_ = tokenizer.convert_tokens_to_ids(data_args.tgt_lang ) if model_args.freeze_embeds: freeze_embeds(_SCREAMING_SNAKE_CASE ) if model_args.freeze_encoder: freeze_params(model.get_encoder() ) assert_all_frozen(model.get_encoder() ) snake_case_ = SeqaSeqDataset # Get datasets snake_case_ = ( dataset_class( _SCREAMING_SNAKE_CASE , type_path="""train""" , data_dir=data_args.data_dir , n_obs=data_args.n_train , max_target_length=data_args.max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or """""" , ) if training_args.do_train else None ) snake_case_ = ( dataset_class( _SCREAMING_SNAKE_CASE , type_path="""val""" , data_dir=data_args.data_dir , n_obs=data_args.n_val , max_target_length=data_args.val_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or """""" , ) if training_args.do_eval or training_args.evaluation_strategy != EvaluationStrategy.NO else None ) snake_case_ = ( dataset_class( _SCREAMING_SNAKE_CASE , type_path="""test""" , data_dir=data_args.data_dir , n_obs=data_args.n_test , max_target_length=data_args.test_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or """""" , ) if training_args.do_predict else None ) # Initialize our Trainer snake_case_ = ( build_compute_metrics_fn(data_args.task , _SCREAMING_SNAKE_CASE ) if training_args.predict_with_generate else None ) snake_case_ = SeqaSeqTrainer( model=_SCREAMING_SNAKE_CASE , args=_SCREAMING_SNAKE_CASE , data_args=_SCREAMING_SNAKE_CASE , train_dataset=_SCREAMING_SNAKE_CASE , eval_dataset=_SCREAMING_SNAKE_CASE , data_collator=SeqaSeqDataCollator( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , model.config.decoder_start_token_id , training_args.tpu_num_cores ) , compute_metrics=_SCREAMING_SNAKE_CASE , tokenizer=_SCREAMING_SNAKE_CASE , ) snake_case_ = {} # Training if training_args.do_train: logger.info("""*** Train ***""" ) snake_case_ = trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) snake_case_ = train_result.metrics snake_case_ = data_args.n_train trainer.save_model() # this also saves the tokenizer if trainer.is_world_process_zero(): handle_metrics("""train""" , _SCREAMING_SNAKE_CASE , training_args.output_dir ) all_metrics.update(_SCREAMING_SNAKE_CASE ) # 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""" ) ) # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) tokenizer.save_pretrained(training_args.output_dir ) # Evaluation if training_args.do_eval: logger.info("""*** Evaluate ***""" ) snake_case_ = trainer.evaluate(metric_key_prefix="""val""" ) snake_case_ = data_args.n_val snake_case_ = round(metrics["""val_loss"""] , 4 ) if trainer.is_world_process_zero(): handle_metrics("""val""" , _SCREAMING_SNAKE_CASE , training_args.output_dir ) all_metrics.update(_SCREAMING_SNAKE_CASE ) if training_args.do_predict: logger.info("""*** Predict ***""" ) snake_case_ = trainer.predict(test_dataset=_SCREAMING_SNAKE_CASE , metric_key_prefix="""test""" ) snake_case_ = test_output.metrics snake_case_ = data_args.n_test if trainer.is_world_process_zero(): snake_case_ = round(metrics["""test_loss"""] , 4 ) handle_metrics("""test""" , _SCREAMING_SNAKE_CASE , training_args.output_dir ) all_metrics.update(_SCREAMING_SNAKE_CASE ) if training_args.predict_with_generate: snake_case_ = tokenizer.batch_decode( test_output.predictions , skip_special_tokens=_SCREAMING_SNAKE_CASE , clean_up_tokenization_spaces=_SCREAMING_SNAKE_CASE ) snake_case_ = lmap(str.strip , _SCREAMING_SNAKE_CASE ) write_txt_file(_SCREAMING_SNAKE_CASE , os.path.join(training_args.output_dir , """test_generations.txt""" ) ) if trainer.is_world_process_zero(): save_json(_SCREAMING_SNAKE_CASE , os.path.join(training_args.output_dir , """all_results.json""" ) ) return all_metrics def _a ( _SCREAMING_SNAKE_CASE ) -> str: # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
715
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __SCREAMING_SNAKE_CASE : Optional[Any] = { 'configuration_biogpt': ['BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BioGptConfig'], 'tokenization_biogpt': ['BioGptTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : Optional[Any] = [ 'BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST', 'BioGptForCausalLM', 'BioGptForTokenClassification', 'BioGptForSequenceClassification', 'BioGptModel', 'BioGptPreTrainedModel', ] if TYPE_CHECKING: from .configuration_biogpt import BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, BioGptConfig from .tokenization_biogpt import BioGptTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_biogpt import ( BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptPreTrainedModel, ) else: import sys __SCREAMING_SNAKE_CASE : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
2
0
"""simple docstring""" import os import pytest from attr import dataclass __SCREAMING_SNAKE_CASE : Tuple = 'us-east-1' # defaults region @dataclass class __A : '''simple docstring''' __lowercase: str __lowercase: Optional[Any] = """arn:aws:iam::558105141721:role/sagemaker_execution_role""" __lowercase: str = { """task_name""": """mnli""", """per_device_train_batch_size""": 16, """per_device_eval_batch_size""": 16, """do_train""": True, """do_eval""": True, """do_predict""": True, """output_dir""": """/opt/ml/model""", """overwrite_output_dir""": True, """max_steps""": 5_00, """save_steps""": 55_00, } __lowercase: Dict = {**hyperparameters, """max_steps""": 10_00} @property def lowerCAmelCase ( self : Any ) ->str: """simple docstring""" if self.framework == "pytorch": return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"eval_accuracy.*=\D*(.*?)$"}, {"Name": "eval_loss", "Regex": r"eval_loss.*=\D*(.*?)$"}, ] else: return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"loss.*=\D*(.*?)]?$"}, {"Name": "eval_loss", "Regex": r"sparse_categorical_accuracy.*=\D*(.*?)]?$"}, ] @property def lowerCAmelCase ( self : Optional[int] ) ->str: """simple docstring""" return F"""{self.framework}-transfromers-test""" @property def lowerCAmelCase ( self : Any ) ->str: """simple docstring""" return F"""./tests/sagemaker/scripts/{self.framework}""" @property def lowerCAmelCase ( self : Any ) ->str: """simple docstring""" if self.framework == "pytorch": return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-pytorch-training:1.7.1-transformers4.6.1-gpu-py36-cu110-ubuntu18.04" else: return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-tensorflow-training:2.4.1-transformers4.6.1-gpu-py37-cu110-ubuntu18.04" @pytest.fixture(scope="""class""" ) def _a ( _SCREAMING_SNAKE_CASE ) -> List[Any]: snake_case_ = SageMakerTestEnvironment(framework=request.cls.framework )
716
"""simple docstring""" __SCREAMING_SNAKE_CASE : str = 'Input must be a string of 8 numbers plus letter' __SCREAMING_SNAKE_CASE : Dict = 'TRWAGMYFPDXBNJZSQVHLCKE' def _a ( _SCREAMING_SNAKE_CASE ) -> bool: if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): snake_case_ = f"""Expected string as input, found {type(_SCREAMING_SNAKE_CASE ).__name__}""" raise TypeError(_SCREAMING_SNAKE_CASE ) snake_case_ = spanish_id.replace("""-""" , """""" ).upper() if len(_SCREAMING_SNAKE_CASE ) != 9: raise ValueError(_SCREAMING_SNAKE_CASE ) try: snake_case_ = int(spanish_id_clean[0:8] ) snake_case_ = spanish_id_clean[8] except ValueError as ex: raise ValueError(_SCREAMING_SNAKE_CASE ) from ex if letter.isdigit(): raise ValueError(_SCREAMING_SNAKE_CASE ) return letter == LOOKUP_LETTERS[number % 23] if __name__ == "__main__": import doctest doctest.testmod()
2
0
"""simple docstring""" from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __SCREAMING_SNAKE_CASE : int = {'configuration_mmbt': ['MMBTConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : List[Any] = ['MMBTForClassification', 'MMBTModel', 'ModalEmbeddings'] if TYPE_CHECKING: from .configuration_mmbt import MMBTConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mmbt import MMBTForClassification, MMBTModel, ModalEmbeddings else: import sys __SCREAMING_SNAKE_CASE : Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
717
"""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 logging __SCREAMING_SNAKE_CASE : List[str] = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Optional[int] = {'vocab_file': 'spiece.model'} __SCREAMING_SNAKE_CASE : List[str] = { 'vocab_file': { 'albert-base-v1': 'https://huggingface.co/albert-base-v1/resolve/main/spiece.model', 'albert-large-v1': 'https://huggingface.co/albert-large-v1/resolve/main/spiece.model', 'albert-xlarge-v1': 'https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model', 'albert-xxlarge-v1': 'https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model', 'albert-base-v2': 'https://huggingface.co/albert-base-v2/resolve/main/spiece.model', 'albert-large-v2': 'https://huggingface.co/albert-large-v2/resolve/main/spiece.model', 'albert-xlarge-v2': 'https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model', 'albert-xxlarge-v2': 'https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model', } } __SCREAMING_SNAKE_CASE : List[str] = { 'albert-base-v1': 512, 'albert-large-v1': 512, 'albert-xlarge-v1': 512, 'albert-xxlarge-v1': 512, 'albert-base-v2': 512, 'albert-large-v2': 512, 'albert-xlarge-v2': 512, 'albert-xxlarge-v2': 512, } __SCREAMING_SNAKE_CASE : int = '▁' class __A (snake_case__): '''simple docstring''' __lowercase: Optional[Any] = VOCAB_FILES_NAMES __lowercase: Optional[int] = PRETRAINED_VOCAB_FILES_MAP __lowercase: Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : int , UpperCAmelCase_ : Any , UpperCAmelCase_ : Dict=True , UpperCAmelCase_ : Dict=True , UpperCAmelCase_ : List[str]=False , UpperCAmelCase_ : List[Any]="[CLS]" , UpperCAmelCase_ : Any="[SEP]" , UpperCAmelCase_ : str="<unk>" , UpperCAmelCase_ : str="[SEP]" , UpperCAmelCase_ : Optional[Any]="<pad>" , UpperCAmelCase_ : Optional[int]="[CLS]" , UpperCAmelCase_ : int="[MASK]" , UpperCAmelCase_ : Optional[Dict[str, Any]] = None , **UpperCAmelCase_ : Union[str, Any] , ) ->None: """simple docstring""" snake_case_ = ( AddedToken(UpperCAmelCase_ , lstrip=UpperCAmelCase_ , rstrip=UpperCAmelCase_ , normalized=UpperCAmelCase_ ) if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) else mask_token ) snake_case_ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=UpperCAmelCase_ , remove_space=UpperCAmelCase_ , keep_accents=UpperCAmelCase_ , bos_token=UpperCAmelCase_ , eos_token=UpperCAmelCase_ , unk_token=UpperCAmelCase_ , sep_token=UpperCAmelCase_ , pad_token=UpperCAmelCase_ , cls_token=UpperCAmelCase_ , mask_token=UpperCAmelCase_ , sp_model_kwargs=self.sp_model_kwargs , **UpperCAmelCase_ , ) snake_case_ = do_lower_case snake_case_ = remove_space snake_case_ = keep_accents snake_case_ = vocab_file snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(UpperCAmelCase_ ) @property def lowerCAmelCase ( self : List[Any] ) ->Dict: """simple docstring""" return len(self.sp_model ) def lowerCAmelCase ( self : str ) ->List[Any]: """simple docstring""" snake_case_ = {self.convert_ids_to_tokens(UpperCAmelCase_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Dict ) ->List[str]: """simple docstring""" snake_case_ = self.__dict__.copy() snake_case_ = None return state def __setstate__( self : Tuple , UpperCAmelCase_ : Optional[int] ) ->Optional[int]: """simple docstring""" snake_case_ = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): snake_case_ = {} snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : Any ) ->str: """simple docstring""" if self.remove_space: snake_case_ = """ """.join(inputs.strip().split() ) else: snake_case_ = inputs snake_case_ = outputs.replace("""``""" , """\"""" ).replace("""''""" , """\"""" ) if not self.keep_accents: snake_case_ = unicodedata.normalize("""NFKD""" , UpperCAmelCase_ ) snake_case_ = """""".join([c for c in outputs if not unicodedata.combining(UpperCAmelCase_ )] ) if self.do_lower_case: snake_case_ = outputs.lower() return outputs def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : str ) ->List[str]: """simple docstring""" snake_case_ = self.preprocess_text(UpperCAmelCase_ ) snake_case_ = self.sp_model.encode(UpperCAmelCase_ , out_type=UpperCAmelCase_ ) snake_case_ = [] for piece in pieces: if len(UpperCAmelCase_ ) > 1 and piece[-1] == str(""",""" ) and piece[-2].isdigit(): snake_case_ = self.sp_model.EncodeAsPieces(piece[:-1].replace(UpperCAmelCase_ , """""" ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: snake_case_ = cur_pieces[1:] else: snake_case_ = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(UpperCAmelCase_ ) else: new_pieces.append(UpperCAmelCase_ ) return new_pieces def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : Optional[int] ) ->Dict: """simple docstring""" return self.sp_model.PieceToId(UpperCAmelCase_ ) def lowerCAmelCase ( self : str , UpperCAmelCase_ : Union[str, Any] ) ->Optional[int]: """simple docstring""" return self.sp_model.IdToPiece(UpperCAmelCase_ ) def lowerCAmelCase ( self : str , UpperCAmelCase_ : Dict ) ->Any: """simple docstring""" snake_case_ = [] snake_case_ = """""" snake_case_ = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(UpperCAmelCase_ ) + token snake_case_ = True snake_case_ = [] else: current_sub_tokens.append(UpperCAmelCase_ ) snake_case_ = False out_string += self.sp_model.decode(UpperCAmelCase_ ) return out_string.strip() def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ) ->List[int]: """simple docstring""" snake_case_ = [self.sep_token_id] snake_case_ = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None , UpperCAmelCase_ : bool = False ) ->List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=UpperCAmelCase_ , token_ids_a=UpperCAmelCase_ , already_has_special_tokens=UpperCAmelCase_ ) if token_ids_a is not None: return [1] + ([0] * len(UpperCAmelCase_ )) + [1] + ([0] * len(UpperCAmelCase_ )) + [1] return [1] + ([0] * len(UpperCAmelCase_ )) + [1] def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ) ->List[int]: """simple docstring""" snake_case_ = [self.sep_token_id] snake_case_ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def lowerCAmelCase ( self : str , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None ) ->Tuple[str]: """simple docstring""" if not os.path.isdir(UpperCAmelCase_ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return snake_case_ = os.path.join( UpperCAmelCase_ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCAmelCase_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , UpperCAmelCase_ ) elif not os.path.isfile(self.vocab_file ): with open(UpperCAmelCase_ , """wb""" ) as fi: snake_case_ = self.sp_model.serialized_model_proto() fi.write(UpperCAmelCase_ ) return (out_vocab_file,)
2
0
"""simple docstring""" from pathlib import Path import fire def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[Any]: snake_case_ = Path(_SCREAMING_SNAKE_CASE ) snake_case_ = Path(_SCREAMING_SNAKE_CASE ) dest_dir.mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) for path in src_dir.iterdir(): snake_case_ = [x.rstrip() for x in list(path.open().readlines() )][:n] snake_case_ = dest_dir.joinpath(path.name ) print(_SCREAMING_SNAKE_CASE ) dest_path.open("""w""" ).write("""\n""".join(_SCREAMING_SNAKE_CASE ) ) if __name__ == "__main__": fire.Fire(minify)
718
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE ) -> list: # bit count represents no. of bits in the gray code if bit_count < 0: raise ValueError("""The given input must be positive""" ) # get the generated string sequence snake_case_ = gray_code_sequence_string(_SCREAMING_SNAKE_CASE ) # # convert them to integers for i in range(len(_SCREAMING_SNAKE_CASE ) ): snake_case_ = int(sequence[i] , 2 ) return sequence def _a ( _SCREAMING_SNAKE_CASE ) -> list: # The approach is a recursive one # Base case achieved when either n = 0 or n=1 if bit_count == 0: return ["0"] if bit_count == 1: return ["0", "1"] snake_case_ = 1 << bit_count # defines the length of the sequence # 1<< n is equivalent to 2^n # recursive answer will generate answer for n-1 bits snake_case_ = gray_code_sequence_string(bit_count - 1 ) snake_case_ = [] # append 0 to first half of the smaller sequence generated for i in range(seq_len // 2 ): snake_case_ = """0""" + smaller_sequence[i] sequence.append(_SCREAMING_SNAKE_CASE ) # append 1 to second half ... start from the end of the list for i in reversed(range(seq_len // 2 ) ): snake_case_ = """1""" + smaller_sequence[i] sequence.append(_SCREAMING_SNAKE_CASE ) return sequence if __name__ == "__main__": import doctest doctest.testmod()
2
0
from pathlib import PurePosixPath from typing import Optional import fsspec from fsspec import AbstractFileSystem from huggingface_hub.hf_api import DatasetInfo from ..utils.file_utils import get_authentication_headers_for_url from ..utils.hub import hf_hub_url class __A (snake_case__): '''simple docstring''' __lowercase: Optional[int] = """""" __lowercase: Union[str, Any] = """hf-legacy""" # "hf://"" is reserved for hffs def __init__( self : Dict , UpperCAmelCase_ : Optional[DatasetInfo] = None , UpperCAmelCase_ : Optional[str] = None , **UpperCAmelCase_ : str , ) ->List[Any]: """simple docstring""" super().__init__(self , **UpperCAmelCase_ ) snake_case_ = repo_info snake_case_ = token snake_case_ = None def lowerCAmelCase ( self : int ) ->List[Any]: """simple docstring""" if self.dir_cache is None: snake_case_ = {} for hf_file in self.repo_info.siblings: # TODO(QL): add sizes snake_case_ = { """name""": hf_file.rfilename, """size""": None, """type""": """file""", } self.dir_cache.update( { str(UpperCAmelCase_ ): {"""name""": str(UpperCAmelCase_ ), """size""": None, """type""": """directory"""} for d in list(PurePosixPath(hf_file.rfilename ).parents )[:-1] } ) def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : str , UpperCAmelCase_ : str = "rb" , **UpperCAmelCase_ : List[Any] , ) ->Union[str, Any]: """simple docstring""" if not isinstance(self.repo_info , UpperCAmelCase_ ): raise NotImplementedError(F"""Open is only implemented for dataset repositories, but got {self.repo_info}""" ) snake_case_ = hf_hub_url(self.repo_info.id , UpperCAmelCase_ , revision=self.repo_info.sha ) return fsspec.open( UpperCAmelCase_ , mode=UpperCAmelCase_ , headers=get_authentication_headers_for_url(UpperCAmelCase_ , use_auth_token=self.token ) , client_kwargs={"""trust_env""": True} , ).open() def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : Tuple , **UpperCAmelCase_ : List[Any] ) ->Dict: """simple docstring""" self._get_dirs() snake_case_ = self._strip_protocol(UpperCAmelCase_ ) if path in self.dir_cache: return self.dir_cache[path] else: raise FileNotFoundError(UpperCAmelCase_ ) def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any]=False , **UpperCAmelCase_ : Dict ) ->List[str]: """simple docstring""" self._get_dirs() snake_case_ = PurePosixPath(path.strip("""/""" ) ) snake_case_ = {} for p, f in self.dir_cache.items(): snake_case_ = PurePosixPath(p.strip("""/""" ) ) snake_case_ = p.parent if root == path: snake_case_ = f snake_case_ = list(paths.values() ) if detail: return out else: return sorted(f["""name"""] for f in out )
719
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __SCREAMING_SNAKE_CASE : Optional[Any] = { 'configuration_megatron_bert': ['MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MegatronBertConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : Tuple = [ 'MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'MegatronBertForCausalLM', 'MegatronBertForMaskedLM', 'MegatronBertForMultipleChoice', 'MegatronBertForNextSentencePrediction', 'MegatronBertForPreTraining', 'MegatronBertForQuestionAnswering', 'MegatronBertForSequenceClassification', 'MegatronBertForTokenClassification', 'MegatronBertModel', 'MegatronBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_megatron_bert import MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MegatronBertConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_megatron_bert import ( MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, MegatronBertPreTrainedModel, ) else: import sys __SCREAMING_SNAKE_CASE : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
2
0
"""simple docstring""" from urllib.parse import quote import pytest from datasets.utils.hub import hf_hub_url @pytest.mark.parametrize("""repo_id""" , ["""canonical_dataset_name""", """org-name/dataset-name"""] ) @pytest.mark.parametrize("""path""" , ["""filename.csv""", """filename with blanks.csv"""] ) @pytest.mark.parametrize("""revision""" , [None, """v2"""] ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[int]: snake_case_ = hf_hub_url(repo_id=_SCREAMING_SNAKE_CASE , path=_SCREAMING_SNAKE_CASE , revision=_SCREAMING_SNAKE_CASE ) assert url == f"""https://huggingface.co/datasets/{repo_id}/resolve/{revision or "main"}/{quote(_SCREAMING_SNAKE_CASE )}"""
720
"""simple docstring""" import argparse import json import os from pathlib import Path import requests import torch from transformers import JukeboxConfig, JukeboxModel from transformers.utils import logging logging.set_verbosity_info() __SCREAMING_SNAKE_CASE : str = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Optional[int] = 'https://openaipublic.azureedge.net/jukebox/models/' __SCREAMING_SNAKE_CASE : List[Any] = { 'jukebox-1b-lyrics': [ '5b/vqvae.pth.tar', '5b/prior_level_0.pth.tar', '5b/prior_level_1.pth.tar', '1b_lyrics/prior_level_2.pth.tar', ], 'jukebox-5b-lyrics': [ '5b/vqvae.pth.tar', '5b/prior_level_0.pth.tar', '5b/prior_level_1.pth.tar', '5b_lyrics/prior_level_2.pth.tar', ], } def _a ( _SCREAMING_SNAKE_CASE ) -> int: if key.endswith(""".model.1.bias""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.1.bias""" , """.conv1d_1.bias""" ) elif key.endswith(""".model.1.weight""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.1.weight""" , """.conv1d_1.weight""" ) elif key.endswith(""".model.3.bias""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.3.bias""" , """.conv1d_2.bias""" ) elif key.endswith(""".model.3.weight""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.3.weight""" , """.conv1d_2.weight""" ) if "conditioner_blocks.0." in key: snake_case_ = key.replace("""conditioner_blocks.0""" , """conditioner_blocks""" ) if "prime_prior" in key: snake_case_ = key.replace("""prime_prior""" , """encoder""" ) if ".emb." in key and "total" not in key and "absolute" not in key and "relative" not in key: snake_case_ = key.replace(""".emb.""" , """.""" ) if key.endswith("""k""" ): # replace vqvae.X.k with vqvae.X.codebook return key.replace(""".k""" , """.codebook""" ) if "y_emb." in key: return key.replace("""y_emb.""" , """metadata_embedding.""" ) if "x_emb.emb." in key: snake_case_ = key.replace("""0.x_emb.emb""" , """embed_tokens""" ) if "prime_state_ln" in key: return key.replace("""prime_state_ln""" , """encoder.final_layer_norm""" ) if ".ln" in key: return key.replace(""".ln""" , """.layer_norm""" ) if "_ln" in key: return key.replace("""_ln""" , """_layer_norm""" ) if "prime_state_proj" in key: return key.replace("""prime_state_proj""" , """encoder.proj_in""" ) if "prime_x_out" in key: return key.replace("""prime_x_out""" , """encoder.lm_head""" ) if "prior.x_out" in key: return key.replace("""x_out""" , """fc_proj_out""" ) if "x_emb" in key: return key.replace("""x_emb""" , """embed_tokens""" ) return key def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: snake_case_ = {} import re snake_case_ = re.compile(r"""encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)""" ) snake_case_ = re.compile( r"""encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""encoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)""" ) snake_case_ = re.compile( r"""decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""decoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""conditioner_blocks.(\d*).cond.model.(\d*).(\d).(bias|weight)""" ) snake_case_ = re.compile( r"""conditioner_blocks.(\d*).cond.model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""conditioner_blocks.(\d*).cond.model.(\d*).(bias|weight)""" ) for original_key, value in state_dict.items(): # rename vqvae.encoder keys if re_encoder_block_conv_in.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_encoder_block_conv_in.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) snake_case_ = f"""encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.{groups[-1]}""" snake_case_ = re_encoder_block_conv_in.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_encoder_block_resnet.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_encoder_block_resnet.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) snake_case_ = {"""1""": 1, """3""": 2}[groups[-2]] snake_case_ = f"""encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.""" snake_case_ = f"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}""" snake_case_ = prefix + resnet_block snake_case_ = re_encoder_block_resnet.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_encoder_block_proj_out.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_encoder_block_proj_out.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = f"""encoders.{groups[0]}.level_blocks.{groups[1]}.proj_out.{groups[-1]}""" snake_case_ = re_encoder_block_proj_out.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # rename vqvae.decoder keys elif re_decoder_block_conv_out.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_decoder_block_conv_out.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) - 2 snake_case_ = f"""decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.{groups[-1]}""" snake_case_ = re_decoder_block_conv_out.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_decoder_block_resnet.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_decoder_block_resnet.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) - 2 snake_case_ = {"""1""": 1, """3""": 2}[groups[-2]] snake_case_ = f"""decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.""" snake_case_ = f"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}""" snake_case_ = prefix + resnet_block snake_case_ = re_decoder_block_resnet.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_decoder_block_proj_in.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_decoder_block_proj_in.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = f"""decoders.{groups[0]}.level_blocks.{groups[1]}.proj_in.{groups[-1]}""" snake_case_ = re_decoder_block_proj_in.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # rename prior cond.model to upsampler.upsample_block and resnet elif re_prior_cond_conv_out.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_prior_cond_conv_out.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[1] ) * 2 + int(groups[2] ) - 2 snake_case_ = f"""conditioner_blocks.upsampler.upsample_block.{block_index}.{groups[-1]}""" snake_case_ = re_prior_cond_conv_out.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_prior_cond_resnet.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_prior_cond_resnet.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[1] ) * 2 + int(groups[2] ) - 2 snake_case_ = {"""1""": 1, """3""": 2}[groups[-2]] snake_case_ = f"""conditioner_blocks.upsampler.upsample_block.{block_index}.""" snake_case_ = f"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}""" snake_case_ = prefix + resnet_block snake_case_ = re_prior_cond_resnet.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_prior_cond_proj_in.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_prior_cond_proj_in.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = f"""conditioner_blocks.upsampler.proj_in.{groups[-1]}""" snake_case_ = re_prior_cond_proj_in.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # keep original key else: snake_case_ = original_key snake_case_ = replace_key(_SCREAMING_SNAKE_CASE ) if f"""{key_prefix}.{key}""" not in model_state_dict or key is None: print(f"""failed converting {original_key} to {key}, does not match""" ) # handle missmatched shape elif value.shape != model_state_dict[f"""{key_prefix}.{key}"""].shape: snake_case_ = model_state_dict[f"""{key_prefix}.{key}"""] print(f"""{original_key}-> {key} : \nshape {val.shape} and { value.shape}, do not match""" ) snake_case_ = original_key snake_case_ = original_key snake_case_ = value return new_dict @torch.no_grad() def _a ( _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> Optional[int]: for file in MODEL_MAPPING[model_name]: if not os.path.isfile(f"""{pytorch_dump_folder_path}/{file.split("/" )[-1]}""" ): snake_case_ = requests.get(f"""{PREFIX}{file}""" , allow_redirects=_SCREAMING_SNAKE_CASE ) os.makedirs(f"""{pytorch_dump_folder_path}/""" , exist_ok=_SCREAMING_SNAKE_CASE ) open(f"""{pytorch_dump_folder_path}/{file.split("/" )[-1]}""" , """wb""" ).write(r.content ) snake_case_ = MODEL_MAPPING[model_name.split("""/""" )[-1]] snake_case_ = JukeboxConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) snake_case_ = JukeboxModel(_SCREAMING_SNAKE_CASE ) snake_case_ = [] snake_case_ = {} for i, dict_name in enumerate(_SCREAMING_SNAKE_CASE ): snake_case_ = torch.load(f"""{pytorch_dump_folder_path}/{dict_name.split("/" )[-1]}""" )["""model"""] snake_case_ = {} for k in old_dic.keys(): if k.endswith(""".b""" ): snake_case_ = old_dic[k] elif k.endswith(""".w""" ): snake_case_ = old_dic[k] elif "level_2" not in dict_name and "cond.model." in k: snake_case_ = old_dic[k] else: snake_case_ = old_dic[k] snake_case_ = """vqvae""" if i == 0 else f"""priors.{3 - i}""" snake_case_ = fix_jukebox_keys(_SCREAMING_SNAKE_CASE , model.state_dict() , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) weight_dict.append(_SCREAMING_SNAKE_CASE ) snake_case_ = weight_dict.pop(0 ) model.vqvae.load_state_dict(_SCREAMING_SNAKE_CASE ) for i in range(len(_SCREAMING_SNAKE_CASE ) ): model.priors[i].load_state_dict(weight_dict[2 - i] ) Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) with open(f"""{pytorch_dump_folder_path}/mapping.json""" , """w""" ) as txtfile: json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) print(f"""Saving model {model_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) return weight_dict if __name__ == "__main__": __SCREAMING_SNAKE_CASE : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='jukebox-5b-lyrics', type=str, help='Name of the model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default='jukebox-5b-lyrics-converted', type=str, help='Path to the output PyTorch model directory.', ) __SCREAMING_SNAKE_CASE : str = parser.parse_args() convert_openai_checkpoint(args.model_name, args.pytorch_dump_folder_path)
2
0
"""simple docstring""" from .configuration_bert_masked import MaskedBertConfig from .modeling_bert_masked import ( MaskedBertForMultipleChoice, MaskedBertForQuestionAnswering, MaskedBertForSequenceClassification, MaskedBertForTokenClassification, MaskedBertModel, ) from .modules import *
721
"""simple docstring""" # XXX: we want transformers master here - in the absense of conftest manipulating sys.path: # hack it in for now: import sys from pathlib import Path __SCREAMING_SNAKE_CASE : Union[str, Any] = Path(__file__).resolve().parents[3] / 'src' sys.path.insert(1, str(git_repo_path)) import dataclasses # noqa import io # noqa import itertools # noqa import json # noqa import os # noqa import unittest # noqa from copy import deepcopy # noqa from parameterized import parameterized # noqa from transformers import TrainingArguments, is_torch_available # noqa from transformers.deepspeed import is_deepspeed_available # noqa from transformers.file_utils import WEIGHTS_NAME # noqa from transformers.testing_utils import ( # noqa CaptureLogger, ExtendSysPath, TestCasePlus, execute_subprocess_async, get_gpu_count, mockenv_context, require_deepspeed, require_torch_gpu, require_torch_multi_gpu, slow, ) from transformers.trainer_utils import set_seed # noqa set_seed(42) __SCREAMING_SNAKE_CASE : Dict = {'base': 'patrickvonplaten/wav2vec2_tiny_random', 'robust': 'patrickvonplaten/wav2vec2_tiny_random_robust'} __SCREAMING_SNAKE_CASE : Dict = 'zero2' __SCREAMING_SNAKE_CASE : List[Any] = 'zero3' __SCREAMING_SNAKE_CASE : int = [ZEROa, ZEROa] def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: # customize the test name generator function as we want both params to appear in the sub-test # name, as by default it shows only the first param snake_case_ = parameterized.to_safe_name("""_""".join(str(_SCREAMING_SNAKE_CASE ) for x in param.args ) ) return f"""{func.__name__}_{param_based_name}""" # Cartesian-product of zero stages with models to test __SCREAMING_SNAKE_CASE : Dict = list(itertools.product(stages, models.keys())) @slow @require_deepspeed @require_torch_gpu class __A (snake_case__): '''simple docstring''' @parameterized.expand(UpperCAmelCase_ , name_func=UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Union[str, Any] ) ->Any: """simple docstring""" self.run_and_check( stage=UpperCAmelCase_ , model=UpperCAmelCase_ , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) @require_torch_multi_gpu @parameterized.expand(UpperCAmelCase_ , name_func=UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[Any] ) ->Optional[Any]: """simple docstring""" self.run_and_check( stage=UpperCAmelCase_ , model=UpperCAmelCase_ , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) @parameterized.expand(UpperCAmelCase_ , name_func=UpperCAmelCase_ ) def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[int] ) ->List[str]: """simple docstring""" self.run_and_check( stage=UpperCAmelCase_ , model=UpperCAmelCase_ , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) @require_torch_multi_gpu @parameterized.expand(UpperCAmelCase_ , name_func=UpperCAmelCase_ ) def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : str , UpperCAmelCase_ : List[Any] ) ->Optional[int]: """simple docstring""" self.run_and_check( stage=UpperCAmelCase_ , model=UpperCAmelCase_ , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : Union[str, Any] ) ->Optional[int]: """simple docstring""" pass def lowerCAmelCase ( self : Any , UpperCAmelCase_ : str , UpperCAmelCase_ : str , UpperCAmelCase_ : int = 10 , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : bool = True , ) ->List[str]: """simple docstring""" snake_case_ = models[model] snake_case_ = self.run_trainer( stage=UpperCAmelCase_ , model_name=UpperCAmelCase_ , eval_steps=UpperCAmelCase_ , num_train_epochs=1 , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) self.do_checks(UpperCAmelCase_ ) return output_dir def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : str , UpperCAmelCase_ : int = 10 , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : bool = True , ) ->List[str]: """simple docstring""" snake_case_ = self.get_auto_remove_tmp_dir("""./xxx""" , after=UpperCAmelCase_ ) snake_case_ = F""" --model_name_or_path {model_name} --dataset_name hf-internal-testing/librispeech_asr_dummy --dataset_config_name clean --train_split_name validation --validation_split_name validation --output_dir {output_dir} --num_train_epochs {str(UpperCAmelCase_ )} --per_device_train_batch_size 2 --per_device_eval_batch_size 2 --evaluation_strategy steps --learning_rate 5e-4 --warmup_steps 8 --orthography timit --preprocessing_num_workers 1 --group_by_length --freeze_feature_extractor --report_to none --save_steps 0 --eval_steps {eval_steps} --report_to none """.split() if fpaa: args.extend(["""--fp16"""] ) # currently ds_config_wav2vec2_zero.json requires "zero_optimization.find_unused_parameters": true, # hence the separate config files snake_case_ = F"""--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json""".split() snake_case_ = [F"""{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py"""] snake_case_ = self.get_launcher(UpperCAmelCase_ ) snake_case_ = launcher + script + args + ds_args # keep for quick debug # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die execute_subprocess_async(UpperCAmelCase_ , env=self.get_env() ) return output_dir def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : Any=False ) ->Tuple: """simple docstring""" snake_case_ = min(2 , get_gpu_count() ) if distributed else 1 return F"""deepspeed --num_nodes 1 --num_gpus {num_gpus}""".split()
2
0
"""simple docstring""" import os from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen, xsplitext from ..table import array_cast from ..utils.py_utils import no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: from .features import FeatureType __SCREAMING_SNAKE_CASE : Dict = False, False, False @dataclass class __A : '''simple docstring''' __lowercase: Optional[int] = None __lowercase: bool = True __lowercase: bool = True __lowercase: Optional[str] = None # Automatically constructed __lowercase: ClassVar[str] = "dict" __lowercase: ClassVar[Any] = pa.struct({"""bytes""": pa.binary(), """path""": pa.string()}) __lowercase: str = field(default="""Audio""" , init=snake_case__ , repr=snake_case__) def __call__( self : Optional[Any] ) ->Optional[int]: """simple docstring""" return self.pa_type def lowerCAmelCase ( self : int , UpperCAmelCase_ : Union[str, bytes, dict] ) ->dict: """simple docstring""" try: import soundfile as sf # soundfile is a dependency of librosa, needed to decode audio files. except ImportError as err: raise ImportError("""To support encoding audio data, please install 'soundfile'.""" ) from err if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): return {"bytes": None, "path": value} elif isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): return {"bytes": value, "path": None} elif "array" in value: # convert the audio array to wav bytes snake_case_ = BytesIO() sf.write(UpperCAmelCase_ , value["""array"""] , value["""sampling_rate"""] , format="""wav""" ) return {"bytes": buffer.getvalue(), "path": None} elif value.get("""path""" ) is not None and os.path.isfile(value["""path"""] ): # we set "bytes": None to not duplicate the data if they're already available locally if value["path"].endswith("""pcm""" ): # "PCM" only has raw audio bytes if value.get("""sampling_rate""" ) is None: # At least, If you want to convert "PCM-byte" to "WAV-byte", you have to know sampling rate raise KeyError("""To use PCM files, please specify a 'sampling_rate' in Audio object""" ) if value.get("""bytes""" ): # If we already had PCM-byte, we don`t have to make "read file, make bytes" (just use it!) snake_case_ = np.frombuffer(value["""bytes"""] , dtype=np.intaa ).astype(np.floataa ) / 32_767 else: snake_case_ = np.memmap(value["""path"""] , dtype="""h""" , mode="""r""" ).astype(np.floataa ) / 32_767 snake_case_ = BytesIO(bytes() ) sf.write(UpperCAmelCase_ , UpperCAmelCase_ , value["""sampling_rate"""] , format="""wav""" ) return {"bytes": buffer.getvalue(), "path": None} else: return {"bytes": None, "path": value.get("""path""" )} elif value.get("""bytes""" ) is not None or value.get("""path""" ) is not None: # store the audio bytes, and path is used to infer the audio format using the file extension return {"bytes": value.get("""bytes""" ), "path": value.get("""path""" )} else: raise ValueError( F"""An audio sample should have one of 'path' or 'bytes' but they are missing or None in {value}.""" ) def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : dict , UpperCAmelCase_ : Optional[Dict[str, Union[str, bool, None]]] = None ) ->dict: """simple docstring""" if not self.decode: raise RuntimeError("""Decoding is disabled for this feature. Please use Audio(decode=True) instead.""" ) snake_case_ , snake_case_ = (value["""path"""], BytesIO(value["""bytes"""] )) if value["""bytes"""] is not None else (value["""path"""], None) if path is None and file is None: raise ValueError(F"""An audio sample should have one of 'path' or 'bytes' but both are None in {value}.""" ) try: import librosa import soundfile as sf except ImportError as err: raise ImportError("""To support decoding audio files, please install 'librosa' and 'soundfile'.""" ) from err snake_case_ = xsplitext(UpperCAmelCase_ )[1][1:].lower() if path is not None else None if not config.IS_OPUS_SUPPORTED and audio_format == "opus": raise RuntimeError( """Decoding 'opus' files requires system library 'libsndfile'>=1.0.31, """ """You can try to update `soundfile` python library: `pip install \"soundfile>=0.12.1\"`. """ ) elif not config.IS_MP3_SUPPORTED and audio_format == "mp3": raise RuntimeError( """Decoding 'mp3' files requires system library 'libsndfile'>=1.1.0, """ """You can try to update `soundfile` python library: `pip install \"soundfile>=0.12.1\"`. """ ) if file is None: snake_case_ = token_per_repo_id or {} snake_case_ = path.split("""::""" )[-1] try: snake_case_ = string_to_dict(UpperCAmelCase_ , config.HUB_DATASETS_URL )["""repo_id"""] snake_case_ = token_per_repo_id[repo_id] except (ValueError, KeyError): snake_case_ = None with xopen(UpperCAmelCase_ , """rb""" , use_auth_token=UpperCAmelCase_ ) as f: snake_case_ , snake_case_ = sf.read(UpperCAmelCase_ ) else: snake_case_ , snake_case_ = sf.read(UpperCAmelCase_ ) snake_case_ = array.T if self.mono: snake_case_ = librosa.to_mono(UpperCAmelCase_ ) if self.sampling_rate and self.sampling_rate != sampling_rate: snake_case_ = librosa.resample(UpperCAmelCase_ , orig_sr=UpperCAmelCase_ , target_sr=self.sampling_rate ) snake_case_ = self.sampling_rate return {"path": path, "array": array, "sampling_rate": sampling_rate} def lowerCAmelCase ( self : Dict ) ->Union["FeatureType", Dict[str, "FeatureType"]]: """simple docstring""" from .features import Value if self.decode: raise ValueError("""Cannot flatten a decoded Audio feature.""" ) return { "bytes": Value("""binary""" ), "path": Value("""string""" ), } def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : Union[pa.StringArray, pa.StructArray] ) ->pa.StructArray: """simple docstring""" if pa.types.is_string(storage.type ): snake_case_ = pa.array([None] * len(UpperCAmelCase_ ) , type=pa.binary() ) snake_case_ = pa.StructArray.from_arrays([bytes_array, storage] , ["""bytes""", """path"""] , mask=storage.is_null() ) elif pa.types.is_binary(storage.type ): snake_case_ = pa.array([None] * len(UpperCAmelCase_ ) , type=pa.string() ) snake_case_ = pa.StructArray.from_arrays([storage, path_array] , ["""bytes""", """path"""] , mask=storage.is_null() ) elif pa.types.is_struct(storage.type ) and storage.type.get_all_field_indices("""array""" ): snake_case_ = pa.array([Audio().encode_example(UpperCAmelCase_ ) if x is not None else None for x in storage.to_pylist()] ) elif pa.types.is_struct(storage.type ): if storage.type.get_field_index("""bytes""" ) >= 0: snake_case_ = storage.field("""bytes""" ) else: snake_case_ = pa.array([None] * len(UpperCAmelCase_ ) , type=pa.binary() ) if storage.type.get_field_index("""path""" ) >= 0: snake_case_ = storage.field("""path""" ) else: snake_case_ = pa.array([None] * len(UpperCAmelCase_ ) , type=pa.string() ) snake_case_ = pa.StructArray.from_arrays([bytes_array, path_array] , ["""bytes""", """path"""] , mask=storage.is_null() ) return array_cast(UpperCAmelCase_ , self.pa_type ) def lowerCAmelCase ( self : Optional[Any] , UpperCAmelCase_ : pa.StructArray ) ->pa.StructArray: """simple docstring""" @no_op_if_value_is_null def path_to_bytes(UpperCAmelCase_ : Dict ): with xopen(UpperCAmelCase_ , """rb""" ) as f: snake_case_ = f.read() return bytes_ snake_case_ = pa.array( [ (path_to_bytes(x["""path"""] ) if x["""bytes"""] is None else x["""bytes"""]) if x is not None else None for x in storage.to_pylist() ] , type=pa.binary() , ) snake_case_ = pa.array( [os.path.basename(UpperCAmelCase_ ) if path is not None else None for path in storage.field("""path""" ).to_pylist()] , type=pa.string() , ) snake_case_ = pa.StructArray.from_arrays([bytes_array, path_array] , ["""bytes""", """path"""] , mask=bytes_array.is_null() ) return array_cast(UpperCAmelCase_ , self.pa_type )
700
"""simple docstring""" import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, Features, Value from .base import TaskTemplate @dataclass(frozen=snake_case__) class __A (snake_case__): '''simple docstring''' __lowercase: str = field(default="""automatic-speech-recognition""" , metadata={"""include_in_asdict_even_if_is_default""": True}) __lowercase: ClassVar[Features] = Features({"""audio""": Audio()}) __lowercase: ClassVar[Features] = Features({"""transcription""": Value("""string""")}) __lowercase: str = "audio" __lowercase: str = "transcription" def lowerCAmelCase ( self : List[Any] , UpperCAmelCase_ : Any ) ->int: """simple docstring""" if self.audio_column not in features: raise ValueError(F"""Column {self.audio_column} is not present in features.""" ) if not isinstance(features[self.audio_column] , UpperCAmelCase_ ): raise ValueError(F"""Column {self.audio_column} is not an Audio type.""" ) snake_case_ = copy.deepcopy(self ) snake_case_ = self.input_schema.copy() snake_case_ = features[self.audio_column] snake_case_ = input_schema return task_template @property def lowerCAmelCase ( self : List[str] ) ->Dict[str, str]: """simple docstring""" return {self.audio_column: "audio", self.transcription_column: "transcription"}
2
0
"""simple docstring""" import inspect import unittest from transformers import ConvNextVaConfig from transformers.models.auto import get_values from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES 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 transformers import ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __A : '''simple docstring''' def __init__( self : Optional[int] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[int]=13 , UpperCAmelCase_ : str=32 , UpperCAmelCase_ : List[Any]=3 , UpperCAmelCase_ : Optional[Any]=4 , UpperCAmelCase_ : Dict=[10, 20, 30, 40] , UpperCAmelCase_ : List[Any]=[2, 2, 3, 2] , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : Any=37 , UpperCAmelCase_ : str="gelu" , UpperCAmelCase_ : Optional[int]=10 , UpperCAmelCase_ : Dict=0.02 , UpperCAmelCase_ : int=["stage2", "stage3", "stage4"] , UpperCAmelCase_ : Optional[int]=[2, 3, 4] , UpperCAmelCase_ : List[str]=None , ) ->Union[str, Any]: """simple docstring""" snake_case_ = parent snake_case_ = batch_size snake_case_ = image_size snake_case_ = num_channels snake_case_ = num_stages snake_case_ = hidden_sizes snake_case_ = depths snake_case_ = is_training snake_case_ = use_labels snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = num_labels snake_case_ = initializer_range snake_case_ = out_features snake_case_ = out_indices snake_case_ = scope def lowerCAmelCase ( self : List[str] ) ->str: """simple docstring""" snake_case_ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case_ = None if self.use_labels: snake_case_ = ids_tensor([self.batch_size] , self.num_labels ) snake_case_ = self.get_config() return config, pixel_values, labels def lowerCAmelCase ( self : Dict ) ->Optional[int]: """simple docstring""" return ConvNextVaConfig( num_channels=self.num_channels , hidden_sizes=self.hidden_sizes , depths=self.depths , num_stages=self.num_stages , hidden_act=self.hidden_act , is_decoder=UpperCAmelCase_ , initializer_range=self.initializer_range , out_features=self.out_features , out_indices=self.out_indices , num_labels=self.num_labels , ) def lowerCAmelCase ( self : List[Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Optional[Any] ) ->List[Any]: """simple docstring""" snake_case_ = ConvNextVaModel(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[Any] ) ->Any: """simple docstring""" snake_case_ = ConvNextVaForImageClassification(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCAmelCase ( self : Optional[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Union[str, Any] ) ->Tuple: """simple docstring""" snake_case_ = ConvNextVaBackbone(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ ) # verify hidden states self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:] ) # verify backbone works with out_features=None snake_case_ = None snake_case_ = ConvNextVaBackbone(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" snake_case_ = self.prepare_config_and_inputs() snake_case_ , snake_case_ , snake_case_ = config_and_inputs snake_case_ = {"""pixel_values""": pixel_values} return config, inputs_dict def lowerCAmelCase ( self : List[str] ) ->Union[str, Any]: """simple docstring""" snake_case_ = self.prepare_config_and_inputs() snake_case_ , snake_case_ , snake_case_ = config_and_inputs snake_case_ = {"""pixel_values""": pixel_values, """labels""": labels} return config, inputs_dict @require_torch class __A (snake_case__ , snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Optional[Any] = ( ( ConvNextVaModel, ConvNextVaForImageClassification, ConvNextVaBackbone, ) if is_torch_available() else () ) __lowercase: Union[str, Any] = ( {"""feature-extraction""": ConvNextVaModel, """image-classification""": ConvNextVaForImageClassification} if is_torch_available() else {} ) __lowercase: Union[str, Any] = False __lowercase: Optional[Any] = False __lowercase: Any = False __lowercase: Union[str, Any] = False __lowercase: Dict = False def lowerCAmelCase ( self : Union[str, Any] ) ->Tuple: """simple docstring""" snake_case_ = ConvNextVaModelTester(self ) snake_case_ = ConfigTester(self , config_class=UpperCAmelCase_ , has_text_modality=UpperCAmelCase_ , hidden_size=37 ) def lowerCAmelCase ( self : List[Any] ) ->Optional[Any]: """simple docstring""" 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 lowerCAmelCase ( self : str ) ->Optional[Any]: """simple docstring""" return @unittest.skip(reason="""ConvNextV2 does not use inputs_embeds""" ) def lowerCAmelCase ( self : Optional[int] ) ->Union[str, Any]: """simple docstring""" pass @unittest.skip(reason="""ConvNextV2 does not support input and output embeddings""" ) def lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" pass @unittest.skip(reason="""ConvNextV2 does not use feedforward chunking""" ) def lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" pass def lowerCAmelCase ( self : Dict ) ->Optional[int]: """simple docstring""" if not self.model_tester.is_training: return for model_class in self.all_model_classes: snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_with_labels() snake_case_ = True if model_class.__name__ in [ *get_values(UpperCAmelCase_ ), *get_values(UpperCAmelCase_ ), ]: continue snake_case_ = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.train() snake_case_ = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ , return_labels=UpperCAmelCase_ ) snake_case_ = model(**UpperCAmelCase_ ).loss loss.backward() def lowerCAmelCase ( self : Optional[int] ) ->Any: """simple docstring""" if not self.model_tester.is_training: return for model_class in self.all_model_classes: snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_with_labels() snake_case_ = False snake_case_ = True if ( model_class.__name__ in [*get_values(UpperCAmelCase_ ), *get_values(UpperCAmelCase_ )] or not model_class.supports_gradient_checkpointing ): continue snake_case_ = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.gradient_checkpointing_enable() model.train() snake_case_ = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ , return_labels=UpperCAmelCase_ ) snake_case_ = model(**UpperCAmelCase_ ).loss loss.backward() def lowerCAmelCase ( self : List[Any] ) ->Union[str, Any]: """simple docstring""" snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ = model_class(UpperCAmelCase_ ) snake_case_ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case_ = [*signature.parameters.keys()] snake_case_ = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] ) ->Union[str, Any]: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->Dict: """simple docstring""" def check_hidden_states_output(UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : str ): snake_case_ = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() with torch.no_grad(): snake_case_ = model(**self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) ) snake_case_ = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states snake_case_ = self.model_tester.num_stages self.assertEqual(len(UpperCAmelCase_ ) , expected_num_stages + 1 ) # ConvNextV2's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ = True check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] snake_case_ = True check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] ) ->Dict: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_ ) @slow def lowerCAmelCase ( self : Tuple ) ->str: """simple docstring""" for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ = ConvNextVaModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) def _a ( ) -> str: snake_case_ = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class __A (unittest.TestCase): '''simple docstring''' @cached_property def lowerCAmelCase ( self : Union[str, Any] ) ->Optional[int]: """simple docstring""" return AutoImageProcessor.from_pretrained("""facebook/convnextv2-tiny-1k-224""" ) if is_vision_available() else None @slow def lowerCAmelCase ( self : Tuple ) ->int: """simple docstring""" snake_case_ = ConvNextVaForImageClassification.from_pretrained("""facebook/convnextv2-tiny-1k-224""" ).to(UpperCAmelCase_ ) snake_case_ = self.default_image_processor snake_case_ = prepare_img() snake_case_ = preprocessor(images=UpperCAmelCase_ , return_tensors="""pt""" ).to(UpperCAmelCase_ ) # forward pass with torch.no_grad(): snake_case_ = model(**UpperCAmelCase_ ) # verify the logits snake_case_ = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape , UpperCAmelCase_ ) snake_case_ = torch.tensor([0.9_996, 0.1_966, -0.4_386] ).to(UpperCAmelCase_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCAmelCase_ , atol=1E-4 ) )
701
"""simple docstring""" from functools import reduce __SCREAMING_SNAKE_CASE : Tuple = ( '73167176531330624919225119674426574742355349194934' '96983520312774506326239578318016984801869478851843' '85861560789112949495459501737958331952853208805511' '12540698747158523863050715693290963295227443043557' '66896648950445244523161731856403098711121722383113' '62229893423380308135336276614282806444486645238749' '30358907296290491560440772390713810515859307960866' '70172427121883998797908792274921901699720888093776' '65727333001053367881220235421809751254540594752243' '52584907711670556013604839586446706324415722155397' '53697817977846174064955149290862569321978468622482' '83972241375657056057490261407972968652414535100474' '82166370484403199890008895243450658541227588666881' '16427171479924442928230863465674813919123162824586' '17866458359124566529476545682848912883142607690042' '24219022671055626321111109370544217506941658960408' '07198403850962455444362981230987879927244284909188' '84580156166097919133875499200524063689912560717606' '05886116467109405077541002256983155200055935729725' '71636269561882670428252483600823257530420752963450' ) def _a ( _SCREAMING_SNAKE_CASE = N ) -> int: return max( # mypy cannot properly interpret reduce int(reduce(lambda _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : str(int(_SCREAMING_SNAKE_CASE ) * int(_SCREAMING_SNAKE_CASE ) ) , n[i : i + 13] ) ) for i in range(len(_SCREAMING_SNAKE_CASE ) - 12 ) ) if __name__ == "__main__": print(f"""{solution() = }""")
2
0
"""simple docstring""" from __future__ import annotations from typing import Any class __A : '''simple docstring''' def __init__( self : Tuple , UpperCAmelCase_ : int , UpperCAmelCase_ : int , UpperCAmelCase_ : float = 0 ) ->None: """simple docstring""" snake_case_ , snake_case_ = row, column snake_case_ = [[default_value for c in range(UpperCAmelCase_ )] for r in range(UpperCAmelCase_ )] def __str__( self : Optional[int] ) ->str: """simple docstring""" snake_case_ = F"""Matrix consist of {self.row} rows and {self.column} columns\n""" # Make string identifier snake_case_ = 0 for row_vector in self.array: for obj in row_vector: snake_case_ = max(UpperCAmelCase_ , len(str(UpperCAmelCase_ ) ) ) snake_case_ = F"""%{max_element_length}s""" # Make string and return def single_line(UpperCAmelCase_ : list[float] ) -> str: nonlocal string_format_identifier snake_case_ = """[""" line += ", ".join(string_format_identifier % (obj,) for obj in row_vector ) line += "]" return line s += "\n".join(single_line(UpperCAmelCase_ ) for row_vector in self.array ) return s def __repr__( self : Tuple ) ->str: """simple docstring""" return str(self ) def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : tuple[int, int] ) ->bool: """simple docstring""" if not (isinstance(UpperCAmelCase_ , (list, tuple) ) and len(UpperCAmelCase_ ) == 2): return False elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column): return False else: return True def __getitem__( self : Union[str, Any] , UpperCAmelCase_ : tuple[int, int] ) ->Any: """simple docstring""" assert self.validate_indicies(UpperCAmelCase_ ) return self.array[loc[0]][loc[1]] def __setitem__( self : Dict , UpperCAmelCase_ : tuple[int, int] , UpperCAmelCase_ : float ) ->None: """simple docstring""" assert self.validate_indicies(UpperCAmelCase_ ) snake_case_ = value def __add__( self : Optional[int] , UpperCAmelCase_ : Matrix ) ->Matrix: """simple docstring""" assert isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) assert self.row == another.row and self.column == another.column # Add snake_case_ = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): snake_case_ = self[r, c] + another[r, c] return result def __neg__( self : int ) ->Matrix: """simple docstring""" snake_case_ = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): snake_case_ = -self[r, c] return result def __sub__( self : Optional[Any] , UpperCAmelCase_ : Matrix ) ->Matrix: """simple docstring""" return self + (-another) def __mul__( self : List[str] , UpperCAmelCase_ : int | float | Matrix ) ->Matrix: """simple docstring""" if isinstance(UpperCAmelCase_ , (int, float) ): # Scalar multiplication snake_case_ = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): snake_case_ = self[r, c] * another return result elif isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): # Matrix multiplication assert self.column == another.row snake_case_ = 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: snake_case_ = F"""Unsupported type given for another ({type(UpperCAmelCase_ )})""" raise TypeError(UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] ) ->Matrix: """simple docstring""" snake_case_ = Matrix(self.column , self.row ) for r in range(self.row ): for c in range(self.column ): snake_case_ = self[r, c] return result def lowerCAmelCase ( self : str , UpperCAmelCase_ : Matrix , UpperCAmelCase_ : Matrix ) ->Any: """simple docstring""" assert isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) and isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) assert self.row == self.column == u.row == v.row # u, v should be column vector assert u.column == v.column == 1 # u, v should be column vector # Calculate snake_case_ = v.transpose() snake_case_ = (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 ( ) -> None: # a^(-1) snake_case_ = Matrix(3 , 3 , 0 ) for i in range(3 ): snake_case_ = 1 print(f"""a^(-1) is {ainv}""" ) # u, v snake_case_ = Matrix(3 , 1 , 0 ) snake_case_ , snake_case_ , snake_case_ = 1, 2, -3 snake_case_ = Matrix(3 , 1 , 0 ) snake_case_ , snake_case_ , snake_case_ = 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(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )}""" ) def _a ( ) -> None: import doctest doctest.testmod() testa()
702
"""simple docstring""" from ....configuration_utils import PretrainedConfig from ....utils import logging __SCREAMING_SNAKE_CASE : str = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : str = { 'speechbrain/m-ctc-t-large': 'https://huggingface.co/speechbrain/m-ctc-t-large/resolve/main/config.json', # See all M-CTC-T models at https://huggingface.co/models?filter=mctct } class __A (snake_case__): '''simple docstring''' __lowercase: Any = """mctct""" def __init__( self : Dict , UpperCAmelCase_ : List[Any]=8_065 , UpperCAmelCase_ : Tuple=1_536 , UpperCAmelCase_ : Optional[Any]=36 , UpperCAmelCase_ : int=6_144 , UpperCAmelCase_ : Dict=4 , UpperCAmelCase_ : Any=384 , UpperCAmelCase_ : List[str]=920 , UpperCAmelCase_ : Any=1E-5 , UpperCAmelCase_ : Any=0.3 , UpperCAmelCase_ : Tuple="relu" , UpperCAmelCase_ : Union[str, Any]=0.02 , UpperCAmelCase_ : Dict=0.3 , UpperCAmelCase_ : str=0.3 , UpperCAmelCase_ : Any=1 , UpperCAmelCase_ : Any=0 , UpperCAmelCase_ : int=2 , UpperCAmelCase_ : str=1 , UpperCAmelCase_ : Tuple=0.3 , UpperCAmelCase_ : Optional[Any]=1 , UpperCAmelCase_ : Optional[Any]=(7,) , UpperCAmelCase_ : Optional[Any]=(3,) , UpperCAmelCase_ : List[str]=80 , UpperCAmelCase_ : Tuple=1 , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : List[str]="sum" , UpperCAmelCase_ : Union[str, Any]=False , **UpperCAmelCase_ : Any , ) ->Dict: """simple docstring""" super().__init__(**UpperCAmelCase_ , pad_token_id=UpperCAmelCase_ , bos_token_id=UpperCAmelCase_ , eos_token_id=UpperCAmelCase_ ) snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = intermediate_size snake_case_ = num_attention_heads snake_case_ = attention_head_dim snake_case_ = max_position_embeddings snake_case_ = layer_norm_eps snake_case_ = layerdrop snake_case_ = hidden_act snake_case_ = initializer_range snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = pad_token_id snake_case_ = bos_token_id snake_case_ = eos_token_id snake_case_ = conv_glu_dim snake_case_ = conv_dropout snake_case_ = num_conv_layers snake_case_ = input_feat_per_channel snake_case_ = input_channels snake_case_ = conv_channels snake_case_ = ctc_loss_reduction snake_case_ = ctc_zero_infinity # prevents config testing fail with exporting to json snake_case_ = list(UpperCAmelCase_ ) snake_case_ = list(UpperCAmelCase_ ) if len(self.conv_kernel ) != self.num_conv_layers: raise ValueError( """Configuration for convolutional module is incorrect. """ """It is required that `len(config.conv_kernel)` == `config.num_conv_layers` """ F"""but is `len(config.conv_kernel) = {len(self.conv_kernel )}`, """ F"""`config.num_conv_layers = {self.num_conv_layers}`.""" )
2
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) if is_sentencepiece_available(): from ..ta.tokenization_ta import TaTokenizer else: from ...utils.dummy_sentencepiece_objects import TaTokenizer __SCREAMING_SNAKE_CASE : Dict = TaTokenizer if is_tokenizers_available(): from ..ta.tokenization_ta_fast import TaTokenizerFast else: from ...utils.dummy_tokenizers_objects import TaTokenizerFast __SCREAMING_SNAKE_CASE : str = TaTokenizerFast __SCREAMING_SNAKE_CASE : List[str] = {'configuration_mt5': ['MT5Config', 'MT5OnnxConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : Dict = [ 'MT5EncoderModel', 'MT5ForConditionalGeneration', 'MT5ForQuestionAnswering', 'MT5Model', 'MT5PreTrainedModel', 'MT5Stack', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : Tuple = ['TFMT5EncoderModel', 'TFMT5ForConditionalGeneration', 'TFMT5Model'] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : Union[str, Any] = ['FlaxMT5EncoderModel', 'FlaxMT5ForConditionalGeneration', 'FlaxMT5Model'] if TYPE_CHECKING: from .configuration_mta import MTaConfig, MTaOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mta import ( MTaEncoderModel, MTaForConditionalGeneration, MTaForQuestionAnswering, MTaModel, MTaPreTrainedModel, MTaStack, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mta import TFMTaEncoderModel, TFMTaForConditionalGeneration, TFMTaModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_mta import FlaxMTaEncoderModel, FlaxMTaForConditionalGeneration, FlaxMTaModel else: import sys __SCREAMING_SNAKE_CASE : List[str] = _LazyModule( __name__, globals()['__file__'], _import_structure, extra_objects={'MT5Tokenizer': MTaTokenizer, 'MT5TokenizerFast': MTaTokenizerFast}, module_spec=__spec__, )
703
"""simple docstring""" from math import factorial def _a ( _SCREAMING_SNAKE_CASE = 100 ) -> int: return sum(int(_SCREAMING_SNAKE_CASE ) for x in str(factorial(_SCREAMING_SNAKE_CASE ) ) ) if __name__ == "__main__": print(solution(int(input('Enter the Number: ').strip())))
2
0
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE ) -> int: '''simple docstring''' if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): raise ValueError("""Input must be an integer""" ) if input_num <= 0: raise ValueError("""Input must be positive""" ) return sum( divisor for divisor in range(1 , input_num // 2 + 1 ) if input_num % divisor == 0 ) if __name__ == "__main__": import doctest doctest.testmod()
704
"""simple docstring""" import unittest import torch from diffusers import VQModel from diffusers.utils import floats_tensor, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class __A (snake_case__ , snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: str = VQModel __lowercase: Union[str, Any] = """sample""" @property def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : List[str]=(32, 32) ) ->Tuple: """simple docstring""" snake_case_ = 4 snake_case_ = 3 snake_case_ = floats_tensor((batch_size, num_channels) + sizes ).to(UpperCAmelCase_ ) return {"sample": image} @property def lowerCAmelCase ( self : Tuple ) ->str: """simple docstring""" return (3, 32, 32) @property def lowerCAmelCase ( self : List[Any] ) ->Any: """simple docstring""" return (3, 32, 32) def lowerCAmelCase ( self : Optional[int] ) ->Dict: """simple docstring""" snake_case_ = { """block_out_channels""": [32, 64], """in_channels""": 3, """out_channels""": 3, """down_block_types""": ["""DownEncoderBlock2D""", """DownEncoderBlock2D"""], """up_block_types""": ["""UpDecoderBlock2D""", """UpDecoderBlock2D"""], """latent_channels""": 3, } snake_case_ = self.dummy_input return init_dict, inputs_dict def lowerCAmelCase ( self : List[str] ) ->Dict: """simple docstring""" pass def lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" pass def lowerCAmelCase ( self : Any ) ->Union[str, Any]: """simple docstring""" snake_case_ , snake_case_ = VQModel.from_pretrained("""fusing/vqgan-dummy""" , output_loading_info=UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) self.assertEqual(len(loading_info["""missing_keys"""] ) , 0 ) model.to(UpperCAmelCase_ ) snake_case_ = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def lowerCAmelCase ( self : Tuple ) ->Optional[Any]: """simple docstring""" snake_case_ = VQModel.from_pretrained("""fusing/vqgan-dummy""" ) model.to(UpperCAmelCase_ ).eval() torch.manual_seed(0 ) if torch.cuda.is_available(): torch.cuda.manual_seed_all(0 ) snake_case_ = torch.randn(1 , model.config.in_channels , model.config.sample_size , model.config.sample_size ) snake_case_ = image.to(UpperCAmelCase_ ) with torch.no_grad(): snake_case_ = model(UpperCAmelCase_ ).sample snake_case_ = output[0, -1, -3:, -3:].flatten().cpu() # fmt: off snake_case_ = torch.tensor([-0.0_153, -0.4_044, -0.1_880, -0.5_161, -0.2_418, -0.4_072, -0.1_612, -0.0_633, -0.0_143] ) # fmt: on self.assertTrue(torch.allclose(UpperCAmelCase_ , UpperCAmelCase_ , atol=1E-3 ) )
2
0
"""simple docstring""" __SCREAMING_SNAKE_CASE : str = 'Input must be a string of 8 numbers plus letter' __SCREAMING_SNAKE_CASE : Dict = 'TRWAGMYFPDXBNJZSQVHLCKE' def _a ( _SCREAMING_SNAKE_CASE ) -> bool: if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): snake_case_ = f"""Expected string as input, found {type(_SCREAMING_SNAKE_CASE ).__name__}""" raise TypeError(_SCREAMING_SNAKE_CASE ) snake_case_ = spanish_id.replace("""-""" , """""" ).upper() if len(_SCREAMING_SNAKE_CASE ) != 9: raise ValueError(_SCREAMING_SNAKE_CASE ) try: snake_case_ = int(spanish_id_clean[0:8] ) snake_case_ = spanish_id_clean[8] except ValueError as ex: raise ValueError(_SCREAMING_SNAKE_CASE ) from ex if letter.isdigit(): raise ValueError(_SCREAMING_SNAKE_CASE ) return letter == LOOKUP_LETTERS[number % 23] if __name__ == "__main__": import doctest doctest.testmod()
705
"""simple docstring""" import gc import random import unittest import numpy as np import torch from diffusers import ( DDIMScheduler, KandinskyVaaControlnetPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) 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 from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class __A (snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Dict = KandinskyVaaControlnetPipeline __lowercase: str = ["""image_embeds""", """negative_image_embeds""", """hint"""] __lowercase: List[str] = ["""image_embeds""", """negative_image_embeds""", """hint"""] __lowercase: Union[str, Any] = [ """generator""", """height""", """width""", """latents""", """guidance_scale""", """num_inference_steps""", """return_dict""", """guidance_scale""", """num_images_per_prompt""", """output_type""", """return_dict""", ] __lowercase: Tuple = False @property def lowerCAmelCase ( self : Any ) ->Union[str, Any]: """simple docstring""" return 32 @property def lowerCAmelCase ( self : Optional[Any] ) ->Union[str, Any]: """simple docstring""" return 32 @property def lowerCAmelCase ( self : int ) ->List[str]: """simple docstring""" return self.time_input_dim @property def lowerCAmelCase ( self : Union[str, Any] ) ->Union[str, Any]: """simple docstring""" return self.time_input_dim * 4 @property def lowerCAmelCase ( self : Dict ) ->Optional[int]: """simple docstring""" return 100 @property def lowerCAmelCase ( self : str ) ->List[Any]: """simple docstring""" torch.manual_seed(0 ) snake_case_ = { """in_channels""": 8, # Out channels is double in channels because predicts mean and variance """out_channels""": 8, """addition_embed_type""": """image_hint""", """down_block_types""": ("""ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D"""), """up_block_types""": ("""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""), """mid_block_type""": """UNetMidBlock2DSimpleCrossAttn""", """block_out_channels""": (self.block_out_channels_a, self.block_out_channels_a * 2), """layers_per_block""": 1, """encoder_hid_dim""": self.text_embedder_hidden_size, """encoder_hid_dim_type""": """image_proj""", """cross_attention_dim""": self.cross_attention_dim, """attention_head_dim""": 4, """resnet_time_scale_shift""": """scale_shift""", """class_embed_type""": None, } snake_case_ = UNetaDConditionModel(**UpperCAmelCase_ ) return model @property def lowerCAmelCase ( self : Any ) ->Optional[Any]: """simple docstring""" return { "block_out_channels": [32, 32, 64, 64], "down_block_types": [ "DownEncoderBlock2D", "DownEncoderBlock2D", "DownEncoderBlock2D", "AttnDownEncoderBlock2D", ], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": ["AttnUpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"], "vq_embed_dim": 4, } @property def lowerCAmelCase ( self : Any ) ->int: """simple docstring""" torch.manual_seed(0 ) snake_case_ = VQModel(**self.dummy_movq_kwargs ) return model def lowerCAmelCase ( self : Dict ) ->str: """simple docstring""" snake_case_ = self.dummy_unet snake_case_ = self.dummy_movq snake_case_ = DDIMScheduler( num_train_timesteps=1_000 , beta_schedule="""linear""" , beta_start=0.00_085 , beta_end=0.012 , clip_sample=UpperCAmelCase_ , set_alpha_to_one=UpperCAmelCase_ , steps_offset=1 , prediction_type="""epsilon""" , thresholding=UpperCAmelCase_ , ) snake_case_ = { """unet""": unet, """scheduler""": scheduler, """movq""": movq, } return components def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[Any]=0 ) ->List[str]: """simple docstring""" snake_case_ = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(UpperCAmelCase_ ) ).to(UpperCAmelCase_ ) snake_case_ = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( UpperCAmelCase_ ) # create hint snake_case_ = floats_tensor((1, 3, 64, 64) , rng=random.Random(UpperCAmelCase_ ) ).to(UpperCAmelCase_ ) if str(UpperCAmelCase_ ).startswith("""mps""" ): snake_case_ = torch.manual_seed(UpperCAmelCase_ ) else: snake_case_ = torch.Generator(device=UpperCAmelCase_ ).manual_seed(UpperCAmelCase_ ) snake_case_ = { """image_embeds""": image_embeds, """negative_image_embeds""": negative_image_embeds, """hint""": hint, """generator""": generator, """height""": 64, """width""": 64, """guidance_scale""": 4.0, """num_inference_steps""": 2, """output_type""": """np""", } return inputs def lowerCAmelCase ( self : List[str] ) ->List[Any]: """simple docstring""" snake_case_ = """cpu""" snake_case_ = self.get_dummy_components() snake_case_ = self.pipeline_class(**UpperCAmelCase_ ) snake_case_ = pipe.to(UpperCAmelCase_ ) pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) snake_case_ = pipe(**self.get_dummy_inputs(UpperCAmelCase_ ) ) snake_case_ = output.images snake_case_ = pipe( **self.get_dummy_inputs(UpperCAmelCase_ ) , return_dict=UpperCAmelCase_ , )[0] snake_case_ = image[0, -3:, -3:, -1] snake_case_ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) snake_case_ = np.array( [0.6_959_826, 0.868_279, 0.7_558_092, 0.68_769_467, 0.85_805_804, 0.65_977_496, 0.44_885_302, 0.5_959_111, 0.4_251_595] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 ), F""" expected_slice {expected_slice}, but got {image_slice.flatten()}""" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 ), F""" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}""" @slow @require_torch_gpu class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : List[Any] ) ->Union[str, Any]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCAmelCase ( self : List[str] ) ->List[str]: """simple docstring""" snake_case_ = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinskyv22/kandinskyv22_controlnet_robotcat_fp16.npy""" ) snake_case_ = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinskyv22/hint_image_cat.png""" ) snake_case_ = torch.from_numpy(np.array(UpperCAmelCase_ ) ).float() / 255.0 snake_case_ = hint.permute(2 , 0 , 1 ).unsqueeze(0 ) snake_case_ = KandinskyVaaPriorPipeline.from_pretrained( """kandinsky-community/kandinsky-2-2-prior""" , torch_dtype=torch.floataa ) pipe_prior.to(UpperCAmelCase_ ) snake_case_ = KandinskyVaaControlnetPipeline.from_pretrained( """kandinsky-community/kandinsky-2-2-controlnet-depth""" , torch_dtype=torch.floataa ) snake_case_ = pipeline.to(UpperCAmelCase_ ) pipeline.set_progress_bar_config(disable=UpperCAmelCase_ ) snake_case_ = """A robot, 4k photo""" snake_case_ = torch.Generator(device="""cuda""" ).manual_seed(0 ) snake_case_ , snake_case_ = pipe_prior( UpperCAmelCase_ , generator=UpperCAmelCase_ , num_inference_steps=5 , negative_prompt="""""" , ).to_tuple() snake_case_ = torch.Generator(device="""cuda""" ).manual_seed(0 ) snake_case_ = pipeline( image_embeds=UpperCAmelCase_ , negative_image_embeds=UpperCAmelCase_ , hint=UpperCAmelCase_ , generator=UpperCAmelCase_ , num_inference_steps=100 , output_type="""np""" , ) snake_case_ = output.images[0] assert image.shape == (512, 512, 3) assert_mean_pixel_difference(UpperCAmelCase_ , UpperCAmelCase_ )
2
0
"""simple docstring""" import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, Features, Value from .base import TaskTemplate @dataclass(frozen=snake_case__) class __A (snake_case__): '''simple docstring''' __lowercase: str = field(default="""automatic-speech-recognition""" , metadata={"""include_in_asdict_even_if_is_default""": True}) __lowercase: ClassVar[Features] = Features({"""audio""": Audio()}) __lowercase: ClassVar[Features] = Features({"""transcription""": Value("""string""")}) __lowercase: str = "audio" __lowercase: str = "transcription" def lowerCAmelCase ( self : List[Any] , UpperCAmelCase_ : Any ) ->int: """simple docstring""" if self.audio_column not in features: raise ValueError(F"""Column {self.audio_column} is not present in features.""" ) if not isinstance(features[self.audio_column] , UpperCAmelCase_ ): raise ValueError(F"""Column {self.audio_column} is not an Audio type.""" ) snake_case_ = copy.deepcopy(self ) snake_case_ = self.input_schema.copy() snake_case_ = features[self.audio_column] snake_case_ = input_schema return task_template @property def lowerCAmelCase ( self : List[str] ) ->Dict[str, str]: """simple docstring""" return {self.audio_column: "audio", self.transcription_column: "transcription"}
706
"""simple docstring""" from __future__ import annotations from collections import deque class __A : '''simple docstring''' def __init__( self : List[Any] , UpperCAmelCase_ : list[str] ) ->List[Any]: """simple docstring""" snake_case_ = [] self.adlist.append( {"""value""": """""", """next_states""": [], """fail_state""": 0, """output""": []} ) for keyword in keywords: self.add_keyword(UpperCAmelCase_ ) self.set_fail_transitions() def lowerCAmelCase ( self : int , UpperCAmelCase_ : int , UpperCAmelCase_ : str ) ->int | None: """simple docstring""" for state in self.adlist[current_state]["next_states"]: if char == self.adlist[state]["value"]: return state return None def lowerCAmelCase ( self : int , UpperCAmelCase_ : str ) ->None: """simple docstring""" snake_case_ = 0 for character in keyword: snake_case_ = self.find_next_state(UpperCAmelCase_ , UpperCAmelCase_ ) if next_state is None: self.adlist.append( { """value""": character, """next_states""": [], """fail_state""": 0, """output""": [], } ) self.adlist[current_state]["next_states"].append(len(self.adlist ) - 1 ) snake_case_ = len(self.adlist ) - 1 else: snake_case_ = next_state self.adlist[current_state]["output"].append(UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->None: """simple docstring""" snake_case_ = deque() for node in self.adlist[0]["next_states"]: q.append(UpperCAmelCase_ ) snake_case_ = 0 while q: snake_case_ = q.popleft() for child in self.adlist[r]["next_states"]: q.append(UpperCAmelCase_ ) snake_case_ = self.adlist[r]["""fail_state"""] while ( self.find_next_state(UpperCAmelCase_ , self.adlist[child]["""value"""] ) is None and state != 0 ): snake_case_ = self.adlist[state]["""fail_state"""] snake_case_ = self.find_next_state( UpperCAmelCase_ , self.adlist[child]["""value"""] ) if self.adlist[child]["fail_state"] is None: snake_case_ = 0 snake_case_ = ( self.adlist[child]["""output"""] + self.adlist[self.adlist[child]["""fail_state"""]]["""output"""] ) def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : str ) ->dict[str, list[int]]: """simple docstring""" snake_case_ = {} # returns a dict with keywords and list of its occurrences snake_case_ = 0 for i in range(len(UpperCAmelCase_ ) ): while ( self.find_next_state(UpperCAmelCase_ , string[i] ) is None and current_state != 0 ): snake_case_ = self.adlist[current_state]["""fail_state"""] snake_case_ = self.find_next_state(UpperCAmelCase_ , string[i] ) if next_state is None: snake_case_ = 0 else: snake_case_ = next_state for key in self.adlist[current_state]["output"]: if key not in result: snake_case_ = [] result[key].append(i - len(UpperCAmelCase_ ) + 1 ) return result if __name__ == "__main__": import doctest doctest.testmod()
2
0
"""simple docstring""" import os from pathlib import Path from unittest.mock import patch import pytest import zstandard as zstd from datasets.download.download_config import DownloadConfig from datasets.utils.file_utils import ( OfflineModeIsEnabled, cached_path, fsspec_get, fsspec_head, ftp_get, ftp_head, get_from_cache, http_get, http_head, ) __SCREAMING_SNAKE_CASE : Optional[Any] = '\\n Text data.\n Second line of data.' __SCREAMING_SNAKE_CASE : List[str] = 'file' @pytest.fixture(scope="""session""" ) def _a ( _SCREAMING_SNAKE_CASE ) -> List[str]: snake_case_ = tmp_path_factory.mktemp("""data""" ) / (FILE_PATH + """.zstd""") snake_case_ = bytes(_SCREAMING_SNAKE_CASE , """utf-8""" ) with zstd.open(_SCREAMING_SNAKE_CASE , """wb""" ) as f: f.write(_SCREAMING_SNAKE_CASE ) return path @pytest.fixture def _a ( _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: with open(os.path.join(tmpfs.local_root_dir , _SCREAMING_SNAKE_CASE ) , """w""" ) as f: f.write(_SCREAMING_SNAKE_CASE ) return FILE_PATH @pytest.mark.parametrize("""compression_format""" , ["""gzip""", """xz""", """zstd"""] ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[int]: snake_case_ = {"""gzip""": gz_file, """xz""": xz_file, """zstd""": zstd_path} snake_case_ = input_paths[compression_format] snake_case_ = tmp_path / """cache""" snake_case_ = DownloadConfig(cache_dir=_SCREAMING_SNAKE_CASE , extract_compressed_file=_SCREAMING_SNAKE_CASE ) snake_case_ = cached_path(_SCREAMING_SNAKE_CASE , download_config=_SCREAMING_SNAKE_CASE ) with open(_SCREAMING_SNAKE_CASE ) as f: snake_case_ = f.read() with open(_SCREAMING_SNAKE_CASE ) as f: snake_case_ = f.read() assert extracted_file_content == expected_file_content @pytest.mark.parametrize("""default_extracted""" , [True, False] ) @pytest.mark.parametrize("""default_cache_dir""" , [True, False] ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> int: snake_case_ = """custom_cache""" snake_case_ = """custom_extracted_dir""" snake_case_ = tmp_path / """custom_extracted_path""" if default_extracted: snake_case_ = ("""downloads""" if default_cache_dir else custom_cache_dir, """extracted""") else: monkeypatch.setattr("""datasets.config.EXTRACTED_DATASETS_DIR""" , _SCREAMING_SNAKE_CASE ) monkeypatch.setattr("""datasets.config.EXTRACTED_DATASETS_PATH""" , str(_SCREAMING_SNAKE_CASE ) ) snake_case_ = custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir) snake_case_ = xz_file snake_case_ = ( DownloadConfig(extract_compressed_file=_SCREAMING_SNAKE_CASE ) if default_cache_dir else DownloadConfig(cache_dir=tmp_path / custom_cache_dir , extract_compressed_file=_SCREAMING_SNAKE_CASE ) ) snake_case_ = cached_path(_SCREAMING_SNAKE_CASE , download_config=_SCREAMING_SNAKE_CASE ) assert Path(_SCREAMING_SNAKE_CASE ).parent.parts[-2:] == expected def _a ( _SCREAMING_SNAKE_CASE ) -> Any: # absolute path snake_case_ = str(Path(_SCREAMING_SNAKE_CASE ).resolve() ) assert cached_path(_SCREAMING_SNAKE_CASE ) == text_file # relative path snake_case_ = str(Path(_SCREAMING_SNAKE_CASE ).resolve().relative_to(Path(os.getcwd() ) ) ) assert cached_path(_SCREAMING_SNAKE_CASE ) == text_file def _a ( _SCREAMING_SNAKE_CASE ) -> List[str]: # absolute path snake_case_ = str(tmp_path.resolve() / """__missing_file__.txt""" ) with pytest.raises(_SCREAMING_SNAKE_CASE ): cached_path(_SCREAMING_SNAKE_CASE ) # relative path snake_case_ = """./__missing_file__.txt""" with pytest.raises(_SCREAMING_SNAKE_CASE ): cached_path(_SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE ) -> str: snake_case_ = get_from_cache(f"""tmp://{tmpfs_file}""" ) with open(_SCREAMING_SNAKE_CASE ) as f: snake_case_ = f.read() assert output_file_content == FILE_CONTENT @patch("""datasets.config.HF_DATASETS_OFFLINE""" , _SCREAMING_SNAKE_CASE ) def _a ( ) -> Tuple: with pytest.raises(_SCREAMING_SNAKE_CASE ): cached_path("""https://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , _SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE ) -> Dict: snake_case_ = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(_SCREAMING_SNAKE_CASE ): http_get("""https://huggingface.co""" , temp_file=_SCREAMING_SNAKE_CASE ) with pytest.raises(_SCREAMING_SNAKE_CASE ): http_head("""https://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , _SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE ) -> Dict: snake_case_ = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(_SCREAMING_SNAKE_CASE ): ftp_get("""ftp://huggingface.co""" , temp_file=_SCREAMING_SNAKE_CASE ) with pytest.raises(_SCREAMING_SNAKE_CASE ): ftp_head("""ftp://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , _SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE ) -> Tuple: snake_case_ = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(_SCREAMING_SNAKE_CASE ): fsspec_get("""s3://huggingface.co""" , temp_file=_SCREAMING_SNAKE_CASE ) with pytest.raises(_SCREAMING_SNAKE_CASE ): fsspec_head("""s3://huggingface.co""" )
707
"""simple docstring""" import inspect import unittest from transformers import ConvNextVaConfig from transformers.models.auto import get_values from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES 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 transformers import ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __A : '''simple docstring''' def __init__( self : Optional[int] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[int]=13 , UpperCAmelCase_ : str=32 , UpperCAmelCase_ : List[Any]=3 , UpperCAmelCase_ : Optional[Any]=4 , UpperCAmelCase_ : Dict=[10, 20, 30, 40] , UpperCAmelCase_ : List[Any]=[2, 2, 3, 2] , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : Any=37 , UpperCAmelCase_ : str="gelu" , UpperCAmelCase_ : Optional[int]=10 , UpperCAmelCase_ : Dict=0.02 , UpperCAmelCase_ : int=["stage2", "stage3", "stage4"] , UpperCAmelCase_ : Optional[int]=[2, 3, 4] , UpperCAmelCase_ : List[str]=None , ) ->Union[str, Any]: """simple docstring""" snake_case_ = parent snake_case_ = batch_size snake_case_ = image_size snake_case_ = num_channels snake_case_ = num_stages snake_case_ = hidden_sizes snake_case_ = depths snake_case_ = is_training snake_case_ = use_labels snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = num_labels snake_case_ = initializer_range snake_case_ = out_features snake_case_ = out_indices snake_case_ = scope def lowerCAmelCase ( self : List[str] ) ->str: """simple docstring""" snake_case_ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case_ = None if self.use_labels: snake_case_ = ids_tensor([self.batch_size] , self.num_labels ) snake_case_ = self.get_config() return config, pixel_values, labels def lowerCAmelCase ( self : Dict ) ->Optional[int]: """simple docstring""" return ConvNextVaConfig( num_channels=self.num_channels , hidden_sizes=self.hidden_sizes , depths=self.depths , num_stages=self.num_stages , hidden_act=self.hidden_act , is_decoder=UpperCAmelCase_ , initializer_range=self.initializer_range , out_features=self.out_features , out_indices=self.out_indices , num_labels=self.num_labels , ) def lowerCAmelCase ( self : List[Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Optional[Any] ) ->List[Any]: """simple docstring""" snake_case_ = ConvNextVaModel(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[Any] ) ->Any: """simple docstring""" snake_case_ = ConvNextVaForImageClassification(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCAmelCase ( self : Optional[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Union[str, Any] ) ->Tuple: """simple docstring""" snake_case_ = ConvNextVaBackbone(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ ) # verify hidden states self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:] ) # verify backbone works with out_features=None snake_case_ = None snake_case_ = ConvNextVaBackbone(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" snake_case_ = self.prepare_config_and_inputs() snake_case_ , snake_case_ , snake_case_ = config_and_inputs snake_case_ = {"""pixel_values""": pixel_values} return config, inputs_dict def lowerCAmelCase ( self : List[str] ) ->Union[str, Any]: """simple docstring""" snake_case_ = self.prepare_config_and_inputs() snake_case_ , snake_case_ , snake_case_ = config_and_inputs snake_case_ = {"""pixel_values""": pixel_values, """labels""": labels} return config, inputs_dict @require_torch class __A (snake_case__ , snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Optional[Any] = ( ( ConvNextVaModel, ConvNextVaForImageClassification, ConvNextVaBackbone, ) if is_torch_available() else () ) __lowercase: Union[str, Any] = ( {"""feature-extraction""": ConvNextVaModel, """image-classification""": ConvNextVaForImageClassification} if is_torch_available() else {} ) __lowercase: Union[str, Any] = False __lowercase: Optional[Any] = False __lowercase: Any = False __lowercase: Union[str, Any] = False __lowercase: Dict = False def lowerCAmelCase ( self : Union[str, Any] ) ->Tuple: """simple docstring""" snake_case_ = ConvNextVaModelTester(self ) snake_case_ = ConfigTester(self , config_class=UpperCAmelCase_ , has_text_modality=UpperCAmelCase_ , hidden_size=37 ) def lowerCAmelCase ( self : List[Any] ) ->Optional[Any]: """simple docstring""" 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 lowerCAmelCase ( self : str ) ->Optional[Any]: """simple docstring""" return @unittest.skip(reason="""ConvNextV2 does not use inputs_embeds""" ) def lowerCAmelCase ( self : Optional[int] ) ->Union[str, Any]: """simple docstring""" pass @unittest.skip(reason="""ConvNextV2 does not support input and output embeddings""" ) def lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" pass @unittest.skip(reason="""ConvNextV2 does not use feedforward chunking""" ) def lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" pass def lowerCAmelCase ( self : Dict ) ->Optional[int]: """simple docstring""" if not self.model_tester.is_training: return for model_class in self.all_model_classes: snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_with_labels() snake_case_ = True if model_class.__name__ in [ *get_values(UpperCAmelCase_ ), *get_values(UpperCAmelCase_ ), ]: continue snake_case_ = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.train() snake_case_ = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ , return_labels=UpperCAmelCase_ ) snake_case_ = model(**UpperCAmelCase_ ).loss loss.backward() def lowerCAmelCase ( self : Optional[int] ) ->Any: """simple docstring""" if not self.model_tester.is_training: return for model_class in self.all_model_classes: snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_with_labels() snake_case_ = False snake_case_ = True if ( model_class.__name__ in [*get_values(UpperCAmelCase_ ), *get_values(UpperCAmelCase_ )] or not model_class.supports_gradient_checkpointing ): continue snake_case_ = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.gradient_checkpointing_enable() model.train() snake_case_ = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ , return_labels=UpperCAmelCase_ ) snake_case_ = model(**UpperCAmelCase_ ).loss loss.backward() def lowerCAmelCase ( self : List[Any] ) ->Union[str, Any]: """simple docstring""" snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ = model_class(UpperCAmelCase_ ) snake_case_ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case_ = [*signature.parameters.keys()] snake_case_ = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] ) ->Union[str, Any]: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->Dict: """simple docstring""" def check_hidden_states_output(UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : str ): snake_case_ = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() with torch.no_grad(): snake_case_ = model(**self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) ) snake_case_ = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states snake_case_ = self.model_tester.num_stages self.assertEqual(len(UpperCAmelCase_ ) , expected_num_stages + 1 ) # ConvNextV2's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ = True check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] snake_case_ = True check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] ) ->Dict: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_ ) @slow def lowerCAmelCase ( self : Tuple ) ->str: """simple docstring""" for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ = ConvNextVaModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) def _a ( ) -> str: snake_case_ = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class __A (unittest.TestCase): '''simple docstring''' @cached_property def lowerCAmelCase ( self : Union[str, Any] ) ->Optional[int]: """simple docstring""" return AutoImageProcessor.from_pretrained("""facebook/convnextv2-tiny-1k-224""" ) if is_vision_available() else None @slow def lowerCAmelCase ( self : Tuple ) ->int: """simple docstring""" snake_case_ = ConvNextVaForImageClassification.from_pretrained("""facebook/convnextv2-tiny-1k-224""" ).to(UpperCAmelCase_ ) snake_case_ = self.default_image_processor snake_case_ = prepare_img() snake_case_ = preprocessor(images=UpperCAmelCase_ , return_tensors="""pt""" ).to(UpperCAmelCase_ ) # forward pass with torch.no_grad(): snake_case_ = model(**UpperCAmelCase_ ) # verify the logits snake_case_ = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape , UpperCAmelCase_ ) snake_case_ = torch.tensor([0.9_996, 0.1_966, -0.4_386] ).to(UpperCAmelCase_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCAmelCase_ , atol=1E-4 ) )
2
0
"""simple docstring""" import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import BertTokenizer, BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import AlignProcessor, EfficientNetImageProcessor @require_vision class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : Union[str, Any] ) ->int: """simple docstring""" snake_case_ = tempfile.mkdtemp() snake_case_ = [ """[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] snake_case_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) snake_case_ = { """do_resize""": True, """size""": 20, """do_center_crop""": True, """crop_size""": 18, """do_normalize""": True, """image_mean""": [0.48_145_466, 0.4_578_275, 0.40_821_073], """image_std""": [0.26_862_954, 0.26_130_258, 0.27_577_711], } snake_case_ = os.path.join(self.tmpdirname , UpperCAmelCase_ ) with open(self.image_processor_file , """w""" , encoding="""utf-8""" ) as fp: json.dump(UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : List[str] , **UpperCAmelCase_ : Dict ) ->Dict: """simple docstring""" return BertTokenizer.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] , **UpperCAmelCase_ : Tuple ) ->str: """simple docstring""" return BertTokenizerFast.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] , **UpperCAmelCase_ : Tuple ) ->Dict: """simple docstring""" return EfficientNetImageProcessor.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ) def lowerCAmelCase ( self : int ) ->Dict: """simple docstring""" shutil.rmtree(self.tmpdirname ) def lowerCAmelCase ( self : List[str] ) ->List[str]: """simple docstring""" snake_case_ = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] snake_case_ = [Image.fromarray(np.moveaxis(UpperCAmelCase_ , 0 , -1 ) ) for x in image_inputs] return image_inputs def lowerCAmelCase ( self : Optional[Any] ) ->Optional[int]: """simple docstring""" snake_case_ = self.get_tokenizer() snake_case_ = self.get_rust_tokenizer() snake_case_ = self.get_image_processor() snake_case_ = AlignProcessor(tokenizer=UpperCAmelCase_ , image_processor=UpperCAmelCase_ ) processor_slow.save_pretrained(self.tmpdirname ) snake_case_ = AlignProcessor.from_pretrained(self.tmpdirname , use_fast=UpperCAmelCase_ ) snake_case_ = AlignProcessor(tokenizer=UpperCAmelCase_ , image_processor=UpperCAmelCase_ ) processor_fast.save_pretrained(self.tmpdirname ) snake_case_ = AlignProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , UpperCAmelCase_ ) self.assertIsInstance(processor_fast.tokenizer , UpperCAmelCase_ ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , UpperCAmelCase_ ) self.assertIsInstance(processor_fast.image_processor , UpperCAmelCase_ ) def lowerCAmelCase ( self : int ) ->int: """simple docstring""" snake_case_ = AlignProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) snake_case_ = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) snake_case_ = self.get_image_processor(do_normalize=UpperCAmelCase_ , padding_value=1.0 ) snake_case_ = AlignProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=UpperCAmelCase_ , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , UpperCAmelCase_ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , UpperCAmelCase_ ) def lowerCAmelCase ( self : Tuple ) ->List[str]: """simple docstring""" snake_case_ = self.get_image_processor() snake_case_ = self.get_tokenizer() snake_case_ = AlignProcessor(tokenizer=UpperCAmelCase_ , image_processor=UpperCAmelCase_ ) snake_case_ = self.prepare_image_inputs() snake_case_ = image_processor(UpperCAmelCase_ , return_tensors="""np""" ) snake_case_ = processor(images=UpperCAmelCase_ , return_tensors="""np""" ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1E-2 ) def lowerCAmelCase ( self : Any ) ->List[Any]: """simple docstring""" snake_case_ = self.get_image_processor() snake_case_ = self.get_tokenizer() snake_case_ = AlignProcessor(tokenizer=UpperCAmelCase_ , image_processor=UpperCAmelCase_ ) snake_case_ = """lower newer""" snake_case_ = processor(text=UpperCAmelCase_ ) snake_case_ = tokenizer(UpperCAmelCase_ , padding="""max_length""" , max_length=64 ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def lowerCAmelCase ( self : Dict ) ->Optional[Any]: """simple docstring""" snake_case_ = self.get_image_processor() snake_case_ = self.get_tokenizer() snake_case_ = AlignProcessor(tokenizer=UpperCAmelCase_ , image_processor=UpperCAmelCase_ ) snake_case_ = """lower newer""" snake_case_ = self.prepare_image_inputs() snake_case_ = processor(text=UpperCAmelCase_ , images=UpperCAmelCase_ ) self.assertListEqual(list(inputs.keys() ) , ["""input_ids""", """token_type_ids""", """attention_mask""", """pixel_values"""] ) # test if it raises when no input is passed with pytest.raises(UpperCAmelCase_ ): processor() def lowerCAmelCase ( self : int ) ->int: """simple docstring""" snake_case_ = self.get_image_processor() snake_case_ = self.get_tokenizer() snake_case_ = AlignProcessor(tokenizer=UpperCAmelCase_ , image_processor=UpperCAmelCase_ ) snake_case_ = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] snake_case_ = processor.batch_decode(UpperCAmelCase_ ) snake_case_ = tokenizer.batch_decode(UpperCAmelCase_ ) self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ ) def lowerCAmelCase ( self : int ) ->Union[str, Any]: """simple docstring""" snake_case_ = self.get_image_processor() snake_case_ = self.get_tokenizer() snake_case_ = AlignProcessor(tokenizer=UpperCAmelCase_ , image_processor=UpperCAmelCase_ ) snake_case_ = """lower newer""" snake_case_ = self.prepare_image_inputs() snake_case_ = processor(text=UpperCAmelCase_ , images=UpperCAmelCase_ ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
708
"""simple docstring""" import argparse from pathlib import Path from typing import Dict, OrderedDict, Tuple import torch from audiocraft.models import MusicGen from transformers import ( AutoFeatureExtractor, AutoTokenizer, EncodecModel, MusicgenDecoderConfig, MusicgenForConditionalGeneration, MusicgenProcessor, TaEncoderModel, ) from transformers.models.musicgen.modeling_musicgen import MusicgenForCausalLM from transformers.utils import logging logging.set_verbosity_info() __SCREAMING_SNAKE_CASE : Union[str, Any] = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : int = ['model.decoder.embed_positions.weights'] def _a ( _SCREAMING_SNAKE_CASE ) -> str: if "emb" in name: snake_case_ = name.replace("""emb""" , """model.decoder.embed_tokens""" ) if "transformer" in name: snake_case_ = name.replace("""transformer""" , """model.decoder""" ) if "cross_attention" in name: snake_case_ = name.replace("""cross_attention""" , """encoder_attn""" ) if "linear1" in name: snake_case_ = name.replace("""linear1""" , """fc1""" ) if "linear2" in name: snake_case_ = name.replace("""linear2""" , """fc2""" ) if "norm1" in name: snake_case_ = name.replace("""norm1""" , """self_attn_layer_norm""" ) if "norm_cross" in name: snake_case_ = name.replace("""norm_cross""" , """encoder_attn_layer_norm""" ) if "norm2" in name: snake_case_ = name.replace("""norm2""" , """final_layer_norm""" ) if "out_norm" in name: snake_case_ = name.replace("""out_norm""" , """model.decoder.layer_norm""" ) if "linears" in name: snake_case_ = name.replace("""linears""" , """lm_heads""" ) if "condition_provider.conditioners.description.output_proj" in name: snake_case_ = name.replace("""condition_provider.conditioners.description.output_proj""" , """enc_to_dec_proj""" ) return name def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple[Dict, Dict]: snake_case_ = list(state_dict.keys() ) snake_case_ = {} for key in keys: snake_case_ = state_dict.pop(_SCREAMING_SNAKE_CASE ) snake_case_ = rename_keys(_SCREAMING_SNAKE_CASE ) if "in_proj_weight" in key: # split fused qkv proj snake_case_ = val[:hidden_size, :] snake_case_ = val[hidden_size : 2 * hidden_size, :] snake_case_ = val[-hidden_size:, :] elif "enc_to_dec_proj" in key: snake_case_ = val else: snake_case_ = val return state_dict, enc_dec_proj_state_dict def _a ( _SCREAMING_SNAKE_CASE ) -> MusicgenDecoderConfig: if checkpoint == "small": # default config values snake_case_ = 1_024 snake_case_ = 24 snake_case_ = 16 elif checkpoint == "medium": snake_case_ = 1_536 snake_case_ = 48 snake_case_ = 24 elif checkpoint == "large": snake_case_ = 2_048 snake_case_ = 48 snake_case_ = 32 else: raise ValueError(f"""Checkpoint should be one of `['small', 'medium', 'large']`, got {checkpoint}.""" ) snake_case_ = MusicgenDecoderConfig( hidden_size=_SCREAMING_SNAKE_CASE , ffn_dim=hidden_size * 4 , num_hidden_layers=_SCREAMING_SNAKE_CASE , num_attention_heads=_SCREAMING_SNAKE_CASE , ) return config @torch.no_grad() def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE="cpu" ) -> Tuple: snake_case_ = MusicGen.get_pretrained(_SCREAMING_SNAKE_CASE , device=_SCREAMING_SNAKE_CASE ) snake_case_ = decoder_config_from_checkpoint(_SCREAMING_SNAKE_CASE ) snake_case_ = fairseq_model.lm.state_dict() snake_case_ , snake_case_ = rename_state_dict( _SCREAMING_SNAKE_CASE , hidden_size=decoder_config.hidden_size ) snake_case_ = TaEncoderModel.from_pretrained("""t5-base""" ) snake_case_ = EncodecModel.from_pretrained("""facebook/encodec_32khz""" ) snake_case_ = MusicgenForCausalLM(_SCREAMING_SNAKE_CASE ).eval() # load all decoder weights - expect that we'll be missing embeddings and enc-dec projection snake_case_ , snake_case_ = decoder.load_state_dict(_SCREAMING_SNAKE_CASE , strict=_SCREAMING_SNAKE_CASE ) for key in missing_keys.copy(): if key.startswith(("""text_encoder""", """audio_encoder""") ) or key in EXPECTED_MISSING_KEYS: missing_keys.remove(_SCREAMING_SNAKE_CASE ) if len(_SCREAMING_SNAKE_CASE ) > 0: raise ValueError(f"""Missing key(s) in state_dict: {missing_keys}""" ) if len(_SCREAMING_SNAKE_CASE ) > 0: raise ValueError(f"""Unexpected key(s) in state_dict: {unexpected_keys}""" ) # init the composite model snake_case_ = MusicgenForConditionalGeneration(text_encoder=_SCREAMING_SNAKE_CASE , audio_encoder=_SCREAMING_SNAKE_CASE , decoder=_SCREAMING_SNAKE_CASE ) # load the pre-trained enc-dec projection (from the decoder state dict) model.enc_to_dec_proj.load_state_dict(_SCREAMING_SNAKE_CASE ) # check we can do a forward pass snake_case_ = torch.arange(0 , 8 , dtype=torch.long ).reshape(2 , -1 ) snake_case_ = input_ids.reshape(2 * 4 , -1 ) with torch.no_grad(): snake_case_ = model(input_ids=_SCREAMING_SNAKE_CASE , decoder_input_ids=_SCREAMING_SNAKE_CASE ).logits if logits.shape != (8, 1, 2_048): raise ValueError("""Incorrect shape for logits""" ) # now construct the processor snake_case_ = AutoTokenizer.from_pretrained("""t5-base""" ) snake_case_ = AutoFeatureExtractor.from_pretrained("""facebook/encodec_32khz""" , padding_side="""left""" ) snake_case_ = MusicgenProcessor(feature_extractor=_SCREAMING_SNAKE_CASE , tokenizer=_SCREAMING_SNAKE_CASE ) # set the appropriate bos/pad token ids snake_case_ = 2_048 snake_case_ = 2_048 # set other default generation config params snake_case_ = int(30 * audio_encoder.config.frame_rate ) snake_case_ = True snake_case_ = 3.0 if pytorch_dump_folder is not None: Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) logger.info(f"""Saving model {checkpoint} to {pytorch_dump_folder}""" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) processor.save_pretrained(_SCREAMING_SNAKE_CASE ) if repo_id: logger.info(f"""Pushing model {checkpoint} to {repo_id}""" ) model.push_to_hub(_SCREAMING_SNAKE_CASE ) processor.push_to_hub(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( '--checkpoint', default='small', type=str, help='Checkpoint size of the MusicGen model you\'d like to convert. Can be one of: `[\'small\', \'medium\', \'large\']`.', ) parser.add_argument( '--pytorch_dump_folder', required=True, default=None, type=str, help='Path to the output PyTorch model directory.', ) parser.add_argument( '--push_to_hub', default=None, type=str, help='Where to upload the converted model on the 🤗 hub.' ) parser.add_argument( '--device', default='cpu', type=str, help='Torch device to run the conversion, either cpu or cuda.' ) __SCREAMING_SNAKE_CASE : int = parser.parse_args() convert_musicgen_checkpoint(args.checkpoint, args.pytorch_dump_folder, args.push_to_hub)
2
0
"""simple docstring""" from __future__ import annotations import unittest from transformers import DistilBertConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.distilbert.modeling_tf_distilbert import ( TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDistilBertForMaskedLM, TFDistilBertForMultipleChoice, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertModel, ) class __A : '''simple docstring''' def __init__( self : Union[str, Any] , UpperCAmelCase_ : Optional[int] , ) ->Tuple: """simple docstring""" snake_case_ = parent snake_case_ = 13 snake_case_ = 7 snake_case_ = True snake_case_ = True snake_case_ = False snake_case_ = True snake_case_ = 99 snake_case_ = 32 snake_case_ = 2 snake_case_ = 4 snake_case_ = 37 snake_case_ = """gelu""" snake_case_ = 0.1 snake_case_ = 0.1 snake_case_ = 512 snake_case_ = 16 snake_case_ = 2 snake_case_ = 0.02 snake_case_ = 3 snake_case_ = 4 snake_case_ = None def lowerCAmelCase ( self : Tuple ) ->List[str]: """simple docstring""" snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case_ = None if self.use_input_mask: snake_case_ = random_attention_mask([self.batch_size, self.seq_length] ) snake_case_ = None snake_case_ = None snake_case_ = None if self.use_labels: snake_case_ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) snake_case_ = ids_tensor([self.batch_size] , self.num_choices ) snake_case_ = DistilBertConfig( vocab_size=self.vocab_size , dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , hidden_dim=self.intermediate_size , hidden_act=self.hidden_act , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , ) return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def lowerCAmelCase ( self : int , UpperCAmelCase_ : str , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : int ) ->str: """simple docstring""" snake_case_ = TFDistilBertModel(config=UpperCAmelCase_ ) snake_case_ = {"""input_ids""": input_ids, """attention_mask""": input_mask} snake_case_ = model(UpperCAmelCase_ ) snake_case_ = [input_ids, input_mask] snake_case_ = model(UpperCAmelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCAmelCase ( self : List[Any] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Any , UpperCAmelCase_ : Dict , UpperCAmelCase_ : str , UpperCAmelCase_ : Union[str, Any] ) ->int: """simple docstring""" snake_case_ = TFDistilBertForMaskedLM(config=UpperCAmelCase_ ) snake_case_ = {"""input_ids""": input_ids, """attention_mask""": input_mask} snake_case_ = model(UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : str ) ->Optional[int]: """simple docstring""" snake_case_ = TFDistilBertForQuestionAnswering(config=UpperCAmelCase_ ) snake_case_ = { """input_ids""": input_ids, """attention_mask""": input_mask, } snake_case_ = model(UpperCAmelCase_ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : str , UpperCAmelCase_ : int , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[Any] ) ->int: """simple docstring""" snake_case_ = self.num_labels snake_case_ = TFDistilBertForSequenceClassification(UpperCAmelCase_ ) snake_case_ = {"""input_ids""": input_ids, """attention_mask""": input_mask} snake_case_ = model(UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : Any , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Dict ) ->int: """simple docstring""" snake_case_ = self.num_choices snake_case_ = TFDistilBertForMultipleChoice(UpperCAmelCase_ ) snake_case_ = tf.tile(tf.expand_dims(UpperCAmelCase_ , 1 ) , (1, self.num_choices, 1) ) snake_case_ = tf.tile(tf.expand_dims(UpperCAmelCase_ , 1 ) , (1, self.num_choices, 1) ) snake_case_ = { """input_ids""": multiple_choice_inputs_ids, """attention_mask""": multiple_choice_input_mask, } snake_case_ = model(UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def lowerCAmelCase ( self : int , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : str ) ->List[str]: """simple docstring""" snake_case_ = self.num_labels snake_case_ = TFDistilBertForTokenClassification(UpperCAmelCase_ ) snake_case_ = {"""input_ids""": input_ids, """attention_mask""": input_mask} snake_case_ = model(UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowerCAmelCase ( self : str ) ->Tuple: """simple docstring""" snake_case_ = self.prepare_config_and_inputs() ((snake_case_) , (snake_case_) , (snake_case_) , (snake_case_) , (snake_case_) , (snake_case_)) = config_and_inputs snake_case_ = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_tf class __A (snake_case__ , snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: str = ( ( TFDistilBertModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertForMultipleChoice, ) if is_tf_available() else None ) __lowercase: int = ( { """feature-extraction""": TFDistilBertModel, """fill-mask""": TFDistilBertForMaskedLM, """question-answering""": TFDistilBertForQuestionAnswering, """text-classification""": TFDistilBertForSequenceClassification, """token-classification""": TFDistilBertForTokenClassification, """zero-shot""": TFDistilBertForSequenceClassification, } if is_tf_available() else {} ) __lowercase: Any = False __lowercase: Optional[int] = False def lowerCAmelCase ( self : Any ) ->Tuple: """simple docstring""" snake_case_ = TFDistilBertModelTester(self ) snake_case_ = ConfigTester(self , config_class=UpperCAmelCase_ , dim=37 ) def lowerCAmelCase ( self : Optional[Any] ) ->Tuple: """simple docstring""" self.config_tester.run_common_tests() def lowerCAmelCase ( self : Dict ) ->Tuple: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_model(*UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_masked_lm(*UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] ) ->Dict: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_question_answering(*UpperCAmelCase_ ) def lowerCAmelCase ( self : Any ) ->Dict: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_sequence_classification(*UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] ) ->str: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_multiple_choice(*UpperCAmelCase_ ) def lowerCAmelCase ( self : Any ) ->Dict: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_token_classification(*UpperCAmelCase_ ) @slow def lowerCAmelCase ( self : List[Any] ) ->Optional[int]: """simple docstring""" for model_name in list(TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1] ): snake_case_ = TFDistilBertModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) @require_tf class __A (unittest.TestCase): '''simple docstring''' @slow def lowerCAmelCase ( self : Union[str, Any] ) ->List[str]: """simple docstring""" snake_case_ = TFDistilBertModel.from_pretrained("""distilbert-base-uncased""" ) snake_case_ = tf.constant([[0, 1, 2, 3, 4, 5]] ) snake_case_ = model(UpperCAmelCase_ )[0] snake_case_ = [1, 6, 768] self.assertEqual(output.shape , UpperCAmelCase_ ) snake_case_ = tf.constant( [ [ [0.19_261_885, -0.13_732_955, 0.4_119_799], [0.22_150_156, -0.07_422_661, 0.39_037_204], [0.22_756_018, -0.0_896_414, 0.3_701_467], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , UpperCAmelCase_ , atol=1E-4 )
709
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> int: if index == number_of_items: return 0 snake_case_ = 0 snake_case_ = 0 snake_case_ = knapsack(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , index + 1 ) if weights[index] <= max_weight: snake_case_ = values[index] + knapsack( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , max_weight - weights[index] , index + 1 ) return max(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": import doctest doctest.testmod()
2
0
"""simple docstring""" 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 __SCREAMING_SNAKE_CASE : List[str] = data_utils.TransfoXLTokenizer __SCREAMING_SNAKE_CASE : Optional[int] = data_utils.TransfoXLCorpus __SCREAMING_SNAKE_CASE : Optional[int] = data_utils __SCREAMING_SNAKE_CASE : int = data_utils def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Dict: if transfo_xl_dataset_file: # Convert a pre-processed corpus (see original TensorFlow repo) with open(_SCREAMING_SNAKE_CASE , """rb""" ) as fp: snake_case_ = pickle.load(_SCREAMING_SNAKE_CASE , encoding="""latin1""" ) # Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term) snake_case_ = pytorch_dump_folder_path + """/""" + VOCAB_FILES_NAMES["""pretrained_vocab_file"""] print(f"""Save vocabulary to {pytorch_vocab_dump_path}""" ) snake_case_ = corpus.vocab.__dict__ torch.save(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = corpus.__dict__ corpus_dict_no_vocab.pop("""vocab""" , _SCREAMING_SNAKE_CASE ) snake_case_ = pytorch_dump_folder_path + """/""" + CORPUS_NAME print(f"""Save dataset to {pytorch_dataset_dump_path}""" ) torch.save(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if tf_checkpoint_path: # Convert a pre-trained TensorFlow model snake_case_ = os.path.abspath(_SCREAMING_SNAKE_CASE ) snake_case_ = os.path.abspath(_SCREAMING_SNAKE_CASE ) print(f"""Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.""" ) # Initialise PyTorch model if transfo_xl_config_file == "": snake_case_ = TransfoXLConfig() else: snake_case_ = TransfoXLConfig.from_json_file(_SCREAMING_SNAKE_CASE ) print(f"""Building PyTorch model from configuration: {config}""" ) snake_case_ = TransfoXLLMHeadModel(_SCREAMING_SNAKE_CASE ) snake_case_ = load_tf_weights_in_transfo_xl(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Save pytorch-model snake_case_ = os.path.join(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = os.path.join(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) print(f"""Save PyTorch model to {os.path.abspath(_SCREAMING_SNAKE_CASE )}""" ) torch.save(model.state_dict() , _SCREAMING_SNAKE_CASE ) print(f"""Save configuration file to {os.path.abspath(_SCREAMING_SNAKE_CASE )}""" ) with open(_SCREAMING_SNAKE_CASE , """w""" , encoding="""utf-8""" ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : List[str] = 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.', ) __SCREAMING_SNAKE_CASE : Union[str, Any] = 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, )
710
"""simple docstring""" from math import factorial def _a ( _SCREAMING_SNAKE_CASE = 20 ) -> int: snake_case_ = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1, # 2, 3,... snake_case_ = n // 2 return int(factorial(_SCREAMING_SNAKE_CASE ) / (factorial(_SCREAMING_SNAKE_CASE ) * factorial(n - k )) ) if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution(20)) else: try: __SCREAMING_SNAKE_CASE : Optional[int] = int(sys.argv[1]) print(solution(n)) except ValueError: print('Invalid entry - please enter a number.')
2
0
"""simple docstring""" import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING __SCREAMING_SNAKE_CASE : Tuple = { 'facebook/mask2former-swin-small-coco-instance': ( 'https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json' ) # See all Mask2Former models at https://huggingface.co/models?filter=mask2former } __SCREAMING_SNAKE_CASE : str = logging.get_logger(__name__) class __A (snake_case__): __lowercase: Optional[Any] = """mask2former""" __lowercase: Any = ["""swin"""] __lowercase: Union[str, Any] = {"""hidden_size""": """hidden_dim"""} def __init__( self : str , UpperCAmelCase_ : Optional[Dict] = None , UpperCAmelCase_ : int = 256 , UpperCAmelCase_ : int = 256 , UpperCAmelCase_ : int = 256 , UpperCAmelCase_ : int = 1_024 , UpperCAmelCase_ : str = "relu" , UpperCAmelCase_ : int = 6 , UpperCAmelCase_ : int = 10 , UpperCAmelCase_ : int = 8 , UpperCAmelCase_ : float = 0.0 , UpperCAmelCase_ : int = 2_048 , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : int = 4 , UpperCAmelCase_ : int = 255 , UpperCAmelCase_ : int = 100 , UpperCAmelCase_ : float = 0.1 , UpperCAmelCase_ : float = 2.0 , UpperCAmelCase_ : float = 5.0 , UpperCAmelCase_ : float = 5.0 , UpperCAmelCase_ : int = 12_544 , UpperCAmelCase_ : float = 3.0 , UpperCAmelCase_ : float = 0.75 , UpperCAmelCase_ : float = 0.02 , UpperCAmelCase_ : float = 1.0 , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : List[int] = [4, 8, 16, 32] , UpperCAmelCase_ : bool = None , **UpperCAmelCase_ : Optional[Any] , ) ->Dict: """simple docstring""" if backbone_config is None: logger.info("""`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.""" ) snake_case_ = CONFIG_MAPPING["""swin"""]( image_size=224 , in_channels=3 , patch_size=4 , embed_dim=96 , depths=[2, 2, 18, 2] , num_heads=[3, 6, 12, 24] , window_size=7 , drop_path_rate=0.3 , use_absolute_embeddings=UpperCAmelCase_ , out_features=["""stage1""", """stage2""", """stage3""", """stage4"""] , ) if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): snake_case_ = backbone_config.pop("""model_type""" ) snake_case_ = CONFIG_MAPPING[backbone_model_type] snake_case_ = config_class.from_dict(UpperCAmelCase_ ) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( F"""Backbone {backbone_config.model_type} is not a supported model and may not be compatible with Mask2Former. """ F"""Supported model types: {",".join(self.backbones_supported )}""" ) snake_case_ = backbone_config snake_case_ = feature_size snake_case_ = mask_feature_size snake_case_ = hidden_dim snake_case_ = encoder_feedforward_dim snake_case_ = activation_function snake_case_ = encoder_layers snake_case_ = decoder_layers snake_case_ = num_attention_heads snake_case_ = dropout snake_case_ = dim_feedforward snake_case_ = pre_norm snake_case_ = enforce_input_projection snake_case_ = common_stride snake_case_ = ignore_value snake_case_ = num_queries snake_case_ = no_object_weight snake_case_ = class_weight snake_case_ = mask_weight snake_case_ = dice_weight snake_case_ = train_num_points snake_case_ = oversample_ratio snake_case_ = importance_sample_ratio snake_case_ = init_std snake_case_ = init_xavier_std snake_case_ = use_auxiliary_loss snake_case_ = feature_strides snake_case_ = output_auxiliary_logits snake_case_ = decoder_layers super().__init__(**UpperCAmelCase_ ) @classmethod def lowerCAmelCase ( cls : Tuple , UpperCAmelCase_ : PretrainedConfig , **UpperCAmelCase_ : List[Any] ) ->int: """simple docstring""" return cls( backbone_config=UpperCAmelCase_ , **UpperCAmelCase_ , ) def lowerCAmelCase ( self : int ) ->Dict[str, any]: """simple docstring""" snake_case_ = copy.deepcopy(self.__dict__ ) snake_case_ = self.backbone_config.to_dict() snake_case_ = self.__class__.model_type return output
711
"""simple docstring""" import secrets from random import shuffle from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation def _a ( _SCREAMING_SNAKE_CASE = 8 ) -> str: snake_case_ = ascii_letters + digits + punctuation return "".join(secrets.choice(_SCREAMING_SNAKE_CASE ) for _ in range(_SCREAMING_SNAKE_CASE ) ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: # Password Generator = full boot with random_number, random_letters, and # random_character FUNCTIONS # Put your code here... i -= len(_SCREAMING_SNAKE_CASE ) snake_case_ = i // 3 snake_case_ = i % 3 # chars = chars_incl + random_letters(ascii_letters, i / 3 + remainder) + # random_number(digits, i / 3) + random_characters(punctuation, i / 3) snake_case_ = ( chars_incl + random(_SCREAMING_SNAKE_CASE , quotient + remainder ) + random(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) + random(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) snake_case_ = list(_SCREAMING_SNAKE_CASE ) shuffle(_SCREAMING_SNAKE_CASE ) return "".join(_SCREAMING_SNAKE_CASE ) # random is a generalised function for letters, characters and numbers def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: return "".join(secrets.choice(_SCREAMING_SNAKE_CASE ) for _ in range(_SCREAMING_SNAKE_CASE ) ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: pass # Put your code here... def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[str]: pass # Put your code here... def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[int]: pass # Put your code here... def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 8 ) -> bool: if len(_SCREAMING_SNAKE_CASE ) < min_length: # Your Password must be at least 8 characters long return False snake_case_ = any(char in ascii_uppercase for char in password ) snake_case_ = any(char in ascii_lowercase for char in password ) snake_case_ = any(char in digits for char in password ) snake_case_ = any(char in punctuation for char in password ) return upper and lower and num and spec_char # Passwords should contain UPPERCASE, lowerase # numbers, and special characters def _a ( ) -> str: snake_case_ = int(input("""Please indicate the max length of your password: """ ).strip() ) snake_case_ = input( """Please indicate the characters that must be in your password: """ ).strip() print("""Password generated:""" , password_generator(_SCREAMING_SNAKE_CASE ) ) print( """Alternative Password generated:""" , alternative_password_generator(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) , ) print("""[If you are thinking of using this passsword, You better save it.]""" ) if __name__ == "__main__": main()
2
0
"""simple docstring""" import os import tempfile import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from torch import nn from transformers import ( Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_inverse_sqrt_schedule, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=10 ) -> Optional[int]: snake_case_ = [] for _ in range(_SCREAMING_SNAKE_CASE ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() return lrs def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=10 ) -> int: snake_case_ = [] for step in range(_SCREAMING_SNAKE_CASE ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() if step == num_steps // 2: with tempfile.TemporaryDirectory() as tmpdirname: snake_case_ = os.path.join(_SCREAMING_SNAKE_CASE , """schedule.bin""" ) torch.save(scheduler.state_dict() , _SCREAMING_SNAKE_CASE ) snake_case_ = torch.load(_SCREAMING_SNAKE_CASE ) scheduler.load_state_dict(_SCREAMING_SNAKE_CASE ) return lrs @require_torch class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : Optional[Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : str ) ->Optional[Any]: """simple docstring""" self.assertEqual(len(UpperCAmelCase_ ) , len(UpperCAmelCase_ ) ) for a, b in zip(UpperCAmelCase_ , UpperCAmelCase_ ): self.assertAlmostEqual(UpperCAmelCase_ , UpperCAmelCase_ , delta=UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->Dict: """simple docstring""" snake_case_ = torch.tensor([0.1, -0.2, -0.1] , requires_grad=UpperCAmelCase_ ) snake_case_ = torch.tensor([0.4, 0.2, -0.5] ) snake_case_ = nn.MSELoss() # No warmup, constant schedule, no gradient clipping snake_case_ = AdamW(params=[w] , lr=2E-1 , weight_decay=0.0 ) for _ in range(100 ): snake_case_ = criterion(UpperCAmelCase_ , UpperCAmelCase_ ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1E-2 ) def lowerCAmelCase ( self : Dict ) ->Optional[int]: """simple docstring""" snake_case_ = torch.tensor([0.1, -0.2, -0.1] , requires_grad=UpperCAmelCase_ ) snake_case_ = torch.tensor([0.4, 0.2, -0.5] ) snake_case_ = nn.MSELoss() # No warmup, constant schedule, no gradient clipping snake_case_ = Adafactor( params=[w] , lr=1E-2 , eps=(1E-30, 1E-3) , clip_threshold=1.0 , decay_rate=-0.8 , betaa=UpperCAmelCase_ , weight_decay=0.0 , relative_step=UpperCAmelCase_ , scale_parameter=UpperCAmelCase_ , warmup_init=UpperCAmelCase_ , ) for _ in range(1_000 ): snake_case_ = criterion(UpperCAmelCase_ , UpperCAmelCase_ ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1E-2 ) @require_torch class __A (unittest.TestCase): '''simple docstring''' __lowercase: int = nn.Linear(50 , 50) if is_torch_available() else None __lowercase: Tuple = AdamW(m.parameters() , lr=10.0) if is_torch_available() else None __lowercase: int = 10 def lowerCAmelCase ( self : int , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Dict , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Any=None ) ->Union[str, Any]: """simple docstring""" self.assertEqual(len(UpperCAmelCase_ ) , len(UpperCAmelCase_ ) ) for a, b in zip(UpperCAmelCase_ , UpperCAmelCase_ ): self.assertAlmostEqual(UpperCAmelCase_ , UpperCAmelCase_ , delta=UpperCAmelCase_ , msg=UpperCAmelCase_ ) def lowerCAmelCase ( self : List[Any] ) ->Any: """simple docstring""" snake_case_ = {"""num_warmup_steps""": 2, """num_training_steps""": 10} # schedulers doct format # function: (sched_args_dict, expected_learning_rates) snake_case_ = { get_constant_schedule: ({}, [10.0] * self.num_steps), get_constant_schedule_with_warmup: ( {"""num_warmup_steps""": 4}, [0.0, 2.5, 5.0, 7.5, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0], ), get_linear_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 8.75, 7.5, 6.25, 5.0, 3.75, 2.5, 1.25], ), get_cosine_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 9.61, 8.53, 6.91, 5.0, 3.08, 1.46, 0.38], ), get_cosine_with_hard_restarts_schedule_with_warmup: ( {**common_kwargs, """num_cycles""": 2}, [0.0, 5.0, 10.0, 8.53, 5.0, 1.46, 10.0, 8.53, 5.0, 1.46], ), get_polynomial_decay_schedule_with_warmup: ( {**common_kwargs, """power""": 2.0, """lr_end""": 1E-7}, [0.0, 5.0, 10.0, 7.656, 5.625, 3.906, 2.5, 1.406, 0.625, 0.156], ), get_inverse_sqrt_schedule: ( {"""num_warmup_steps""": 2}, [0.0, 5.0, 10.0, 8.165, 7.071, 6.325, 5.774, 5.345, 5.0, 4.714], ), } for scheduler_func, data in scheds.items(): snake_case_ , snake_case_ = data snake_case_ = scheduler_func(self.optimizer , **UpperCAmelCase_ ) self.assertEqual(len([scheduler.get_lr()[0]] ) , 1 ) snake_case_ = unwrap_schedule(UpperCAmelCase_ , self.num_steps ) self.assertListAlmostEqual( UpperCAmelCase_ , UpperCAmelCase_ , tol=1E-2 , msg=F"""failed for {scheduler_func} in normal scheduler""" , ) snake_case_ = scheduler_func(self.optimizer , **UpperCAmelCase_ ) if scheduler_func.__name__ != "get_constant_schedule": LambdaScheduleWrapper.wrap_scheduler(UpperCAmelCase_ ) # wrap to test picklability of the schedule snake_case_ = unwrap_and_save_reload_schedule(UpperCAmelCase_ , self.num_steps ) self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ , msg=F"""failed for {scheduler_func} in save and reload""" ) class __A : '''simple docstring''' def __init__( self : str , UpperCAmelCase_ : List[str] ) ->List[str]: """simple docstring""" snake_case_ = fn def __call__( self : Optional[Any] , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : int ) ->str: """simple docstring""" return self.fn(*UpperCAmelCase_ , **UpperCAmelCase_ ) @classmethod def lowerCAmelCase ( self : Optional[Any] , UpperCAmelCase_ : Dict ) ->List[Any]: """simple docstring""" snake_case_ = list(map(self , scheduler.lr_lambdas ) )
712
"""simple docstring""" import json import os import tempfile import unittest import numpy as np from datasets import load_dataset 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 if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ImageGPTImageProcessor class __A (unittest.TestCase): '''simple docstring''' def __init__( self : int , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Tuple=7 , UpperCAmelCase_ : Dict=3 , UpperCAmelCase_ : Tuple=18 , UpperCAmelCase_ : Optional[Any]=30 , UpperCAmelCase_ : str=400 , UpperCAmelCase_ : int=True , UpperCAmelCase_ : Optional[int]=None , UpperCAmelCase_ : Optional[Any]=True , ) ->Optional[Any]: """simple docstring""" snake_case_ = size if size is not None else {"""height""": 18, """width""": 18} snake_case_ = parent snake_case_ = batch_size snake_case_ = num_channels snake_case_ = image_size snake_case_ = min_resolution snake_case_ = max_resolution snake_case_ = do_resize snake_case_ = size snake_case_ = do_normalize def lowerCAmelCase ( self : List[str] ) ->Optional[Any]: """simple docstring""" return { # here we create 2 clusters for the sake of simplicity "clusters": np.asarray( [ [0.8_866_443_634_033_203, 0.6_618_829_369_544_983, 0.3_891_746_401_786_804], [-0.6_042_559_146_881_104, -0.02_295_008_860_528_469, 0.5_423_797_369_003_296], ] ), "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, } @require_torch @require_vision class __A (snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: List[Any] = ImageGPTImageProcessor if is_vision_available() else None def lowerCAmelCase ( self : Optional[int] ) ->Optional[int]: """simple docstring""" snake_case_ = ImageGPTImageProcessingTester(self ) @property def lowerCAmelCase ( self : Tuple ) ->List[Any]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(UpperCAmelCase_ , """clusters""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """do_resize""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """size""" ) ) self.assertTrue(hasattr(UpperCAmelCase_ , """do_normalize""" ) ) def lowerCAmelCase ( self : Optional[int] ) ->Optional[Any]: """simple docstring""" snake_case_ = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""height""": 18, """width""": 18} ) snake_case_ = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {"""height""": 42, """width""": 42} ) def lowerCAmelCase ( self : Any ) ->List[Any]: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) snake_case_ = json.loads(image_processor.to_json_string() ) for key, value in self.image_processor_dict.items(): if key == "clusters": self.assertTrue(np.array_equal(UpperCAmelCase_ , obj[key] ) ) else: self.assertEqual(obj[key] , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] ) ->Dict: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: snake_case_ = os.path.join(UpperCAmelCase_ , """image_processor.json""" ) image_processor_first.to_json_file(UpperCAmelCase_ ) snake_case_ = self.image_processing_class.from_json_file(UpperCAmelCase_ ).to_dict() snake_case_ = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(UpperCAmelCase_ , image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] , UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->List[Any]: """simple docstring""" snake_case_ = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: image_processor_first.save_pretrained(UpperCAmelCase_ ) snake_case_ = self.image_processing_class.from_pretrained(UpperCAmelCase_ ).to_dict() snake_case_ = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(UpperCAmelCase_ , image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] , UpperCAmelCase_ ) @unittest.skip("""ImageGPT requires clusters at initialization""" ) def lowerCAmelCase ( self : List[Any] ) ->Tuple: """simple docstring""" pass def _a ( ) -> str: snake_case_ = load_dataset("""hf-internal-testing/fixtures_image_utils""" , split="""test""" ) snake_case_ = Image.open(dataset[4]["""file"""] ) snake_case_ = Image.open(dataset[5]["""file"""] ) snake_case_ = [imagea, imagea] return images @require_vision @require_torch class __A (unittest.TestCase): '''simple docstring''' @slow def lowerCAmelCase ( self : Tuple ) ->List[str]: """simple docstring""" snake_case_ = ImageGPTImageProcessor.from_pretrained("""openai/imagegpt-small""" ) snake_case_ = prepare_images() # test non-batched snake_case_ = image_processing(images[0] , return_tensors="""pt""" ) self.assertIsInstance(encoding.input_ids , torch.LongTensor ) self.assertEqual(encoding.input_ids.shape , (1, 1_024) ) snake_case_ = [306, 191, 191] self.assertEqual(encoding.input_ids[0, :3].tolist() , UpperCAmelCase_ ) # test batched snake_case_ = image_processing(UpperCAmelCase_ , return_tensors="""pt""" ) self.assertIsInstance(encoding.input_ids , torch.LongTensor ) self.assertEqual(encoding.input_ids.shape , (2, 1_024) ) snake_case_ = [303, 13, 13] self.assertEqual(encoding.input_ids[1, -3:].tolist() , UpperCAmelCase_ )
2
0
def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None ) -> Dict: snake_case_ = (path or []) + [u] for v in graph[u]: if visited_edge[u][v] is False: snake_case_ , snake_case_ = True, True snake_case_ = dfs(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return path def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[Any]: snake_case_ = 0 snake_case_ = -1 for i in range(_SCREAMING_SNAKE_CASE ): if i not in graph.keys(): continue if len(graph[i] ) % 2 == 1: odd_degree_nodes += 1 snake_case_ = i if odd_degree_nodes == 0: return 1, odd_node if odd_degree_nodes == 2: return 2, odd_node return 3, odd_node def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: snake_case_ = [[False for _ in range(max_node + 1 )] for _ in range(max_node + 1 )] snake_case_ , snake_case_ = check_circuit_or_path(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if check == 3: print("""graph is not Eulerian""" ) print("""no path""" ) return snake_case_ = 1 if check == 2: snake_case_ = odd_node print("""graph has a Euler path""" ) if check == 1: print("""graph has a Euler cycle""" ) snake_case_ = dfs(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) print(_SCREAMING_SNAKE_CASE ) def _a ( ) -> Any: snake_case_ = {1: [2, 3, 4], 2: [1, 3], 3: [1, 2], 4: [1, 5], 5: [4]} snake_case_ = {1: [2, 3, 4, 5], 2: [1, 3], 3: [1, 2], 4: [1, 5], 5: [1, 4]} snake_case_ = {1: [2, 3, 4], 2: [1, 3, 4], 3: [1, 2], 4: [1, 2, 5], 5: [4]} snake_case_ = {1: [2, 3], 2: [1, 3], 3: [1, 2]} snake_case_ = { 1: [], 2: [] # all degree is zero } snake_case_ = 10 check_euler(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) check_euler(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) check_euler(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) check_euler(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) check_euler(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
713
"""simple docstring""" import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, ) from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST class __A : '''simple docstring''' def __init__( self : Optional[int] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[Any]=13 , UpperCAmelCase_ : Optional[int]=7 , UpperCAmelCase_ : List[str]=True , UpperCAmelCase_ : int=True , UpperCAmelCase_ : List[Any]=True , UpperCAmelCase_ : Optional[int]=True , UpperCAmelCase_ : List[str]=99 , UpperCAmelCase_ : Dict=24 , UpperCAmelCase_ : List[str]=2 , UpperCAmelCase_ : Optional[Any]=6 , UpperCAmelCase_ : int=37 , UpperCAmelCase_ : Optional[Any]="gelu" , UpperCAmelCase_ : Optional[Any]=0.1 , UpperCAmelCase_ : List[Any]=0.1 , UpperCAmelCase_ : Any=512 , UpperCAmelCase_ : str=16 , UpperCAmelCase_ : List[str]=2 , UpperCAmelCase_ : Optional[int]=0.02 , UpperCAmelCase_ : Tuple=3 , UpperCAmelCase_ : Union[str, Any]=None , UpperCAmelCase_ : Any=1_000 , ) ->Tuple: """simple docstring""" snake_case_ = parent snake_case_ = batch_size snake_case_ = seq_length snake_case_ = is_training snake_case_ = use_input_mask snake_case_ = use_token_type_ids snake_case_ = use_labels snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = max_position_embeddings snake_case_ = type_vocab_size snake_case_ = type_sequence_label_size snake_case_ = initializer_range snake_case_ = num_labels snake_case_ = scope snake_case_ = range_bbox def lowerCAmelCase ( self : Tuple ) ->int: """simple docstring""" snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case_ = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox ) # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: snake_case_ = bbox[i, j, 3] snake_case_ = bbox[i, j, 1] snake_case_ = t if bbox[i, j, 2] < bbox[i, j, 0]: snake_case_ = bbox[i, j, 2] snake_case_ = bbox[i, j, 0] snake_case_ = t snake_case_ = None if self.use_input_mask: snake_case_ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) snake_case_ = None if self.use_token_type_ids: snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) snake_case_ = None snake_case_ = None if self.use_labels: snake_case_ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) snake_case_ = self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def lowerCAmelCase ( self : int ) ->Optional[int]: """simple docstring""" return LiltConfig( 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 , ) def lowerCAmelCase ( self : Any , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Any , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[int] , ) ->str: """simple docstring""" snake_case_ = LiltModel(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ , bbox=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ ) snake_case_ = model(UpperCAmelCase_ , bbox=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ ) snake_case_ = model(UpperCAmelCase_ , bbox=UpperCAmelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def lowerCAmelCase ( self : int , UpperCAmelCase_ : str , UpperCAmelCase_ : Any , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : str , UpperCAmelCase_ : List[Any] , ) ->Dict: """simple docstring""" snake_case_ = self.num_labels snake_case_ = LiltForTokenClassification(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model( UpperCAmelCase_ , bbox=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowerCAmelCase ( self : Any , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : str , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : int , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : List[str] , ) ->Dict: """simple docstring""" snake_case_ = LiltForQuestionAnswering(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model( UpperCAmelCase_ , bbox=UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , start_positions=UpperCAmelCase_ , end_positions=UpperCAmelCase_ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def lowerCAmelCase ( self : int ) ->Optional[int]: """simple docstring""" snake_case_ = self.prepare_config_and_inputs() ( ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ( snake_case_ ) , ) = config_and_inputs snake_case_ = { """input_ids""": input_ids, """bbox""": bbox, """token_type_ids""": token_type_ids, """attention_mask""": input_mask, } return config, inputs_dict @require_torch class __A (snake_case__ , snake_case__ , snake_case__ , unittest.TestCase): '''simple docstring''' __lowercase: Optional[int] = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) __lowercase: Optional[Any] = ( { """feature-extraction""": LiltModel, """question-answering""": LiltForQuestionAnswering, """text-classification""": LiltForSequenceClassification, """token-classification""": LiltForTokenClassification, """zero-shot""": LiltForSequenceClassification, } if is_torch_available() else {} ) __lowercase: Union[str, Any] = False __lowercase: List[str] = False def lowerCAmelCase ( self : str , UpperCAmelCase_ : int , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[int] ) ->Optional[int]: """simple docstring""" return True def lowerCAmelCase ( self : Dict ) ->Union[str, Any]: """simple docstring""" snake_case_ = LiltModelTester(self ) snake_case_ = ConfigTester(self , config_class=UpperCAmelCase_ , hidden_size=37 ) def lowerCAmelCase ( self : str ) ->List[Any]: """simple docstring""" self.config_tester.run_common_tests() def lowerCAmelCase ( self : List[str] ) ->int: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] ) ->List[str]: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: snake_case_ = type self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def lowerCAmelCase ( self : List[Any] ) ->Dict: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[Any] ) ->Dict: """simple docstring""" snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*UpperCAmelCase_ ) @slow def lowerCAmelCase ( self : Union[str, Any] ) ->Optional[int]: """simple docstring""" for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ = LiltModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) @require_torch @slow class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : Optional[int] ) ->Dict: """simple docstring""" snake_case_ = LiltModel.from_pretrained("""SCUT-DLVCLab/lilt-roberta-en-base""" ).to(UpperCAmelCase_ ) snake_case_ = torch.tensor([[1, 2]] , device=UpperCAmelCase_ ) snake_case_ = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=UpperCAmelCase_ ) # forward pass with torch.no_grad(): snake_case_ = model(input_ids=UpperCAmelCase_ , bbox=UpperCAmelCase_ ) snake_case_ = torch.Size([1, 2, 768] ) snake_case_ = torch.tensor( [[-0.0_653, 0.0_950, -0.0_061], [-0.0_545, 0.0_926, -0.0_324]] , device=UpperCAmelCase_ , ) self.assertTrue(outputs.last_hidden_state.shape , UpperCAmelCase_ ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , UpperCAmelCase_ , atol=1E-3 ) )
2
0
"""simple docstring""" import argparse import os import re import packaging.version __SCREAMING_SNAKE_CASE : Optional[Any] = 'examples/' __SCREAMING_SNAKE_CASE : int = { 'examples': (re.compile(R'^check_min_version\("[^"]+"\)\s*$', re.MULTILINE), 'check_min_version("VERSION")\n'), 'init': (re.compile(R'^__version__\s+=\s+"([^"]+)"\s*$', re.MULTILINE), '__version__ = "VERSION"\n'), 'setup': (re.compile(R'^(\s*)version\s*=\s*"[^"]+",', re.MULTILINE), R'\1version="VERSION",'), 'doc': (re.compile(R'^(\s*)release\s*=\s*"[^"]+"$', re.MULTILINE), 'release = "VERSION"\n'), } __SCREAMING_SNAKE_CASE : Optional[int] = { 'init': 'src/transformers/__init__.py', 'setup': 'setup.py', } __SCREAMING_SNAKE_CASE : List[Any] = 'README.md' def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Dict: with open(_SCREAMING_SNAKE_CASE , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: snake_case_ = f.read() snake_case_ , snake_case_ = REPLACE_PATTERNS[pattern] snake_case_ = replace.replace("""VERSION""" , _SCREAMING_SNAKE_CASE ) snake_case_ = re_pattern.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) with open(_SCREAMING_SNAKE_CASE , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f: f.write(_SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE ) -> int: for folder, directories, fnames in os.walk(_SCREAMING_SNAKE_CASE ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove("""research_projects""" ) if "legacy" in directories: directories.remove("""legacy""" ) for fname in fnames: if fname.endswith(""".py""" ): update_version_in_file(os.path.join(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE , pattern="""examples""" ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) -> Union[str, Any]: for pattern, fname in REPLACE_FILES.items(): update_version_in_file(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if not patch: update_version_in_examples(_SCREAMING_SNAKE_CASE ) def _a ( ) -> Union[str, Any]: snake_case_ = """🤗 Transformers currently provides the following architectures""" snake_case_ = """1. Want to contribute a new model?""" with open(_SCREAMING_SNAKE_CASE , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: snake_case_ = f.readlines() # Find the start of the list. snake_case_ = 0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 snake_case_ = start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith("""1.""" ): snake_case_ = lines[index].replace( """https://huggingface.co/docs/transformers/main/model_doc""" , """https://huggingface.co/docs/transformers/model_doc""" , ) index += 1 with open(_SCREAMING_SNAKE_CASE , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f: f.writelines(_SCREAMING_SNAKE_CASE ) def _a ( ) -> List[str]: with open(REPLACE_FILES["""init"""] , """r""" ) as f: snake_case_ = f.read() snake_case_ = REPLACE_PATTERNS["""init"""][0].search(_SCREAMING_SNAKE_CASE ).groups()[0] return packaging.version.parse(_SCREAMING_SNAKE_CASE ) def _a ( _SCREAMING_SNAKE_CASE=False ) -> List[str]: snake_case_ = get_version() if patch and default_version.is_devrelease: raise ValueError("""Can't create a patch version from the dev branch, checkout a released version!""" ) if default_version.is_devrelease: snake_case_ = default_version.base_version elif patch: snake_case_ = f"""{default_version.major}.{default_version.minor}.{default_version.micro + 1}""" else: snake_case_ = f"""{default_version.major}.{default_version.minor + 1}.0""" # Now let's ask nicely if that's the right one. snake_case_ = input(f"""Which version are you releasing? [{default_version}]""" ) if len(_SCREAMING_SNAKE_CASE ) == 0: snake_case_ = default_version print(f"""Updating version to {version}.""" ) global_version_update(_SCREAMING_SNAKE_CASE , patch=_SCREAMING_SNAKE_CASE ) if not patch: print("""Cleaning main README, don't forget to run `make fix-copies`.""" ) clean_main_ref_in_model_list() def _a ( ) -> Optional[int]: snake_case_ = get_version() snake_case_ = f"""{current_version.major}.{current_version.minor + 1}.0.dev0""" snake_case_ = current_version.base_version # Check with the user we got that right. snake_case_ = input(f"""Which version are we developing now? [{dev_version}]""" ) if len(_SCREAMING_SNAKE_CASE ) == 0: snake_case_ = dev_version print(f"""Updating version to {version}.""" ) global_version_update(_SCREAMING_SNAKE_CASE ) print("""Cleaning main README, don't forget to run `make fix-copies`.""" ) clean_main_ref_in_model_list() if __name__ == "__main__": __SCREAMING_SNAKE_CASE : str = argparse.ArgumentParser() parser.add_argument('--post_release', action='store_true', help='Whether this is pre or post release.') parser.add_argument('--patch', action='store_true', help='Whether or not this is a patch release.') __SCREAMING_SNAKE_CASE : Any = parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print('Nothing to do after a patch :-)') else: post_release_work()
714
"""simple docstring""" from __future__ import annotations def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> list[int]: snake_case_ = 0 snake_case_ = len(_SCREAMING_SNAKE_CASE ) - 1 while i < j: if nums[i] + nums[j] == target: return [i, j] elif nums[i] + nums[j] < target: snake_case_ = i + 1 else: snake_case_ = j - 1 return [] if __name__ == "__main__": import doctest doctest.testmod() print(f"""{two_pointer([2, 7, 11, 15], 9) = }""")
2
0
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> int: if index == number_of_items: return 0 snake_case_ = 0 snake_case_ = 0 snake_case_ = knapsack(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , index + 1 ) if weights[index] <= max_weight: snake_case_ = values[index] + knapsack( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , max_weight - weights[index] , index + 1 ) return max(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": import doctest doctest.testmod()
715
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __SCREAMING_SNAKE_CASE : Optional[Any] = { 'configuration_biogpt': ['BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BioGptConfig'], 'tokenization_biogpt': ['BioGptTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : Optional[Any] = [ 'BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST', 'BioGptForCausalLM', 'BioGptForTokenClassification', 'BioGptForSequenceClassification', 'BioGptModel', 'BioGptPreTrainedModel', ] if TYPE_CHECKING: from .configuration_biogpt import BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, BioGptConfig from .tokenization_biogpt import BioGptTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_biogpt import ( BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptPreTrainedModel, ) else: import sys __SCREAMING_SNAKE_CASE : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
2
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging __SCREAMING_SNAKE_CASE : Union[str, Any] = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : List[str] = {'ctrl': 'https://huggingface.co/ctrl/resolve/main/config.json'} class __A (snake_case__): '''simple docstring''' __lowercase: Dict = """ctrl""" __lowercase: Optional[Any] = ["""past_key_values"""] __lowercase: Optional[Any] = { """max_position_embeddings""": """n_positions""", """hidden_size""": """n_embd""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self : List[str] , UpperCAmelCase_ : Dict=246_534 , UpperCAmelCase_ : List[Any]=256 , UpperCAmelCase_ : Dict=1_280 , UpperCAmelCase_ : List[str]=8_192 , UpperCAmelCase_ : str=48 , UpperCAmelCase_ : List[str]=16 , UpperCAmelCase_ : Union[str, Any]=0.1 , UpperCAmelCase_ : List[str]=0.1 , UpperCAmelCase_ : List[str]=1E-6 , UpperCAmelCase_ : List[Any]=0.02 , UpperCAmelCase_ : int=True , **UpperCAmelCase_ : int , ) ->Dict: """simple docstring""" snake_case_ = vocab_size snake_case_ = n_positions snake_case_ = n_embd snake_case_ = n_layer snake_case_ = n_head snake_case_ = dff snake_case_ = resid_pdrop snake_case_ = embd_pdrop snake_case_ = layer_norm_epsilon snake_case_ = initializer_range snake_case_ = use_cache super().__init__(**UpperCAmelCase_ )
716
"""simple docstring""" __SCREAMING_SNAKE_CASE : str = 'Input must be a string of 8 numbers plus letter' __SCREAMING_SNAKE_CASE : Dict = 'TRWAGMYFPDXBNJZSQVHLCKE' def _a ( _SCREAMING_SNAKE_CASE ) -> bool: if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): snake_case_ = f"""Expected string as input, found {type(_SCREAMING_SNAKE_CASE ).__name__}""" raise TypeError(_SCREAMING_SNAKE_CASE ) snake_case_ = spanish_id.replace("""-""" , """""" ).upper() if len(_SCREAMING_SNAKE_CASE ) != 9: raise ValueError(_SCREAMING_SNAKE_CASE ) try: snake_case_ = int(spanish_id_clean[0:8] ) snake_case_ = spanish_id_clean[8] except ValueError as ex: raise ValueError(_SCREAMING_SNAKE_CASE ) from ex if letter.isdigit(): raise ValueError(_SCREAMING_SNAKE_CASE ) return letter == LOOKUP_LETTERS[number % 23] if __name__ == "__main__": import doctest doctest.testmod()
2
0
"""simple docstring""" import warnings from transformers import AutoTokenizer from transformers.utils import is_torch_available from transformers.utils.generic import ExplicitEnum from ...processing_utils import ProcessorMixin if is_torch_available(): import torch class __A (snake_case__): '''simple docstring''' __lowercase: List[str] = """char""" __lowercase: Any = """bpe""" __lowercase: Dict = """wp""" __SCREAMING_SNAKE_CASE : Any = (DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE) class __A (snake_case__): '''simple docstring''' __lowercase: str = ["""image_processor""", """char_tokenizer"""] __lowercase: Union[str, Any] = """ViTImageProcessor""" __lowercase: Any = """MgpstrTokenizer""" def __init__( self : Optional[Any] , UpperCAmelCase_ : Optional[int]=None , UpperCAmelCase_ : int=None , **UpperCAmelCase_ : Dict ) ->Dict: """simple docstring""" snake_case_ = None if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" , UpperCAmelCase_ , ) snake_case_ = kwargs.pop("""feature_extractor""" ) snake_case_ = 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`.""" ) snake_case_ = tokenizer snake_case_ = AutoTokenizer.from_pretrained("""gpt2""" ) snake_case_ = AutoTokenizer.from_pretrained("""bert-base-uncased""" ) super().__init__(UpperCAmelCase_ , UpperCAmelCase_ ) def __call__( self : Optional[Any] , UpperCAmelCase_ : int=None , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : Union[str, Any]=None , **UpperCAmelCase_ : Any ) ->Any: """simple docstring""" if images is None and text is None: raise ValueError("""You need to specify either an `images` or `text` input to process.""" ) if images is not None: snake_case_ = self.image_processor(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_ ) if text is not None: snake_case_ = self.char_tokenizer(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_ ) if text is None: return inputs elif images is None: return encodings else: snake_case_ = encodings["""input_ids"""] return inputs def lowerCAmelCase ( self : Any , UpperCAmelCase_ : List[str] ) ->List[str]: """simple docstring""" snake_case_ , snake_case_ , snake_case_ = sequences snake_case_ = char_preds.size(0 ) snake_case_ , snake_case_ = self._decode_helper(UpperCAmelCase_ , """char""" ) snake_case_ , snake_case_ = self._decode_helper(UpperCAmelCase_ , """bpe""" ) snake_case_ , snake_case_ = self._decode_helper(UpperCAmelCase_ , """wp""" ) snake_case_ = [] snake_case_ = [] for i in range(UpperCAmelCase_ ): snake_case_ = [char_scores[i], bpe_scores[i], wp_scores[i]] snake_case_ = [char_strs[i], bpe_strs[i], wp_strs[i]] snake_case_ = scores.index(max(UpperCAmelCase_ ) ) final_strs.append(strs[max_score_index] ) final_scores.append(scores[max_score_index] ) snake_case_ = {} snake_case_ = final_strs snake_case_ = final_scores snake_case_ = char_strs snake_case_ = bpe_strs snake_case_ = wp_strs return out def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : Any , UpperCAmelCase_ : Optional[Any] ) ->Optional[Any]: """simple docstring""" if format == DecodeType.CHARACTER: snake_case_ = self.char_decode snake_case_ = 1 snake_case_ = """[s]""" elif format == DecodeType.BPE: snake_case_ = self.bpe_decode snake_case_ = 2 snake_case_ = """#""" elif format == DecodeType.WORDPIECE: snake_case_ = self.wp_decode snake_case_ = 102 snake_case_ = """[SEP]""" else: raise ValueError(F"""Format {format} is not supported.""" ) snake_case_ , snake_case_ = [], [] snake_case_ = pred_logits.size(0 ) snake_case_ = pred_logits.size(1 ) snake_case_ , snake_case_ = pred_logits.topk(1 , dim=-1 , largest=UpperCAmelCase_ , sorted=UpperCAmelCase_ ) snake_case_ = preds_index.view(-1 , UpperCAmelCase_ )[:, 1:] snake_case_ = decoder(UpperCAmelCase_ ) snake_case_ , snake_case_ = torch.nn.functional.softmax(UpperCAmelCase_ , dim=2 ).max(dim=2 ) snake_case_ = preds_max_prob[:, 1:] for index in range(UpperCAmelCase_ ): snake_case_ = preds_str[index].find(UpperCAmelCase_ ) snake_case_ = preds_str[index][:pred_eos] snake_case_ = preds_index[index].cpu().tolist() snake_case_ = pred_index.index(UpperCAmelCase_ ) if eos_token in pred_index else -1 snake_case_ = preds_max_prob[index][: pred_eos_index + 1] snake_case_ = pred_max_prob.cumprod(dim=0 )[-1] if pred_max_prob.nelement() != 0 else 0.0 dec_strs.append(UpperCAmelCase_ ) conf_scores.append(UpperCAmelCase_ ) return dec_strs, conf_scores def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : str ) ->Dict: """simple docstring""" snake_case_ = [seq.replace(""" """ , """""" ) for seq in self.char_tokenizer.batch_decode(UpperCAmelCase_ )] return decode_strs def lowerCAmelCase ( self : List[str] , UpperCAmelCase_ : Optional[Any] ) ->str: """simple docstring""" return self.bpe_tokenizer.batch_decode(UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : Union[str, Any] ) ->str: """simple docstring""" snake_case_ = [seq.replace(""" """ , """""" ) for seq in self.wp_tokenizer.batch_decode(UpperCAmelCase_ )] return decode_strs
717
"""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 logging __SCREAMING_SNAKE_CASE : List[str] = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Optional[int] = {'vocab_file': 'spiece.model'} __SCREAMING_SNAKE_CASE : List[str] = { 'vocab_file': { 'albert-base-v1': 'https://huggingface.co/albert-base-v1/resolve/main/spiece.model', 'albert-large-v1': 'https://huggingface.co/albert-large-v1/resolve/main/spiece.model', 'albert-xlarge-v1': 'https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model', 'albert-xxlarge-v1': 'https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model', 'albert-base-v2': 'https://huggingface.co/albert-base-v2/resolve/main/spiece.model', 'albert-large-v2': 'https://huggingface.co/albert-large-v2/resolve/main/spiece.model', 'albert-xlarge-v2': 'https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model', 'albert-xxlarge-v2': 'https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model', } } __SCREAMING_SNAKE_CASE : List[str] = { 'albert-base-v1': 512, 'albert-large-v1': 512, 'albert-xlarge-v1': 512, 'albert-xxlarge-v1': 512, 'albert-base-v2': 512, 'albert-large-v2': 512, 'albert-xlarge-v2': 512, 'albert-xxlarge-v2': 512, } __SCREAMING_SNAKE_CASE : int = '▁' class __A (snake_case__): '''simple docstring''' __lowercase: Optional[Any] = VOCAB_FILES_NAMES __lowercase: Optional[int] = PRETRAINED_VOCAB_FILES_MAP __lowercase: Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : int , UpperCAmelCase_ : Any , UpperCAmelCase_ : Dict=True , UpperCAmelCase_ : Dict=True , UpperCAmelCase_ : List[str]=False , UpperCAmelCase_ : List[Any]="[CLS]" , UpperCAmelCase_ : Any="[SEP]" , UpperCAmelCase_ : str="<unk>" , UpperCAmelCase_ : str="[SEP]" , UpperCAmelCase_ : Optional[Any]="<pad>" , UpperCAmelCase_ : Optional[int]="[CLS]" , UpperCAmelCase_ : int="[MASK]" , UpperCAmelCase_ : Optional[Dict[str, Any]] = None , **UpperCAmelCase_ : Union[str, Any] , ) ->None: """simple docstring""" snake_case_ = ( AddedToken(UpperCAmelCase_ , lstrip=UpperCAmelCase_ , rstrip=UpperCAmelCase_ , normalized=UpperCAmelCase_ ) if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) else mask_token ) snake_case_ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=UpperCAmelCase_ , remove_space=UpperCAmelCase_ , keep_accents=UpperCAmelCase_ , bos_token=UpperCAmelCase_ , eos_token=UpperCAmelCase_ , unk_token=UpperCAmelCase_ , sep_token=UpperCAmelCase_ , pad_token=UpperCAmelCase_ , cls_token=UpperCAmelCase_ , mask_token=UpperCAmelCase_ , sp_model_kwargs=self.sp_model_kwargs , **UpperCAmelCase_ , ) snake_case_ = do_lower_case snake_case_ = remove_space snake_case_ = keep_accents snake_case_ = vocab_file snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(UpperCAmelCase_ ) @property def lowerCAmelCase ( self : List[Any] ) ->Dict: """simple docstring""" return len(self.sp_model ) def lowerCAmelCase ( self : str ) ->List[Any]: """simple docstring""" snake_case_ = {self.convert_ids_to_tokens(UpperCAmelCase_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Dict ) ->List[str]: """simple docstring""" snake_case_ = self.__dict__.copy() snake_case_ = None return state def __setstate__( self : Tuple , UpperCAmelCase_ : Optional[int] ) ->Optional[int]: """simple docstring""" snake_case_ = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): snake_case_ = {} snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : Any ) ->str: """simple docstring""" if self.remove_space: snake_case_ = """ """.join(inputs.strip().split() ) else: snake_case_ = inputs snake_case_ = outputs.replace("""``""" , """\"""" ).replace("""''""" , """\"""" ) if not self.keep_accents: snake_case_ = unicodedata.normalize("""NFKD""" , UpperCAmelCase_ ) snake_case_ = """""".join([c for c in outputs if not unicodedata.combining(UpperCAmelCase_ )] ) if self.do_lower_case: snake_case_ = outputs.lower() return outputs def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : str ) ->List[str]: """simple docstring""" snake_case_ = self.preprocess_text(UpperCAmelCase_ ) snake_case_ = self.sp_model.encode(UpperCAmelCase_ , out_type=UpperCAmelCase_ ) snake_case_ = [] for piece in pieces: if len(UpperCAmelCase_ ) > 1 and piece[-1] == str(""",""" ) and piece[-2].isdigit(): snake_case_ = self.sp_model.EncodeAsPieces(piece[:-1].replace(UpperCAmelCase_ , """""" ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: snake_case_ = cur_pieces[1:] else: snake_case_ = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(UpperCAmelCase_ ) else: new_pieces.append(UpperCAmelCase_ ) return new_pieces def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : Optional[int] ) ->Dict: """simple docstring""" return self.sp_model.PieceToId(UpperCAmelCase_ ) def lowerCAmelCase ( self : str , UpperCAmelCase_ : Union[str, Any] ) ->Optional[int]: """simple docstring""" return self.sp_model.IdToPiece(UpperCAmelCase_ ) def lowerCAmelCase ( self : str , UpperCAmelCase_ : Dict ) ->Any: """simple docstring""" snake_case_ = [] snake_case_ = """""" snake_case_ = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(UpperCAmelCase_ ) + token snake_case_ = True snake_case_ = [] else: current_sub_tokens.append(UpperCAmelCase_ ) snake_case_ = False out_string += self.sp_model.decode(UpperCAmelCase_ ) return out_string.strip() def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ) ->List[int]: """simple docstring""" snake_case_ = [self.sep_token_id] snake_case_ = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None , UpperCAmelCase_ : bool = False ) ->List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=UpperCAmelCase_ , token_ids_a=UpperCAmelCase_ , already_has_special_tokens=UpperCAmelCase_ ) if token_ids_a is not None: return [1] + ([0] * len(UpperCAmelCase_ )) + [1] + ([0] * len(UpperCAmelCase_ )) + [1] return [1] + ([0] * len(UpperCAmelCase_ )) + [1] def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ) ->List[int]: """simple docstring""" snake_case_ = [self.sep_token_id] snake_case_ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def lowerCAmelCase ( self : str , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None ) ->Tuple[str]: """simple docstring""" if not os.path.isdir(UpperCAmelCase_ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return snake_case_ = os.path.join( UpperCAmelCase_ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCAmelCase_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , UpperCAmelCase_ ) elif not os.path.isfile(self.vocab_file ): with open(UpperCAmelCase_ , """wb""" ) as fi: snake_case_ = self.sp_model.serialized_model_proto() fi.write(UpperCAmelCase_ ) return (out_vocab_file,)
2
0
"""simple docstring""" import argparse import torch from transformers import ( UniSpeechSatConfig, UniSpeechSatForAudioFrameClassification, UniSpeechSatForSequenceClassification, UniSpeechSatForXVector, WavaVecaFeatureExtractor, logging, ) logging.set_verbosity_info() __SCREAMING_SNAKE_CASE : List[str] = logging.get_logger(__name__) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: snake_case_ = UniSpeechSatForSequenceClassification.from_pretrained(_SCREAMING_SNAKE_CASE , config=_SCREAMING_SNAKE_CASE ) snake_case_ = downstream_dict["""projector.weight"""] snake_case_ = downstream_dict["""projector.bias"""] snake_case_ = downstream_dict["""model.post_net.linear.weight"""] snake_case_ = downstream_dict["""model.post_net.linear.bias"""] return model def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[Any]: snake_case_ = UniSpeechSatForAudioFrameClassification.from_pretrained(_SCREAMING_SNAKE_CASE , config=_SCREAMING_SNAKE_CASE ) snake_case_ = downstream_dict["""model.linear.weight"""] snake_case_ = downstream_dict["""model.linear.bias"""] return model def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple: snake_case_ = UniSpeechSatForXVector.from_pretrained(_SCREAMING_SNAKE_CASE , config=_SCREAMING_SNAKE_CASE ) snake_case_ = downstream_dict["""connector.weight"""] snake_case_ = downstream_dict["""connector.bias"""] for i, kernel_size in enumerate(hf_config.tdnn_kernel ): snake_case_ = downstream_dict[ f"""model.framelevel_feature_extractor.module.{i}.kernel.weight""" ] snake_case_ = downstream_dict[f"""model.framelevel_feature_extractor.module.{i}.kernel.bias"""] snake_case_ = downstream_dict["""model.utterancelevel_feature_extractor.linear1.weight"""] snake_case_ = downstream_dict["""model.utterancelevel_feature_extractor.linear1.bias"""] snake_case_ = downstream_dict["""model.utterancelevel_feature_extractor.linear2.weight"""] snake_case_ = downstream_dict["""model.utterancelevel_feature_extractor.linear2.bias"""] snake_case_ = downstream_dict["""objective.W"""] return model @torch.no_grad() def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[Any]: snake_case_ = torch.load(_SCREAMING_SNAKE_CASE , map_location="""cpu""" ) snake_case_ = checkpoint["""Downstream"""] snake_case_ = UniSpeechSatConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) snake_case_ = WavaVecaFeatureExtractor.from_pretrained( _SCREAMING_SNAKE_CASE , return_attention_mask=_SCREAMING_SNAKE_CASE , do_normalize=_SCREAMING_SNAKE_CASE ) snake_case_ = hf_config.architectures[0] if arch.endswith("""ForSequenceClassification""" ): snake_case_ = convert_classification(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif arch.endswith("""ForAudioFrameClassification""" ): snake_case_ = convert_diarization(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif arch.endswith("""ForXVector""" ): snake_case_ = convert_xvector(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else: raise NotImplementedError(f"""S3PRL weights conversion is not supported for {arch}""" ) if hf_config.use_weighted_layer_sum: snake_case_ = checkpoint["""Featurizer"""]["""weights"""] hf_feature_extractor.save_pretrained(_SCREAMING_SNAKE_CASE ) hf_model.save_pretrained(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : Tuple = argparse.ArgumentParser() parser.add_argument( '--base_model_name', default=None, type=str, help='Name of the huggingface pretrained base model.' ) parser.add_argument('--config_path', default=None, type=str, help='Path to the huggingface classifier config.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to the s3prl checkpoint.') parser.add_argument('--model_dump_path', default=None, type=str, help='Path to the final converted model.') __SCREAMING_SNAKE_CASE : Any = parser.parse_args() convert_saprl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path)
718
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE ) -> list: # bit count represents no. of bits in the gray code if bit_count < 0: raise ValueError("""The given input must be positive""" ) # get the generated string sequence snake_case_ = gray_code_sequence_string(_SCREAMING_SNAKE_CASE ) # # convert them to integers for i in range(len(_SCREAMING_SNAKE_CASE ) ): snake_case_ = int(sequence[i] , 2 ) return sequence def _a ( _SCREAMING_SNAKE_CASE ) -> list: # The approach is a recursive one # Base case achieved when either n = 0 or n=1 if bit_count == 0: return ["0"] if bit_count == 1: return ["0", "1"] snake_case_ = 1 << bit_count # defines the length of the sequence # 1<< n is equivalent to 2^n # recursive answer will generate answer for n-1 bits snake_case_ = gray_code_sequence_string(bit_count - 1 ) snake_case_ = [] # append 0 to first half of the smaller sequence generated for i in range(seq_len // 2 ): snake_case_ = """0""" + smaller_sequence[i] sequence.append(_SCREAMING_SNAKE_CASE ) # append 1 to second half ... start from the end of the list for i in reversed(range(seq_len // 2 ) ): snake_case_ = """1""" + smaller_sequence[i] sequence.append(_SCREAMING_SNAKE_CASE ) return sequence if __name__ == "__main__": import doctest doctest.testmod()
2
0
import argparse import json import os from pathlib import Path import requests import torch from transformers import JukeboxConfig, JukeboxModel from transformers.utils import logging logging.set_verbosity_info() __SCREAMING_SNAKE_CASE : str = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Optional[int] = 'https://openaipublic.azureedge.net/jukebox/models/' __SCREAMING_SNAKE_CASE : List[Any] = { 'jukebox-1b-lyrics': [ '5b/vqvae.pth.tar', '5b/prior_level_0.pth.tar', '5b/prior_level_1.pth.tar', '1b_lyrics/prior_level_2.pth.tar', ], 'jukebox-5b-lyrics': [ '5b/vqvae.pth.tar', '5b/prior_level_0.pth.tar', '5b/prior_level_1.pth.tar', '5b_lyrics/prior_level_2.pth.tar', ], } def _a ( _SCREAMING_SNAKE_CASE ) -> int: if key.endswith(""".model.1.bias""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.1.bias""" , """.conv1d_1.bias""" ) elif key.endswith(""".model.1.weight""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.1.weight""" , """.conv1d_1.weight""" ) elif key.endswith(""".model.3.bias""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.3.bias""" , """.conv1d_2.bias""" ) elif key.endswith(""".model.3.weight""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.3.weight""" , """.conv1d_2.weight""" ) if "conditioner_blocks.0." in key: snake_case_ = key.replace("""conditioner_blocks.0""" , """conditioner_blocks""" ) if "prime_prior" in key: snake_case_ = key.replace("""prime_prior""" , """encoder""" ) if ".emb." in key and "total" not in key and "absolute" not in key and "relative" not in key: snake_case_ = key.replace(""".emb.""" , """.""" ) if key.endswith("""k""" ): # replace vqvae.X.k with vqvae.X.codebook return key.replace(""".k""" , """.codebook""" ) if "y_emb." in key: return key.replace("""y_emb.""" , """metadata_embedding.""" ) if "x_emb.emb." in key: snake_case_ = key.replace("""0.x_emb.emb""" , """embed_tokens""" ) if "prime_state_ln" in key: return key.replace("""prime_state_ln""" , """encoder.final_layer_norm""" ) if ".ln" in key: return key.replace(""".ln""" , """.layer_norm""" ) if "_ln" in key: return key.replace("""_ln""" , """_layer_norm""" ) if "prime_state_proj" in key: return key.replace("""prime_state_proj""" , """encoder.proj_in""" ) if "prime_x_out" in key: return key.replace("""prime_x_out""" , """encoder.lm_head""" ) if "prior.x_out" in key: return key.replace("""x_out""" , """fc_proj_out""" ) if "x_emb" in key: return key.replace("""x_emb""" , """embed_tokens""" ) return key def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: snake_case_ = {} import re snake_case_ = re.compile(r"""encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)""" ) snake_case_ = re.compile( r"""encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""encoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)""" ) snake_case_ = re.compile( r"""decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""decoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""conditioner_blocks.(\d*).cond.model.(\d*).(\d).(bias|weight)""" ) snake_case_ = re.compile( r"""conditioner_blocks.(\d*).cond.model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""conditioner_blocks.(\d*).cond.model.(\d*).(bias|weight)""" ) for original_key, value in state_dict.items(): # rename vqvae.encoder keys if re_encoder_block_conv_in.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_encoder_block_conv_in.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) snake_case_ = f"""encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.{groups[-1]}""" snake_case_ = re_encoder_block_conv_in.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_encoder_block_resnet.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_encoder_block_resnet.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) snake_case_ = {"""1""": 1, """3""": 2}[groups[-2]] snake_case_ = f"""encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.""" snake_case_ = f"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}""" snake_case_ = prefix + resnet_block snake_case_ = re_encoder_block_resnet.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_encoder_block_proj_out.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_encoder_block_proj_out.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = f"""encoders.{groups[0]}.level_blocks.{groups[1]}.proj_out.{groups[-1]}""" snake_case_ = re_encoder_block_proj_out.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # rename vqvae.decoder keys elif re_decoder_block_conv_out.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_decoder_block_conv_out.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) - 2 snake_case_ = f"""decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.{groups[-1]}""" snake_case_ = re_decoder_block_conv_out.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_decoder_block_resnet.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_decoder_block_resnet.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) - 2 snake_case_ = {"""1""": 1, """3""": 2}[groups[-2]] snake_case_ = f"""decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.""" snake_case_ = f"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}""" snake_case_ = prefix + resnet_block snake_case_ = re_decoder_block_resnet.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_decoder_block_proj_in.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_decoder_block_proj_in.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = f"""decoders.{groups[0]}.level_blocks.{groups[1]}.proj_in.{groups[-1]}""" snake_case_ = re_decoder_block_proj_in.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # rename prior cond.model to upsampler.upsample_block and resnet elif re_prior_cond_conv_out.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_prior_cond_conv_out.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[1] ) * 2 + int(groups[2] ) - 2 snake_case_ = f"""conditioner_blocks.upsampler.upsample_block.{block_index}.{groups[-1]}""" snake_case_ = re_prior_cond_conv_out.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_prior_cond_resnet.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_prior_cond_resnet.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[1] ) * 2 + int(groups[2] ) - 2 snake_case_ = {"""1""": 1, """3""": 2}[groups[-2]] snake_case_ = f"""conditioner_blocks.upsampler.upsample_block.{block_index}.""" snake_case_ = f"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}""" snake_case_ = prefix + resnet_block snake_case_ = re_prior_cond_resnet.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_prior_cond_proj_in.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_prior_cond_proj_in.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = f"""conditioner_blocks.upsampler.proj_in.{groups[-1]}""" snake_case_ = re_prior_cond_proj_in.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # keep original key else: snake_case_ = original_key snake_case_ = replace_key(_SCREAMING_SNAKE_CASE ) if f"""{key_prefix}.{key}""" not in model_state_dict or key is None: print(f"""failed converting {original_key} to {key}, does not match""" ) # handle missmatched shape elif value.shape != model_state_dict[f"""{key_prefix}.{key}"""].shape: snake_case_ = model_state_dict[f"""{key_prefix}.{key}"""] print(f"""{original_key}-> {key} : \nshape {val.shape} and { value.shape}, do not match""" ) snake_case_ = original_key snake_case_ = original_key snake_case_ = value return new_dict @torch.no_grad() def _a ( _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> Optional[int]: for file in MODEL_MAPPING[model_name]: if not os.path.isfile(f"""{pytorch_dump_folder_path}/{file.split("/" )[-1]}""" ): snake_case_ = requests.get(f"""{PREFIX}{file}""" , allow_redirects=_SCREAMING_SNAKE_CASE ) os.makedirs(f"""{pytorch_dump_folder_path}/""" , exist_ok=_SCREAMING_SNAKE_CASE ) open(f"""{pytorch_dump_folder_path}/{file.split("/" )[-1]}""" , """wb""" ).write(r.content ) snake_case_ = MODEL_MAPPING[model_name.split("""/""" )[-1]] snake_case_ = JukeboxConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) snake_case_ = JukeboxModel(_SCREAMING_SNAKE_CASE ) snake_case_ = [] snake_case_ = {} for i, dict_name in enumerate(_SCREAMING_SNAKE_CASE ): snake_case_ = torch.load(f"""{pytorch_dump_folder_path}/{dict_name.split("/" )[-1]}""" )["""model"""] snake_case_ = {} for k in old_dic.keys(): if k.endswith(""".b""" ): snake_case_ = old_dic[k] elif k.endswith(""".w""" ): snake_case_ = old_dic[k] elif "level_2" not in dict_name and "cond.model." in k: snake_case_ = old_dic[k] else: snake_case_ = old_dic[k] snake_case_ = """vqvae""" if i == 0 else f"""priors.{3 - i}""" snake_case_ = fix_jukebox_keys(_SCREAMING_SNAKE_CASE , model.state_dict() , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) weight_dict.append(_SCREAMING_SNAKE_CASE ) snake_case_ = weight_dict.pop(0 ) model.vqvae.load_state_dict(_SCREAMING_SNAKE_CASE ) for i in range(len(_SCREAMING_SNAKE_CASE ) ): model.priors[i].load_state_dict(weight_dict[2 - i] ) Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) with open(f"""{pytorch_dump_folder_path}/mapping.json""" , """w""" ) as txtfile: json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) print(f"""Saving model {model_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) return weight_dict if __name__ == "__main__": __SCREAMING_SNAKE_CASE : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='jukebox-5b-lyrics', type=str, help='Name of the model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default='jukebox-5b-lyrics-converted', type=str, help='Path to the output PyTorch model directory.', ) __SCREAMING_SNAKE_CASE : str = parser.parse_args() convert_openai_checkpoint(args.model_name, args.pytorch_dump_folder_path)
719
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __SCREAMING_SNAKE_CASE : Optional[Any] = { 'configuration_megatron_bert': ['MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MegatronBertConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : Tuple = [ 'MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'MegatronBertForCausalLM', 'MegatronBertForMaskedLM', 'MegatronBertForMultipleChoice', 'MegatronBertForNextSentencePrediction', 'MegatronBertForPreTraining', 'MegatronBertForQuestionAnswering', 'MegatronBertForSequenceClassification', 'MegatronBertForTokenClassification', 'MegatronBertModel', 'MegatronBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_megatron_bert import MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MegatronBertConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_megatron_bert import ( MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, MegatronBertPreTrainedModel, ) else: import sys __SCREAMING_SNAKE_CASE : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
2
0
"""simple docstring""" from __future__ import annotations def _a ( _SCREAMING_SNAKE_CASE = 4 ) -> list[list[int]]: snake_case_ = abs(_SCREAMING_SNAKE_CASE ) or 4 return [[1 + x + y * row_size for x in range(_SCREAMING_SNAKE_CASE )] for y in range(_SCREAMING_SNAKE_CASE )] def _a ( _SCREAMING_SNAKE_CASE ) -> list[list[int]]: return reverse_row(transpose(_SCREAMING_SNAKE_CASE ) ) # OR.. transpose(reverse_column(matrix)) def _a ( _SCREAMING_SNAKE_CASE ) -> list[list[int]]: return reverse_row(reverse_column(_SCREAMING_SNAKE_CASE ) ) # OR.. reverse_column(reverse_row(matrix)) def _a ( _SCREAMING_SNAKE_CASE ) -> list[list[int]]: return reverse_column(transpose(_SCREAMING_SNAKE_CASE ) ) # OR.. transpose(reverse_row(matrix)) def _a ( _SCREAMING_SNAKE_CASE ) -> list[list[int]]: snake_case_ = [list(_SCREAMING_SNAKE_CASE ) for x in zip(*_SCREAMING_SNAKE_CASE )] return matrix def _a ( _SCREAMING_SNAKE_CASE ) -> list[list[int]]: snake_case_ = matrix[::-1] return matrix def _a ( _SCREAMING_SNAKE_CASE ) -> list[list[int]]: snake_case_ = [x[::-1] for x in matrix] return matrix def _a ( _SCREAMING_SNAKE_CASE ) -> None: for i in matrix: print(*_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : int = make_matrix() print('\norigin:\n') print_matrix(matrix) print('\nrotate 90 counterclockwise:\n') print_matrix(rotate_aa(matrix)) __SCREAMING_SNAKE_CASE : Tuple = make_matrix() print('\norigin:\n') print_matrix(matrix) print('\nrotate 180:\n') print_matrix(rotate_aaa(matrix)) __SCREAMING_SNAKE_CASE : Optional[int] = make_matrix() print('\norigin:\n') print_matrix(matrix) print('\nrotate 270 counterclockwise:\n') print_matrix(rotate_aaa(matrix))
720
"""simple docstring""" import argparse import json import os from pathlib import Path import requests import torch from transformers import JukeboxConfig, JukeboxModel from transformers.utils import logging logging.set_verbosity_info() __SCREAMING_SNAKE_CASE : str = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE : Optional[int] = 'https://openaipublic.azureedge.net/jukebox/models/' __SCREAMING_SNAKE_CASE : List[Any] = { 'jukebox-1b-lyrics': [ '5b/vqvae.pth.tar', '5b/prior_level_0.pth.tar', '5b/prior_level_1.pth.tar', '1b_lyrics/prior_level_2.pth.tar', ], 'jukebox-5b-lyrics': [ '5b/vqvae.pth.tar', '5b/prior_level_0.pth.tar', '5b/prior_level_1.pth.tar', '5b_lyrics/prior_level_2.pth.tar', ], } def _a ( _SCREAMING_SNAKE_CASE ) -> int: if key.endswith(""".model.1.bias""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.1.bias""" , """.conv1d_1.bias""" ) elif key.endswith(""".model.1.weight""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.1.weight""" , """.conv1d_1.weight""" ) elif key.endswith(""".model.3.bias""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.3.bias""" , """.conv1d_2.bias""" ) elif key.endswith(""".model.3.weight""" ) and len(key.split(""".""" ) ) > 10: snake_case_ = key.replace(""".model.3.weight""" , """.conv1d_2.weight""" ) if "conditioner_blocks.0." in key: snake_case_ = key.replace("""conditioner_blocks.0""" , """conditioner_blocks""" ) if "prime_prior" in key: snake_case_ = key.replace("""prime_prior""" , """encoder""" ) if ".emb." in key and "total" not in key and "absolute" not in key and "relative" not in key: snake_case_ = key.replace(""".emb.""" , """.""" ) if key.endswith("""k""" ): # replace vqvae.X.k with vqvae.X.codebook return key.replace(""".k""" , """.codebook""" ) if "y_emb." in key: return key.replace("""y_emb.""" , """metadata_embedding.""" ) if "x_emb.emb." in key: snake_case_ = key.replace("""0.x_emb.emb""" , """embed_tokens""" ) if "prime_state_ln" in key: return key.replace("""prime_state_ln""" , """encoder.final_layer_norm""" ) if ".ln" in key: return key.replace(""".ln""" , """.layer_norm""" ) if "_ln" in key: return key.replace("""_ln""" , """_layer_norm""" ) if "prime_state_proj" in key: return key.replace("""prime_state_proj""" , """encoder.proj_in""" ) if "prime_x_out" in key: return key.replace("""prime_x_out""" , """encoder.lm_head""" ) if "prior.x_out" in key: return key.replace("""x_out""" , """fc_proj_out""" ) if "x_emb" in key: return key.replace("""x_emb""" , """embed_tokens""" ) return key def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: snake_case_ = {} import re snake_case_ = re.compile(r"""encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)""" ) snake_case_ = re.compile( r"""encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""encoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)""" ) snake_case_ = re.compile( r"""decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""decoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""conditioner_blocks.(\d*).cond.model.(\d*).(\d).(bias|weight)""" ) snake_case_ = re.compile( r"""conditioner_blocks.(\d*).cond.model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)""" ) snake_case_ = re.compile(r"""conditioner_blocks.(\d*).cond.model.(\d*).(bias|weight)""" ) for original_key, value in state_dict.items(): # rename vqvae.encoder keys if re_encoder_block_conv_in.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_encoder_block_conv_in.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) snake_case_ = f"""encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.{groups[-1]}""" snake_case_ = re_encoder_block_conv_in.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_encoder_block_resnet.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_encoder_block_resnet.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) snake_case_ = {"""1""": 1, """3""": 2}[groups[-2]] snake_case_ = f"""encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.""" snake_case_ = f"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}""" snake_case_ = prefix + resnet_block snake_case_ = re_encoder_block_resnet.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_encoder_block_proj_out.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_encoder_block_proj_out.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = f"""encoders.{groups[0]}.level_blocks.{groups[1]}.proj_out.{groups[-1]}""" snake_case_ = re_encoder_block_proj_out.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # rename vqvae.decoder keys elif re_decoder_block_conv_out.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_decoder_block_conv_out.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) - 2 snake_case_ = f"""decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.{groups[-1]}""" snake_case_ = re_decoder_block_conv_out.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_decoder_block_resnet.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_decoder_block_resnet.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[2] ) * 2 + int(groups[3] ) - 2 snake_case_ = {"""1""": 1, """3""": 2}[groups[-2]] snake_case_ = f"""decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.""" snake_case_ = f"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}""" snake_case_ = prefix + resnet_block snake_case_ = re_decoder_block_resnet.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_decoder_block_proj_in.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_decoder_block_proj_in.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = f"""decoders.{groups[0]}.level_blocks.{groups[1]}.proj_in.{groups[-1]}""" snake_case_ = re_decoder_block_proj_in.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # rename prior cond.model to upsampler.upsample_block and resnet elif re_prior_cond_conv_out.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_prior_cond_conv_out.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[1] ) * 2 + int(groups[2] ) - 2 snake_case_ = f"""conditioner_blocks.upsampler.upsample_block.{block_index}.{groups[-1]}""" snake_case_ = re_prior_cond_conv_out.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_prior_cond_resnet.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_prior_cond_resnet.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = int(groups[1] ) * 2 + int(groups[2] ) - 2 snake_case_ = {"""1""": 1, """3""": 2}[groups[-2]] snake_case_ = f"""conditioner_blocks.upsampler.upsample_block.{block_index}.""" snake_case_ = f"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}""" snake_case_ = prefix + resnet_block snake_case_ = re_prior_cond_resnet.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif re_prior_cond_proj_in.fullmatch(_SCREAMING_SNAKE_CASE ): snake_case_ = re_prior_cond_proj_in.match(_SCREAMING_SNAKE_CASE ) snake_case_ = regex_match.groups() snake_case_ = f"""conditioner_blocks.upsampler.proj_in.{groups[-1]}""" snake_case_ = re_prior_cond_proj_in.sub(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # keep original key else: snake_case_ = original_key snake_case_ = replace_key(_SCREAMING_SNAKE_CASE ) if f"""{key_prefix}.{key}""" not in model_state_dict or key is None: print(f"""failed converting {original_key} to {key}, does not match""" ) # handle missmatched shape elif value.shape != model_state_dict[f"""{key_prefix}.{key}"""].shape: snake_case_ = model_state_dict[f"""{key_prefix}.{key}"""] print(f"""{original_key}-> {key} : \nshape {val.shape} and { value.shape}, do not match""" ) snake_case_ = original_key snake_case_ = original_key snake_case_ = value return new_dict @torch.no_grad() def _a ( _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> Optional[int]: for file in MODEL_MAPPING[model_name]: if not os.path.isfile(f"""{pytorch_dump_folder_path}/{file.split("/" )[-1]}""" ): snake_case_ = requests.get(f"""{PREFIX}{file}""" , allow_redirects=_SCREAMING_SNAKE_CASE ) os.makedirs(f"""{pytorch_dump_folder_path}/""" , exist_ok=_SCREAMING_SNAKE_CASE ) open(f"""{pytorch_dump_folder_path}/{file.split("/" )[-1]}""" , """wb""" ).write(r.content ) snake_case_ = MODEL_MAPPING[model_name.split("""/""" )[-1]] snake_case_ = JukeboxConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) snake_case_ = JukeboxModel(_SCREAMING_SNAKE_CASE ) snake_case_ = [] snake_case_ = {} for i, dict_name in enumerate(_SCREAMING_SNAKE_CASE ): snake_case_ = torch.load(f"""{pytorch_dump_folder_path}/{dict_name.split("/" )[-1]}""" )["""model"""] snake_case_ = {} for k in old_dic.keys(): if k.endswith(""".b""" ): snake_case_ = old_dic[k] elif k.endswith(""".w""" ): snake_case_ = old_dic[k] elif "level_2" not in dict_name and "cond.model." in k: snake_case_ = old_dic[k] else: snake_case_ = old_dic[k] snake_case_ = """vqvae""" if i == 0 else f"""priors.{3 - i}""" snake_case_ = fix_jukebox_keys(_SCREAMING_SNAKE_CASE , model.state_dict() , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) weight_dict.append(_SCREAMING_SNAKE_CASE ) snake_case_ = weight_dict.pop(0 ) model.vqvae.load_state_dict(_SCREAMING_SNAKE_CASE ) for i in range(len(_SCREAMING_SNAKE_CASE ) ): model.priors[i].load_state_dict(weight_dict[2 - i] ) Path(_SCREAMING_SNAKE_CASE ).mkdir(exist_ok=_SCREAMING_SNAKE_CASE ) with open(f"""{pytorch_dump_folder_path}/mapping.json""" , """w""" ) as txtfile: json.dump(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) print(f"""Saving model {model_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) return weight_dict if __name__ == "__main__": __SCREAMING_SNAKE_CASE : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='jukebox-5b-lyrics', type=str, help='Name of the model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default='jukebox-5b-lyrics-converted', type=str, help='Path to the output PyTorch model directory.', ) __SCREAMING_SNAKE_CASE : str = parser.parse_args() convert_openai_checkpoint(args.model_name, args.pytorch_dump_folder_path)
2
0
"""simple docstring""" import argparse 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 ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing the experiment tracking capability, # and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To help focus on the differences in the code, building `DataLoaders` # was refactored into its own function. # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## __SCREAMING_SNAKE_CASE : Any = 16 __SCREAMING_SNAKE_CASE : List[str] = 32 def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 16 ) -> Tuple: snake_case_ = AutoTokenizer.from_pretrained("""bert-base-cased""" ) snake_case_ = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(_SCREAMING_SNAKE_CASE ): # max_length=None => use the model max length (it's actually the default) snake_case_ = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=_SCREAMING_SNAKE_CASE , max_length=_SCREAMING_SNAKE_CASE ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): snake_case_ = datasets.map( _SCREAMING_SNAKE_CASE , batched=_SCREAMING_SNAKE_CASE , remove_columns=["""idx""", """sentence1""", """sentence2"""] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library snake_case_ = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(_SCREAMING_SNAKE_CASE ): # On TPU it's best to pad everything to the same length or training will be very slow. snake_case_ = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": snake_case_ = 16 elif accelerator.mixed_precision != "no": snake_case_ = 8 else: snake_case_ = None return tokenizer.pad( _SCREAMING_SNAKE_CASE , padding="""longest""" , max_length=_SCREAMING_SNAKE_CASE , pad_to_multiple_of=_SCREAMING_SNAKE_CASE , return_tensors="""pt""" , ) # Instantiate dataloaders. snake_case_ = DataLoader( tokenized_datasets["""train"""] , shuffle=_SCREAMING_SNAKE_CASE , collate_fn=_SCREAMING_SNAKE_CASE , batch_size=_SCREAMING_SNAKE_CASE ) snake_case_ = DataLoader( tokenized_datasets["""validation"""] , shuffle=_SCREAMING_SNAKE_CASE , collate_fn=_SCREAMING_SNAKE_CASE , batch_size=_SCREAMING_SNAKE_CASE ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('TESTING_MOCKED_DATALOADERS', None) == "1": from accelerate.test_utils.training import mocked_dataloaders __SCREAMING_SNAKE_CASE : Tuple = mocked_dataloaders # noqa: F811 def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""" , _SCREAMING_SNAKE_CASE ) == "1": snake_case_ = 2 # Initialize Accelerator # New Code # # We pass in "all" to `log_with` to grab all available trackers in the environment # Note: If using a custom `Tracker` class, should be passed in here such as: # >>> log_with = ["all", MyCustomTrackerClassInstance()] if args.with_tracking: snake_case_ = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , log_with="""all""" , project_dir=args.project_dir ) else: snake_case_ = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs snake_case_ = config["""lr"""] snake_case_ = int(config["""num_epochs"""] ) snake_case_ = int(config["""seed"""] ) snake_case_ = int(config["""batch_size"""] ) set_seed(_SCREAMING_SNAKE_CASE ) snake_case_ , snake_case_ = get_dataloaders(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = evaluate.load("""glue""" , """mrpc""" ) # If the batch size is too big we use gradient accumulation snake_case_ = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: snake_case_ = batch_size // MAX_GPU_BATCH_SIZE snake_case_ = MAX_GPU_BATCH_SIZE # Instantiate the model (we build the model here so that the seed also control new weights initialization) snake_case_ = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" , return_dict=_SCREAMING_SNAKE_CASE ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). snake_case_ = model.to(accelerator.device ) # Instantiate optimizer snake_case_ = AdamW(params=model.parameters() , lr=_SCREAMING_SNAKE_CASE ) # Instantiate scheduler snake_case_ = get_linear_schedule_with_warmup( optimizer=_SCREAMING_SNAKE_CASE , num_warmup_steps=100 , num_training_steps=(len(_SCREAMING_SNAKE_CASE ) * num_epochs) // gradient_accumulation_steps , ) # 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_ = accelerator.prepare( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # New Code # # We need to initialize the trackers we use. Overall configurations can also be stored if args.with_tracking: snake_case_ = os.path.split(_SCREAMING_SNAKE_CASE )[-1].split(""".""" )[0] accelerator.init_trackers(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Now we train the model for epoch in range(_SCREAMING_SNAKE_CASE ): model.train() # New Code # # For our tracking example, we will log the total loss of each epoch if args.with_tracking: snake_case_ = 0 for step, batch in enumerate(_SCREAMING_SNAKE_CASE ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) snake_case_ = model(**_SCREAMING_SNAKE_CASE ) snake_case_ = outputs.loss # New Code # if args.with_tracking: total_loss += loss.detach().float() snake_case_ = loss / gradient_accumulation_steps accelerator.backward(_SCREAMING_SNAKE_CASE ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(_SCREAMING_SNAKE_CASE ): # We could avoid this line since we set the accelerator with `device_placement=True` (the default). batch.to(accelerator.device ) with torch.no_grad(): snake_case_ = model(**_SCREAMING_SNAKE_CASE ) snake_case_ = outputs.logits.argmax(dim=-1 ) snake_case_ , snake_case_ = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=_SCREAMING_SNAKE_CASE , references=_SCREAMING_SNAKE_CASE , ) snake_case_ = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"""epoch {epoch}:""" , _SCREAMING_SNAKE_CASE ) # New Code # # To actually log, we call `Accelerator.log` # The values passed can be of `str`, `int`, `float` or `dict` of `str` to `float`/`int` if args.with_tracking: accelerator.log( { """accuracy""": eval_metric["""accuracy"""], """f1""": eval_metric["""f1"""], """train_loss""": total_loss.item() / len(_SCREAMING_SNAKE_CASE ), """epoch""": epoch, } , step=_SCREAMING_SNAKE_CASE , ) # New Code # # When a run is finished, you should call `accelerator.end_training()` # to close all of the open trackers if args.with_tracking: accelerator.end_training() def _a ( ) -> Any: snake_case_ = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" , type=_SCREAMING_SNAKE_CASE , default=_SCREAMING_SNAKE_CASE , choices=["""no""", """fp16""", """bf16""", """fp8"""] , help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" , ) parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" ) parser.add_argument( """--with_tracking""" , action="""store_true""" , help="""Whether to load in all available experiment trackers from the environment and use them for logging.""" , ) parser.add_argument( """--project_dir""" , type=_SCREAMING_SNAKE_CASE , default="""logs""" , help="""Location on where to store experiment tracking logs` and relevent project information""" , ) snake_case_ = parser.parse_args() snake_case_ = {"""lr""": 2E-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16} training_function(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
721
"""simple docstring""" # XXX: we want transformers master here - in the absense of conftest manipulating sys.path: # hack it in for now: import sys from pathlib import Path __SCREAMING_SNAKE_CASE : Union[str, Any] = Path(__file__).resolve().parents[3] / 'src' sys.path.insert(1, str(git_repo_path)) import dataclasses # noqa import io # noqa import itertools # noqa import json # noqa import os # noqa import unittest # noqa from copy import deepcopy # noqa from parameterized import parameterized # noqa from transformers import TrainingArguments, is_torch_available # noqa from transformers.deepspeed import is_deepspeed_available # noqa from transformers.file_utils import WEIGHTS_NAME # noqa from transformers.testing_utils import ( # noqa CaptureLogger, ExtendSysPath, TestCasePlus, execute_subprocess_async, get_gpu_count, mockenv_context, require_deepspeed, require_torch_gpu, require_torch_multi_gpu, slow, ) from transformers.trainer_utils import set_seed # noqa set_seed(42) __SCREAMING_SNAKE_CASE : Dict = {'base': 'patrickvonplaten/wav2vec2_tiny_random', 'robust': 'patrickvonplaten/wav2vec2_tiny_random_robust'} __SCREAMING_SNAKE_CASE : Dict = 'zero2' __SCREAMING_SNAKE_CASE : List[Any] = 'zero3' __SCREAMING_SNAKE_CASE : int = [ZEROa, ZEROa] def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: # customize the test name generator function as we want both params to appear in the sub-test # name, as by default it shows only the first param snake_case_ = parameterized.to_safe_name("""_""".join(str(_SCREAMING_SNAKE_CASE ) for x in param.args ) ) return f"""{func.__name__}_{param_based_name}""" # Cartesian-product of zero stages with models to test __SCREAMING_SNAKE_CASE : Dict = list(itertools.product(stages, models.keys())) @slow @require_deepspeed @require_torch_gpu class __A (snake_case__): '''simple docstring''' @parameterized.expand(UpperCAmelCase_ , name_func=UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Union[str, Any] ) ->Any: """simple docstring""" self.run_and_check( stage=UpperCAmelCase_ , model=UpperCAmelCase_ , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) @require_torch_multi_gpu @parameterized.expand(UpperCAmelCase_ , name_func=UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[Any] ) ->Optional[Any]: """simple docstring""" self.run_and_check( stage=UpperCAmelCase_ , model=UpperCAmelCase_ , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) @parameterized.expand(UpperCAmelCase_ , name_func=UpperCAmelCase_ ) def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[int] ) ->List[str]: """simple docstring""" self.run_and_check( stage=UpperCAmelCase_ , model=UpperCAmelCase_ , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) @require_torch_multi_gpu @parameterized.expand(UpperCAmelCase_ , name_func=UpperCAmelCase_ ) def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : str , UpperCAmelCase_ : List[Any] ) ->Optional[int]: """simple docstring""" self.run_and_check( stage=UpperCAmelCase_ , model=UpperCAmelCase_ , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : Union[str, Any] ) ->Optional[int]: """simple docstring""" pass def lowerCAmelCase ( self : Any , UpperCAmelCase_ : str , UpperCAmelCase_ : str , UpperCAmelCase_ : int = 10 , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : bool = True , ) ->List[str]: """simple docstring""" snake_case_ = models[model] snake_case_ = self.run_trainer( stage=UpperCAmelCase_ , model_name=UpperCAmelCase_ , eval_steps=UpperCAmelCase_ , num_train_epochs=1 , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) self.do_checks(UpperCAmelCase_ ) return output_dir def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : str , UpperCAmelCase_ : int = 10 , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : bool = True , ) ->List[str]: """simple docstring""" snake_case_ = self.get_auto_remove_tmp_dir("""./xxx""" , after=UpperCAmelCase_ ) snake_case_ = F""" --model_name_or_path {model_name} --dataset_name hf-internal-testing/librispeech_asr_dummy --dataset_config_name clean --train_split_name validation --validation_split_name validation --output_dir {output_dir} --num_train_epochs {str(UpperCAmelCase_ )} --per_device_train_batch_size 2 --per_device_eval_batch_size 2 --evaluation_strategy steps --learning_rate 5e-4 --warmup_steps 8 --orthography timit --preprocessing_num_workers 1 --group_by_length --freeze_feature_extractor --report_to none --save_steps 0 --eval_steps {eval_steps} --report_to none """.split() if fpaa: args.extend(["""--fp16"""] ) # currently ds_config_wav2vec2_zero.json requires "zero_optimization.find_unused_parameters": true, # hence the separate config files snake_case_ = F"""--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json""".split() snake_case_ = [F"""{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py"""] snake_case_ = self.get_launcher(UpperCAmelCase_ ) snake_case_ = launcher + script + args + ds_args # keep for quick debug # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die execute_subprocess_async(UpperCAmelCase_ , env=self.get_env() ) return output_dir def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : Any=False ) ->Tuple: """simple docstring""" snake_case_ = min(2 , get_gpu_count() ) if distributed else 1 return F"""deepspeed --num_nodes 1 --num_gpus {num_gpus}""".split()
2
0
"""simple docstring""" import unittest from transformers import is_vision_available from transformers.pipelines import pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class __A : '''simple docstring''' @staticmethod def lowerCAmelCase ( *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : List[str] ) ->Any: """simple docstring""" pass @is_pipeline_test @require_vision class __A (unittest.TestCase): '''simple docstring''' @require_torch def lowerCAmelCase ( self : Dict ) ->Optional[Any]: """simple docstring""" snake_case_ = pipeline( model="""hf-internal-testing/tiny-random-clip-zero-shot-image-classification""" , ) snake_case_ = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) snake_case_ = image_classifier(UpperCAmelCase_ , candidate_labels=["""a""", """b""", """c"""] ) # The floating scores are so close, we enter floating error approximation and the order is not guaranteed across # python and torch versions. self.assertIn( nested_simplify(UpperCAmelCase_ ) , [ [{"""score""": 0.333, """label""": """a"""}, {"""score""": 0.333, """label""": """b"""}, {"""score""": 0.333, """label""": """c"""}], [{"""score""": 0.333, """label""": """a"""}, {"""score""": 0.333, """label""": """c"""}, {"""score""": 0.333, """label""": """b"""}], ] , ) snake_case_ = image_classifier([image] * 5 , candidate_labels=["""A""", """B""", """C"""] , batch_size=2 ) self.assertEqual( nested_simplify(UpperCAmelCase_ ) , [ [ {"""score""": 0.333, """label""": ANY(UpperCAmelCase_ )}, {"""score""": 0.333, """label""": ANY(UpperCAmelCase_ )}, {"""score""": 0.333, """label""": ANY(UpperCAmelCase_ )}, ], [ {"""score""": 0.333, """label""": ANY(UpperCAmelCase_ )}, {"""score""": 0.333, """label""": ANY(UpperCAmelCase_ )}, {"""score""": 0.333, """label""": ANY(UpperCAmelCase_ )}, ], [ {"""score""": 0.333, """label""": ANY(UpperCAmelCase_ )}, {"""score""": 0.333, """label""": ANY(UpperCAmelCase_ )}, {"""score""": 0.333, """label""": ANY(UpperCAmelCase_ )}, ], [ {"""score""": 0.333, """label""": ANY(UpperCAmelCase_ )}, {"""score""": 0.333, """label""": ANY(UpperCAmelCase_ )}, {"""score""": 0.333, """label""": ANY(UpperCAmelCase_ )}, ], [ {"""score""": 0.333, """label""": ANY(UpperCAmelCase_ )}, {"""score""": 0.333, """label""": ANY(UpperCAmelCase_ )}, {"""score""": 0.333, """label""": ANY(UpperCAmelCase_ )}, ], ] , ) @require_tf def lowerCAmelCase ( self : Union[str, Any] ) ->Tuple: """simple docstring""" snake_case_ = pipeline( model="""hf-internal-testing/tiny-random-clip-zero-shot-image-classification""" , framework="""tf""" ) snake_case_ = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) snake_case_ = image_classifier(UpperCAmelCase_ , candidate_labels=["""a""", """b""", """c"""] ) self.assertEqual( nested_simplify(UpperCAmelCase_ ) , [{"""score""": 0.333, """label""": """a"""}, {"""score""": 0.333, """label""": """b"""}, {"""score""": 0.333, """label""": """c"""}] , ) snake_case_ = image_classifier([image] * 5 , candidate_labels=["""A""", """B""", """C"""] , batch_size=2 ) self.assertEqual( nested_simplify(UpperCAmelCase_ ) , [ [ {"""score""": 0.333, """label""": ANY(UpperCAmelCase_ )}, {"""score""": 0.333, """label""": ANY(UpperCAmelCase_ )}, {"""score""": 0.333, """label""": ANY(UpperCAmelCase_ )}, ], [ {"""score""": 0.333, """label""": ANY(UpperCAmelCase_ )}, {"""score""": 0.333, """label""": ANY(UpperCAmelCase_ )}, {"""score""": 0.333, """label""": ANY(UpperCAmelCase_ )}, ], [ {"""score""": 0.333, """label""": ANY(UpperCAmelCase_ )}, {"""score""": 0.333, """label""": ANY(UpperCAmelCase_ )}, {"""score""": 0.333, """label""": ANY(UpperCAmelCase_ )}, ], [ {"""score""": 0.333, """label""": ANY(UpperCAmelCase_ )}, {"""score""": 0.333, """label""": ANY(UpperCAmelCase_ )}, {"""score""": 0.333, """label""": ANY(UpperCAmelCase_ )}, ], [ {"""score""": 0.333, """label""": ANY(UpperCAmelCase_ )}, {"""score""": 0.333, """label""": ANY(UpperCAmelCase_ )}, {"""score""": 0.333, """label""": ANY(UpperCAmelCase_ )}, ], ] , ) @slow @require_torch def lowerCAmelCase ( self : Any ) ->int: """simple docstring""" snake_case_ = pipeline( task="""zero-shot-image-classification""" , model="""openai/clip-vit-base-patch32""" , ) # This is an image of 2 cats with remotes and no planes snake_case_ = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) snake_case_ = image_classifier(UpperCAmelCase_ , candidate_labels=["""cat""", """plane""", """remote"""] ) self.assertEqual( nested_simplify(UpperCAmelCase_ ) , [ {"""score""": 0.511, """label""": """remote"""}, {"""score""": 0.485, """label""": """cat"""}, {"""score""": 0.004, """label""": """plane"""}, ] , ) snake_case_ = image_classifier([image] * 5 , candidate_labels=["""cat""", """plane""", """remote"""] , batch_size=2 ) self.assertEqual( nested_simplify(UpperCAmelCase_ ) , [ [ {"""score""": 0.511, """label""": """remote"""}, {"""score""": 0.485, """label""": """cat"""}, {"""score""": 0.004, """label""": """plane"""}, ], ] * 5 , ) @slow @require_tf def lowerCAmelCase ( self : int ) ->Any: """simple docstring""" snake_case_ = pipeline( task="""zero-shot-image-classification""" , model="""openai/clip-vit-base-patch32""" , framework="""tf""" ) # This is an image of 2 cats with remotes and no planes snake_case_ = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) snake_case_ = image_classifier(UpperCAmelCase_ , candidate_labels=["""cat""", """plane""", """remote"""] ) self.assertEqual( nested_simplify(UpperCAmelCase_ ) , [ {"""score""": 0.511, """label""": """remote"""}, {"""score""": 0.485, """label""": """cat"""}, {"""score""": 0.004, """label""": """plane"""}, ] , ) snake_case_ = image_classifier([image] * 5 , candidate_labels=["""cat""", """plane""", """remote"""] , batch_size=2 ) self.assertEqual( nested_simplify(UpperCAmelCase_ ) , [ [ {"""score""": 0.511, """label""": """remote"""}, {"""score""": 0.485, """label""": """cat"""}, {"""score""": 0.004, """label""": """plane"""}, ], ] * 5 , )
700
"""simple docstring""" import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, Features, Value from .base import TaskTemplate @dataclass(frozen=snake_case__) class __A (snake_case__): '''simple docstring''' __lowercase: str = field(default="""automatic-speech-recognition""" , metadata={"""include_in_asdict_even_if_is_default""": True}) __lowercase: ClassVar[Features] = Features({"""audio""": Audio()}) __lowercase: ClassVar[Features] = Features({"""transcription""": Value("""string""")}) __lowercase: str = "audio" __lowercase: str = "transcription" def lowerCAmelCase ( self : List[Any] , UpperCAmelCase_ : Any ) ->int: """simple docstring""" if self.audio_column not in features: raise ValueError(F"""Column {self.audio_column} is not present in features.""" ) if not isinstance(features[self.audio_column] , UpperCAmelCase_ ): raise ValueError(F"""Column {self.audio_column} is not an Audio type.""" ) snake_case_ = copy.deepcopy(self ) snake_case_ = self.input_schema.copy() snake_case_ = features[self.audio_column] snake_case_ = input_schema return task_template @property def lowerCAmelCase ( self : List[str] ) ->Dict[str, str]: """simple docstring""" return {self.audio_column: "audio", self.transcription_column: "transcription"}
2
0
"""simple docstring""" import unittest from transformers import JukeboxTokenizer from transformers.testing_utils import require_torch class __A (unittest.TestCase): '''simple docstring''' __lowercase: Any = JukeboxTokenizer __lowercase: Union[str, Any] = { """artist""": """Zac Brown Band""", """genres""": """Country""", """lyrics""": """I met a traveller from an antique land, Who said \"Two vast and trunkless legs of stone Stand in the desert. . . . Near them, on the sand, Half sunk a shattered visage lies, whose frown, And wrinkled lip, and sneer of cold command, Tell that its sculptor well those passions read Which yet survive, stamped on these lifeless things, The hand that mocked them, and the heart that fed; And on the pedestal, these words appear: My name is Ozymandias, King of Kings; Look on my Works, ye Mighty, and despair! Nothing beside remains. Round the decay Of that colossal Wreck, boundless and bare The lone and level sands stretch far away """, } @require_torch def lowerCAmelCase ( self : List[Any] ) ->int: """simple docstring""" import torch snake_case_ = JukeboxTokenizer.from_pretrained("""openai/jukebox-1b-lyrics""" ) snake_case_ = tokenizer(**self.metas )["""input_ids"""] # fmt: off snake_case_ = [ torch.tensor([[ 0, 0, 0, 7_169, 507, 9, 76, 39, 31, 46, 76, 27, 76, 46, 44, 27, 48, 31, 38, 38, 31, 44, 76, 32, 44, 41, 39, 76, 27, 40, 76, 27, 40, 46, 35, 43, 47, 31, 76, 38, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 41, 76, 45, 27, 35, 30, 76, 71, 20, 49, 41, 76, 48, 27, 45, 46, 76, 27, 40, 30, 76, 46, 44, 47, 40, 37, 38, 31, 45, 45, 76, 38, 31, 33, 45, 76, 41, 32, 76, 45, 46, 41, 40, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 19, 46, 27, 40, 30, 76, 35, 40, 76, 46, 34, 31, 76, 30, 31, 45, 31, 44, 46, 63, 76, 63, 76, 63, 76, 63, 76, 14, 31, 27, 44, 76, 46, 34, 31, 39, 64, 76, 41, 40, 76, 46, 34, 31, 76, 45, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 8, 27, 38, 32, 76, 45, 47, 40, 37, 76, 27, 76, 45, 34, 27, 46, 46, 31, 44, 31, 30, 76, 48, 35, 45, 27, 33, 31, 76, 38, 35, 31, 45, 64, 76, 49, 34, 41, 45, 31, 76, 32, 44, 41, 49, 40, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 49, 44, 35, 40, 37, 38, 31, 30, 76, 38, 35, 42, 64, 76, 27, 40, 30, 76, 45, 40, 31, 31, 44, 76, 41, 32, 76, 29, 41, 38, 30, 76, 29, 41, 39, 39, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 31, 38, 38, 76, 46, 34, 27, 46, 76, 35, 46, 45, 76, 45, 29, 47, 38, 42, 46, 41, 44, 76, 49, 31, 38, 38, 76, 46, 34, 41, 45, 31, 76, 42, 27, 45, 45, 35, 41, 40, 45, 76, 44, 31, 27, 30, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 35, 29, 34, 76, 51, 31, 46, 76, 45, 47, 44, 48, 35, 48, 31, 64, 76, 45, 46, 27, 39, 42, 31, 30, 76, 41, 40, 76, 46, 34, 31, 45, 31, 76, 38, 35, 32, 31, 38, 31, 45, 45, 76, 46, 34, 35, 40, 33, 45, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 34, 27, 40, 30, 76, 46, 34, 27, 46, 76, 39, 41, 29, 37, 31, 30, 76, 46, 34, 31, 39, 64, 76, 27, 40, 30, 76, 46, 34, 31, 76, 34, 31, 27, 44, 46, 76, 46, 34, 27, 46, 76, 32, 31, 30, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 41, 40, 76, 46, 34, 31, 76, 42, 31, 30, 31, 45, 46, 27, 38, 64, 76, 46, 34, 31, 45, 31, 76, 49, 41, 44, 30, 45, 76, 27, 42, 42, 31, 27, 44, 65, 78, 76, 76, 76, 76, 76, 76, 76, 76, 13, 51, 76, 40, 27, 39, 31, 76, 35, 45, 76, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 76, 11, 35, 40, 33, 76, 41, 32, 76, 11, 35, 40, 33, 45, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 12, 41, 41, 37, 76, 41, 40, 76, 39, 51, 76, 23, 41, 44, 37, 45, 64, 76, 51, 31, 76, 13, 35, 33, 34, 46, 51, 64, 76, 27, 40, 30, 76, 30, 31, 45, 42, 27, 35, 44, 67, 78, 76, 76, 76, 76, 76, 76, 76, 76, 14, 41, 46, 34, 35, 40, 33, 76, 28, 31, 45, 35, 30, 31, 76, 44, 31, 39, 27, 35, 40, 45, 63, 76, 18, 41, 47, 40, 30, 76, 46, 34, 31, 76, 30, 31, 29, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76, 15, 32, 76, 46, 34, 27, 46, 76, 29, 41, 38, 41, 45, 45, 27, 38, 76, 23, 44, 31, 29, 37, 64, 76, 28, 41, 47, 40, 30, 38, 31, 45, 45, 76, 27, 40, 30, 76, 28, 27, 44, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 38, 41, 40, 31, 76, 27, 40, 30, 76, 38, 31, 48, 31, 38, 76, 45, 27, 40, 30, 45, 76, 45, 46, 44, 31, 46, 29, 34, 76, 32, 27, 44, 76, 27, 49, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76]] ), torch.tensor([[0, 0, 0, 1_069, 11]] ), torch.tensor([[0, 0, 0, 1_069, 11]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) ) @require_torch def lowerCAmelCase ( self : int ) ->Any: """simple docstring""" import torch snake_case_ = JukeboxTokenizer.from_pretrained("""openai/jukebox-5b-lyrics""" ) snake_case_ = tokenizer(**self.metas )["""input_ids"""] # fmt: off snake_case_ = [ torch.tensor([[ 0, 0, 0, 1_069, 11, -1, -1, -1, -1, 9, 77, 39, 31, 46, 77, 27, 77, 46, 44, 27, 48, 31, 38, 38, 31, 44, 77, 32, 44, 41, 39, 77, 27, 40, 77, 27, 40, 46, 35, 43, 47, 31, 77, 38, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 41, 77, 45, 27, 35, 30, 77, 72, 20, 49, 41, 77, 48, 27, 45, 46, 77, 27, 40, 30, 77, 46, 44, 47, 40, 37, 38, 31, 45, 45, 77, 38, 31, 33, 45, 77, 41, 32, 77, 45, 46, 41, 40, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 19, 46, 27, 40, 30, 77, 35, 40, 77, 46, 34, 31, 77, 30, 31, 45, 31, 44, 46, 63, 77, 63, 77, 63, 77, 63, 77, 14, 31, 27, 44, 77, 46, 34, 31, 39, 64, 77, 41, 40, 77, 46, 34, 31, 77, 45, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 8, 27, 38, 32, 77, 45, 47, 40, 37, 77, 27, 77, 45, 34, 27, 46, 46, 31, 44, 31, 30, 77, 48, 35, 45, 27, 33, 31, 77, 38, 35, 31, 45, 64, 77, 49, 34, 41, 45, 31, 77, 32, 44, 41, 49, 40, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 49, 44, 35, 40, 37, 38, 31, 30, 77, 38, 35, 42, 64, 77, 27, 40, 30, 77, 45, 40, 31, 31, 44, 77, 41, 32, 77, 29, 41, 38, 30, 77, 29, 41, 39, 39, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 31, 38, 38, 77, 46, 34, 27, 46, 77, 35, 46, 45, 77, 45, 29, 47, 38, 42, 46, 41, 44, 77, 49, 31, 38, 38, 77, 46, 34, 41, 45, 31, 77, 42, 27, 45, 45, 35, 41, 40, 45, 77, 44, 31, 27, 30, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 35, 29, 34, 77, 51, 31, 46, 77, 45, 47, 44, 48, 35, 48, 31, 64, 77, 45, 46, 27, 39, 42, 31, 30, 77, 41, 40, 77, 46, 34, 31, 45, 31, 77, 38, 35, 32, 31, 38, 31, 45, 45, 77, 46, 34, 35, 40, 33, 45, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 34, 27, 40, 30, 77, 46, 34, 27, 46, 77, 39, 41, 29, 37, 31, 30, 77, 46, 34, 31, 39, 64, 77, 27, 40, 30, 77, 46, 34, 31, 77, 34, 31, 27, 44, 46, 77, 46, 34, 27, 46, 77, 32, 31, 30, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 41, 40, 77, 46, 34, 31, 77, 42, 31, 30, 31, 45, 46, 27, 38, 64, 77, 46, 34, 31, 45, 31, 77, 49, 41, 44, 30, 45, 77, 27, 42, 42, 31, 27, 44, 65, 79, 77, 77, 77, 77, 77, 77, 77, 77, 13, 51, 77, 40, 27, 39, 31, 77, 35, 45, 77, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 77, 11, 35, 40, 33, 77, 41, 32, 77, 11, 35, 40, 33, 45, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 12, 41, 41, 37, 77, 41, 40, 77, 39, 51, 77, 23, 41, 44, 37, 45, 64, 77, 51, 31, 77, 13, 35, 33, 34, 46, 51, 64, 77, 27, 40, 30, 77, 30, 31, 45, 42, 27, 35, 44, 67, 79, 77, 77, 77, 77, 77, 77, 77, 77, 14, 41, 46, 34, 35, 40, 33, 77, 28, 31, 45, 35, 30, 31, 77, 44, 31, 39, 27, 35, 40, 45, 63, 77, 18, 41, 47, 40, 30, 77, 46, 34, 31, 77, 30, 31, 29, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77, 15, 32, 77, 46, 34, 27, 46, 77, 29, 41, 38, 41, 45, 45, 27, 38, 77, 23, 44, 31, 29, 37, 64, 77, 28, 41, 47, 40, 30, 38, 31, 45, 45, 77, 27, 40, 30, 77, 28, 27, 44, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 38, 41, 40, 31, 77, 27, 40, 30, 77, 38, 31, 48, 31, 38, 77, 45, 27, 40, 30, 45, 77, 45, 46, 44, 31, 46, 29, 34, 77, 32, 27, 44, 77, 27, 49, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77]] ), torch.tensor([[0, 0, 0, 1_069, 11, -1, -1, -1, -1]] ), torch.tensor([[0, 0, 0, 1_069, 11, -1, -1, -1, -1]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) )
701
"""simple docstring""" from functools import reduce __SCREAMING_SNAKE_CASE : Tuple = ( '73167176531330624919225119674426574742355349194934' '96983520312774506326239578318016984801869478851843' '85861560789112949495459501737958331952853208805511' '12540698747158523863050715693290963295227443043557' '66896648950445244523161731856403098711121722383113' '62229893423380308135336276614282806444486645238749' '30358907296290491560440772390713810515859307960866' '70172427121883998797908792274921901699720888093776' '65727333001053367881220235421809751254540594752243' '52584907711670556013604839586446706324415722155397' '53697817977846174064955149290862569321978468622482' '83972241375657056057490261407972968652414535100474' '82166370484403199890008895243450658541227588666881' '16427171479924442928230863465674813919123162824586' '17866458359124566529476545682848912883142607690042' '24219022671055626321111109370544217506941658960408' '07198403850962455444362981230987879927244284909188' '84580156166097919133875499200524063689912560717606' '05886116467109405077541002256983155200055935729725' '71636269561882670428252483600823257530420752963450' ) def _a ( _SCREAMING_SNAKE_CASE = N ) -> int: return max( # mypy cannot properly interpret reduce int(reduce(lambda _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : str(int(_SCREAMING_SNAKE_CASE ) * int(_SCREAMING_SNAKE_CASE ) ) , n[i : i + 13] ) ) for i in range(len(_SCREAMING_SNAKE_CASE ) - 12 ) ) if __name__ == "__main__": print(f"""{solution() = }""")
2
0