code
stringlengths
82
54.1k
code_codestyle
int64
0
699
style_context
stringlengths
111
35.6k
style_context_codestyle
int64
0
699
label
int64
0
1
def UpperCAmelCase ( a_ = 4_0_0_0_0_0_0 ) -> int: """simple docstring""" __A = [0, 1] __A = 0 while fib[i] <= n: fib.append(fib[i] + fib[i + 1] ) if fib[i + 2] > n: break i += 1 __A = 0 for j in range(len(a_ ) - 1 ): if fib[j] % 2 == 0: total += fib[j] return total if __name__ == "__main__": print(f'''{solution() = }''')
55
SCREAMING_SNAKE_CASE :int = {str(digit): digit**5 for digit in range(10)} def UpperCAmelCase ( a_ ) -> int: """simple docstring""" return sum(DIGITS_FIFTH_POWER[digit] for digit in str(a_ ) ) def UpperCAmelCase ( ) -> int: """simple docstring""" return sum( number for number in range(1_0_0_0 , 1_0_0_0_0_0_0 ) if number == digits_fifth_powers_sum(a_ ) ) if __name__ == "__main__": print(solution())
55
1
import unittest from transformers import JukeboxTokenizer from transformers.testing_utils import require_torch class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' snake_case_ = JukeboxTokenizer snake_case_ = { "artist": "Zac Brown Band", "genres": "Country", "lyrics": "I met a traveller from an antique land,\n Who said \"Two vast and trunkless legs of stone\n Stand in the desert. . . . Near them, on the sand,\n Half sunk a shattered visage lies, whose frown,\n And wrinkled lip, and sneer of cold command,\n Tell that its sculptor well those passions read\n Which yet survive, stamped on these lifeless things,\n The hand that mocked them, and the heart that fed;\n And on the pedestal, these words appear:\n My name is Ozymandias, King of Kings;\n Look on my Works, ye Mighty, and despair!\n Nothing beside remains. Round the decay\n Of that colossal Wreck, boundless and bare\n The lone and level sands stretch far away\n ", } @require_torch def UpperCamelCase_ ( self : List[str] ): import torch __A = JukeboxTokenizer.from_pretrained("openai/jukebox-1b-lyrics" ) __A = tokenizer(**self.metas )["input_ids"] # fmt: off __A = [ torch.tensor([[ 0, 0, 0, 71_69, 5_07, 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, 10_69, 11]] ), torch.tensor([[0, 0, 0, 10_69, 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 UpperCamelCase_ ( self : List[Any] ): import torch __A = JukeboxTokenizer.from_pretrained("openai/jukebox-5b-lyrics" ) __A = tokenizer(**self.metas )["input_ids"] # fmt: off __A = [ torch.tensor([[ 0, 0, 0, 10_69, 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, 10_69, 11, -1, -1, -1, -1]] ), torch.tensor([[0, 0, 0, 10_69, 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] ) )
55
import inspect import unittest from transformers import MobileNetVaConfig 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 MobileNetVaForImageClassification, MobileNetVaModel from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileNetVaImageProcessor class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def UpperCamelCase_ ( self : Any ): __A = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(A ,"tf_padding" ) ) self.parent.assertTrue(hasattr(A ,"depth_multiplier" ) ) class UpperCAmelCase : '''simple docstring''' def __init__( self : Optional[Any] ,A : int ,A : List[Any]=13 ,A : int=3 ,A : Optional[Any]=32 ,A : Union[str, Any]=0.25 ,A : Tuple=8 ,A : Optional[int]=True ,A : Union[str, Any]=10_24 ,A : Any=32 ,A : Optional[int]="relu6" ,A : int=0.1 ,A : Optional[Any]=0.02 ,A : Optional[Any]=True ,A : List[str]=True ,A : str=10 ,A : str=None ,): __A = parent __A = batch_size __A = num_channels __A = image_size __A = depth_multiplier __A = min_depth __A = tf_padding __A = int(last_hidden_size * depth_multiplier ) __A = output_stride __A = hidden_act __A = classifier_dropout_prob __A = use_labels __A = is_training __A = num_labels __A = initializer_range __A = scope def UpperCamelCase_ ( self : Optional[int] ): __A = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __A = None __A = None if self.use_labels: __A = ids_tensor([self.batch_size] ,self.num_labels ) __A = ids_tensor([self.batch_size, self.image_size, self.image_size] ,self.num_labels ) __A = self.get_config() return config, pixel_values, labels, pixel_labels def UpperCamelCase_ ( self : Any ): return MobileNetVaConfig( num_channels=self.num_channels ,image_size=self.image_size ,depth_multiplier=self.depth_multiplier ,min_depth=self.min_depth ,tf_padding=self.tf_padding ,hidden_act=self.hidden_act ,classifier_dropout_prob=self.classifier_dropout_prob ,initializer_range=self.initializer_range ,) def UpperCamelCase_ ( self : Optional[int] ,A : str ,A : Tuple ,A : Optional[int] ,A : List[str] ): __A = MobileNetVaModel(config=A ) model.to(A ) model.eval() __A = model(A ) self.parent.assertEqual( result.last_hidden_state.shape ,( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) ,) def UpperCamelCase_ ( self : List[Any] ,A : Union[str, Any] ,A : List[Any] ,A : int ,A : Union[str, Any] ): __A = self.num_labels __A = MobileNetVaForImageClassification(A ) model.to(A ) model.eval() __A = model(A ,labels=A ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def UpperCamelCase_ ( self : Tuple ): __A = self.prepare_config_and_inputs() __A , __A , __A , __A = config_and_inputs __A = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = (MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else () snake_case_ = ( {"feature-extraction": MobileNetVaModel, "image-classification": MobileNetVaForImageClassification} if is_torch_available() else {} ) snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = False def UpperCamelCase_ ( self : Any ): __A = MobileNetVaModelTester(self ) __A = MobileNetVaConfigTester(self ,config_class=A ,has_text_modality=A ) def UpperCamelCase_ ( self : str ): self.config_tester.run_common_tests() @unittest.skip(reason="MobileNetV1 does not use inputs_embeds" ) def UpperCamelCase_ ( self : Union[str, Any] ): pass @unittest.skip(reason="MobileNetV1 does not support input and output embeddings" ) def UpperCamelCase_ ( self : Tuple ): pass @unittest.skip(reason="MobileNetV1 does not output attentions" ) def UpperCamelCase_ ( self : Any ): pass def UpperCamelCase_ ( self : Optional[int] ): __A , __A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __A = model_class(A ) __A = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __A = [*signature.parameters.keys()] __A = ["pixel_values"] self.assertListEqual(arg_names[:1] ,A ) def UpperCamelCase_ ( self : List[Any] ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A ) def UpperCamelCase_ ( self : Optional[int] ): def check_hidden_states_output(A : List[Any] ,A : List[Any] ,A : Optional[int] ): __A = model_class(A ) model.to(A ) model.eval() with torch.no_grad(): __A = model(**self._prepare_for_class(A ,A ) ) __A = outputs.hidden_states __A = 26 self.assertEqual(len(A ) ,A ) __A , __A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __A = True check_hidden_states_output(A ,A ,A ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __A = True check_hidden_states_output(A ,A ,A ) def UpperCamelCase_ ( self : Tuple ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*A ) @slow def UpperCamelCase_ ( self : Union[str, Any] ): for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __A = MobileNetVaModel.from_pretrained(A ) self.assertIsNotNone(A ) def UpperCAmelCase ( ) -> str: """simple docstring""" __A = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def UpperCamelCase_ ( self : List[str] ): return ( MobileNetVaImageProcessor.from_pretrained("google/mobilenet_v1_1.0_224" ) if is_vision_available() else None ) @slow def UpperCamelCase_ ( self : Optional[Any] ): __A = MobileNetVaForImageClassification.from_pretrained("google/mobilenet_v1_1.0_224" ).to(A ) __A = self.default_image_processor __A = prepare_img() __A = image_processor(images=A ,return_tensors="pt" ).to(A ) # forward pass with torch.no_grad(): __A = model(**A ) # verify the logits __A = torch.Size((1, 10_01) ) self.assertEqual(outputs.logits.shape ,A ) __A = torch.tensor([-4.17_39, -1.12_33, 3.12_05] ).to(A ) self.assertTrue(torch.allclose(outputs.logits[0, :3] ,A ,atol=1E-4 ) )
55
1
def UpperCAmelCase ( a_ ) -> list[int]: """simple docstring""" __A = len(a_ ) for i in range(a_ ): for j in range(i + 1 , a_ ): if numbers[j] < numbers[i]: __A , __A = numbers[j], numbers[i] return numbers if __name__ == "__main__": SCREAMING_SNAKE_CASE :Optional[Any] = input('Enter numbers separated by a comma:\n').strip() SCREAMING_SNAKE_CASE :List[Any] = [int(item) for item in user_input.split(',')] print(exchange_sort(unsorted))
55
import copy import unittest from transformers.models.auto import get_values from transformers.testing_utils import require_torch, 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, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_MULTIPLE_CHOICE_MAPPING, MODEL_FOR_QUESTION_ANSWERING_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaModel, ) from transformers.models.layoutlmva.modeling_layoutlmva import LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class UpperCAmelCase : '''simple docstring''' def __init__( self : str ,A : int ,A : int=2 ,A : Optional[Any]=3 ,A : Dict=4 ,A : Optional[int]=2 ,A : Union[str, Any]=7 ,A : List[str]=True ,A : Union[str, Any]=True ,A : Optional[int]=True ,A : Optional[int]=True ,A : Tuple=99 ,A : Optional[int]=36 ,A : Dict=3 ,A : str=4 ,A : Optional[Any]=37 ,A : Dict="gelu" ,A : Dict=0.1 ,A : Union[str, Any]=0.1 ,A : Union[str, Any]=5_12 ,A : Any=16 ,A : Union[str, Any]=2 ,A : List[Any]=0.02 ,A : List[Any]=6 ,A : Optional[int]=6 ,A : List[Any]=3 ,A : Union[str, Any]=4 ,A : Tuple=None ,A : List[str]=10_00 ,): __A = parent __A = batch_size __A = num_channels __A = image_size __A = patch_size __A = text_seq_length __A = is_training __A = use_input_mask __A = use_token_type_ids __A = use_labels __A = vocab_size __A = hidden_size __A = num_hidden_layers __A = num_attention_heads __A = intermediate_size __A = hidden_act __A = hidden_dropout_prob __A = attention_probs_dropout_prob __A = max_position_embeddings __A = type_vocab_size __A = type_sequence_label_size __A = initializer_range __A = coordinate_size __A = shape_size __A = num_labels __A = num_choices __A = scope __A = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) __A = text_seq_length __A = (image_size // patch_size) ** 2 + 1 __A = self.text_seq_length + self.image_seq_length def UpperCamelCase_ ( self : int ): __A = ids_tensor([self.batch_size, self.text_seq_length] ,self.vocab_size ) __A = ids_tensor([self.batch_size, self.text_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]: __A = bbox[i, j, 3] __A = bbox[i, j, 1] __A = t if bbox[i, j, 2] < bbox[i, j, 0]: __A = bbox[i, j, 2] __A = bbox[i, j, 0] __A = t __A = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __A = None if self.use_input_mask: __A = random_attention_mask([self.batch_size, self.text_seq_length] ) __A = None if self.use_token_type_ids: __A = ids_tensor([self.batch_size, self.text_seq_length] ,self.type_vocab_size ) __A = None __A = None if self.use_labels: __A = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) __A = ids_tensor([self.batch_size, self.text_seq_length] ,self.num_labels ) __A = LayoutLMvaConfig( 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 ,coordinate_size=self.coordinate_size ,shape_size=self.shape_size ,input_size=self.image_size ,patch_size=self.patch_size ,) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def UpperCamelCase_ ( self : Optional[int] ,A : List[str] ,A : Any ,A : Dict ,A : List[Any] ,A : Optional[int] ,A : Any ,A : Dict ,A : List[Any] ): __A = LayoutLMvaModel(config=A ) model.to(A ) model.eval() # text + image __A = model(A ,pixel_values=A ) __A = model( A ,bbox=A ,pixel_values=A ,attention_mask=A ,token_type_ids=A ) __A = model(A ,bbox=A ,pixel_values=A ,token_type_ids=A ) __A = model(A ,bbox=A ,pixel_values=A ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) # text only __A = model(A ) self.parent.assertEqual( result.last_hidden_state.shape ,(self.batch_size, self.text_seq_length, self.hidden_size) ) # image only __A = model(pixel_values=A ) self.parent.assertEqual( result.last_hidden_state.shape ,(self.batch_size, self.image_seq_length, self.hidden_size) ) def UpperCamelCase_ ( self : Optional[int] ,A : Dict ,A : List[str] ,A : Any ,A : List[Any] ,A : Any ,A : Any ,A : Dict ,A : Optional[Any] ): __A = self.num_labels __A = LayoutLMvaForSequenceClassification(A ) model.to(A ) model.eval() __A = model( A ,bbox=A ,pixel_values=A ,attention_mask=A ,token_type_ids=A ,labels=A ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def UpperCamelCase_ ( self : str ,A : Optional[Any] ,A : Dict ,A : str ,A : Tuple ,A : Union[str, Any] ,A : List[Any] ,A : Any ,A : Union[str, Any] ): __A = self.num_labels __A = LayoutLMvaForTokenClassification(config=A ) model.to(A ) model.eval() __A = model( A ,bbox=A ,pixel_values=A ,attention_mask=A ,token_type_ids=A ,labels=A ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.text_seq_length, self.num_labels) ) def UpperCamelCase_ ( self : Optional[int] ,A : Optional[Any] ,A : int ,A : str ,A : List[str] ,A : int ,A : List[str] ,A : List[str] ,A : Dict ): __A = LayoutLMvaForQuestionAnswering(config=A ) model.to(A ) model.eval() __A = model( A ,bbox=A ,pixel_values=A ,attention_mask=A ,token_type_ids=A ,start_positions=A ,end_positions=A ,) self.parent.assertEqual(result.start_logits.shape ,(self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape ,(self.batch_size, self.seq_length) ) def UpperCamelCase_ ( self : str ): __A = self.prepare_config_and_inputs() ( ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ) = config_and_inputs __A = { "input_ids": input_ids, "bbox": bbox, "pixel_values": pixel_values, "token_type_ids": token_type_ids, "attention_mask": input_mask, } return config, inputs_dict @require_torch class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = ( ( LayoutLMvaModel, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaForQuestionAnswering, ) if is_torch_available() else () ) snake_case_ = ( {"document-question-answering": LayoutLMvaForQuestionAnswering, "feature-extraction": LayoutLMvaModel} if is_torch_available() else {} ) def UpperCamelCase_ ( self : str ,A : Any ,A : Any ,A : Tuple ,A : List[Any] ,A : Optional[Any] ): # `DocumentQuestionAnsweringPipeline` is expected to work with this model, but it combines the text and visual # embedding along the sequence dimension (dim 1), which causes an error during post-processing as `p_mask` has # the sequence dimension of the text embedding only. # (see the line `embedding_output = torch.cat([embedding_output, visual_embeddings], dim=1)`) return True def UpperCamelCase_ ( self : Union[str, Any] ): __A = LayoutLMvaModelTester(self ) __A = ConfigTester(self ,config_class=A ,hidden_size=37 ) def UpperCamelCase_ ( self : List[Any] ,A : int ,A : List[str] ,A : Dict=False ): __A = copy.deepcopy(A ) if model_class in get_values(A ): __A = { k: v.unsqueeze(1 ).expand(-1 ,self.model_tester.num_choices ,-1 ).contiguous() if isinstance(A ,torch.Tensor ) and v.ndim > 1 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(A ): __A = torch.ones(self.model_tester.batch_size ,dtype=torch.long ,device=A ) elif model_class in get_values(A ): __A = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=A ) __A = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=A ) elif model_class in [ *get_values(A ), ]: __A = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=A ) elif model_class in [ *get_values(A ), ]: __A = torch.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) ,dtype=torch.long ,device=A ,) return inputs_dict def UpperCamelCase_ ( self : List[Any] ): self.config_tester.run_common_tests() def UpperCamelCase_ ( self : Union[str, Any] ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A ) def UpperCamelCase_ ( self : str ): __A = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __A = type self.model_tester.create_and_check_model(*A ) def UpperCamelCase_ ( self : Optional[Any] ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*A ) def UpperCamelCase_ ( self : Optional[Any] ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*A ) def UpperCamelCase_ ( self : str ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*A ) @slow def UpperCamelCase_ ( self : Optional[int] ): for model_name in LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __A = LayoutLMvaModel.from_pretrained(A ) self.assertIsNotNone(A ) def UpperCAmelCase ( ) -> Dict: """simple docstring""" __A = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def UpperCamelCase_ ( self : Any ): return LayoutLMvaImageProcessor(apply_ocr=A ) if is_vision_available() else None @slow def UpperCamelCase_ ( self : Dict ): __A = LayoutLMvaModel.from_pretrained("microsoft/layoutlmv3-base" ).to(A ) __A = self.default_image_processor __A = prepare_img() __A = image_processor(images=A ,return_tensors="pt" ).pixel_values.to(A ) __A = torch.tensor([[1, 2]] ) __A = torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]] ).unsqueeze(0 ) # forward pass __A = model( input_ids=input_ids.to(A ) ,bbox=bbox.to(A ) ,pixel_values=pixel_values.to(A ) ,) # verify the logits __A = torch.Size((1, 1_99, 7_68) ) self.assertEqual(outputs.last_hidden_state.shape ,A ) __A = torch.tensor( [[-0.05_29, 0.36_18, 0.16_32], [-0.15_87, -0.16_67, -0.04_00], [-0.15_57, -0.16_71, -0.05_05]] ).to(A ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] ,A ,atol=1E-4 ) )
55
1
import argparse import json import logging import os import shutil import sys import tempfile import unittest from unittest import mock import torch from accelerate.utils import write_basic_config from transformers.testing_utils import TestCasePlus, get_gpu_count, run_command, slow, torch_device from transformers.utils import is_apex_available logging.basicConfig(level=logging.DEBUG) SCREAMING_SNAKE_CASE :Optional[int] = logging.getLogger() def UpperCAmelCase ( ) -> Any: """simple docstring""" __A = argparse.ArgumentParser() parser.add_argument("-f" ) __A = parser.parse_args() return args.f def UpperCAmelCase ( a_ ) -> Union[str, Any]: """simple docstring""" __A = {} __A = os.path.join(a_ , "all_results.json" ) if os.path.exists(a_ ): with open(a_ , "r" ) as f: __A = json.load(a_ ) else: raise ValueError(F'''can\'t find {path}''' ) return results def UpperCAmelCase ( ) -> List[Any]: """simple docstring""" __A = torch.cuda.is_available() and torch_device == "cuda" return is_using_cuda and is_apex_available() SCREAMING_SNAKE_CASE :Dict = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' @classmethod def UpperCamelCase_ ( cls : List[Any] ): # Write Accelerate config, will pick up on CPU, GPU, and multi-GPU __A = tempfile.mkdtemp() __A = os.path.join(cls.tmpdir ,"default_config.yml" ) write_basic_config(save_location=cls.configPath ) __A = ["accelerate", "launch", "--config_file", cls.configPath] @classmethod def UpperCamelCase_ ( cls : Union[str, Any] ): shutil.rmtree(cls.tmpdir ) @mock.patch.dict(os.environ ,{"WANDB_MODE": "offline"} ) def UpperCamelCase_ ( self : Dict ): __A = self.get_auto_remove_tmp_dir() __A = f''' {self.examples_dir}/pytorch/text-classification/run_glue_no_trainer.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --seed=42 --checkpointing_steps epoch --with_tracking '''.split() if is_cuda_and_apex_available(): testargs.append("--fp16" ) run_command(self._launch_args + testargs ) __A = get_results(A ) self.assertGreaterEqual(result["eval_accuracy"] ,0.75 ) self.assertTrue(os.path.exists(os.path.join(A ,"epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(A ,"glue_no_trainer" ) ) ) @mock.patch.dict(os.environ ,{"WANDB_MODE": "offline"} ) def UpperCamelCase_ ( self : Tuple ): __A = self.get_auto_remove_tmp_dir() __A = f''' {self.examples_dir}/pytorch/language-modeling/run_clm_no_trainer.py --model_name_or_path distilgpt2 --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --block_size 128 --per_device_train_batch_size 5 --per_device_eval_batch_size 5 --num_train_epochs 2 --output_dir {tmp_dir} --checkpointing_steps epoch --with_tracking '''.split() if torch.cuda.device_count() > 1: # Skipping because there are not enough batches to train the model + would need a drop_last to work. return run_command(self._launch_args + testargs ) __A = get_results(A ) self.assertLess(result["perplexity"] ,1_00 ) self.assertTrue(os.path.exists(os.path.join(A ,"epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(A ,"clm_no_trainer" ) ) ) @mock.patch.dict(os.environ ,{"WANDB_MODE": "offline"} ) def UpperCamelCase_ ( self : int ): __A = self.get_auto_remove_tmp_dir() __A = f''' {self.examples_dir}/pytorch/language-modeling/run_mlm_no_trainer.py --model_name_or_path distilroberta-base --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --output_dir {tmp_dir} --num_train_epochs=1 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __A = get_results(A ) self.assertLess(result["perplexity"] ,42 ) self.assertTrue(os.path.exists(os.path.join(A ,"epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(A ,"mlm_no_trainer" ) ) ) @mock.patch.dict(os.environ ,{"WANDB_MODE": "offline"} ) def UpperCamelCase_ ( self : Optional[int] ): # with so little data distributed training needs more epochs to get the score on par with 0/1 gpu __A = 7 if get_gpu_count() > 1 else 2 __A = self.get_auto_remove_tmp_dir() __A = f''' {self.examples_dir}/pytorch/token-classification/run_ner_no_trainer.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/conll/sample.json --validation_file tests/fixtures/tests_samples/conll/sample.json --output_dir {tmp_dir} --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=2 --num_train_epochs={epochs} --seed 7 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __A = get_results(A ) self.assertGreaterEqual(result["eval_accuracy"] ,0.75 ) self.assertLess(result["train_loss"] ,0.5 ) self.assertTrue(os.path.exists(os.path.join(A ,"epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(A ,"ner_no_trainer" ) ) ) @unittest.skip(reason="Fix me @muellerzr" ) @mock.patch.dict(os.environ ,{"WANDB_MODE": "offline"} ) def UpperCamelCase_ ( self : int ): __A = self.get_auto_remove_tmp_dir() __A = f''' {self.examples_dir}/pytorch/question-answering/run_qa_no_trainer.py --model_name_or_path bert-base-uncased --version_2_with_negative --train_file tests/fixtures/tests_samples/SQUAD/sample.json --validation_file tests/fixtures/tests_samples/SQUAD/sample.json --output_dir {tmp_dir} --seed=42 --max_train_steps=10 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __A = get_results(A ) # Because we use --version_2_with_negative the testing script uses SQuAD v2 metrics. self.assertGreaterEqual(result["eval_f1"] ,28 ) self.assertGreaterEqual(result["eval_exact"] ,28 ) self.assertTrue(os.path.exists(os.path.join(A ,"epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(A ,"qa_no_trainer" ) ) ) @mock.patch.dict(os.environ ,{"WANDB_MODE": "offline"} ) def UpperCamelCase_ ( self : Optional[Any] ): __A = self.get_auto_remove_tmp_dir() __A = f''' {self.examples_dir}/pytorch/multiple-choice/run_swag_no_trainer.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/swag/sample.json --validation_file tests/fixtures/tests_samples/swag/sample.json --output_dir {tmp_dir} --max_train_steps=20 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --with_tracking '''.split() run_command(self._launch_args + testargs ) __A = get_results(A ) self.assertGreaterEqual(result["eval_accuracy"] ,0.8 ) self.assertTrue(os.path.exists(os.path.join(A ,"swag_no_trainer" ) ) ) @slow @mock.patch.dict(os.environ ,{"WANDB_MODE": "offline"} ) def UpperCamelCase_ ( self : str ): __A = self.get_auto_remove_tmp_dir() __A = f''' {self.examples_dir}/pytorch/summarization/run_summarization_no_trainer.py --model_name_or_path t5-small --train_file tests/fixtures/tests_samples/xsum/sample.json --validation_file tests/fixtures/tests_samples/xsum/sample.json --output_dir {tmp_dir} --max_train_steps=50 --num_warmup_steps=8 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __A = get_results(A ) self.assertGreaterEqual(result["eval_rouge1"] ,10 ) self.assertGreaterEqual(result["eval_rouge2"] ,2 ) self.assertGreaterEqual(result["eval_rougeL"] ,7 ) self.assertGreaterEqual(result["eval_rougeLsum"] ,7 ) self.assertTrue(os.path.exists(os.path.join(A ,"epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(A ,"summarization_no_trainer" ) ) ) @slow @mock.patch.dict(os.environ ,{"WANDB_MODE": "offline"} ) def UpperCamelCase_ ( self : Any ): __A = self.get_auto_remove_tmp_dir() __A = f''' {self.examples_dir}/pytorch/translation/run_translation_no_trainer.py --model_name_or_path sshleifer/student_marian_en_ro_6_1 --source_lang en --target_lang ro --train_file tests/fixtures/tests_samples/wmt16/sample.json --validation_file tests/fixtures/tests_samples/wmt16/sample.json --output_dir {tmp_dir} --max_train_steps=50 --num_warmup_steps=8 --num_beams=6 --learning_rate=3e-3 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --source_lang en_XX --target_lang ro_RO --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __A = get_results(A ) self.assertGreaterEqual(result["eval_bleu"] ,30 ) self.assertTrue(os.path.exists(os.path.join(A ,"epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(A ,"translation_no_trainer" ) ) ) @slow def UpperCamelCase_ ( self : Optional[int] ): __A = logging.StreamHandler(sys.stdout ) logger.addHandler(A ) __A = self.get_auto_remove_tmp_dir() __A = f''' {self.examples_dir}/pytorch/semantic-segmentation/run_semantic_segmentation_no_trainer.py --dataset_name huggingface/semantic-segmentation-test-sample --output_dir {tmp_dir} --max_train_steps=10 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch '''.split() run_command(self._launch_args + testargs ) __A = get_results(A ) self.assertGreaterEqual(result["eval_overall_accuracy"] ,0.10 ) @mock.patch.dict(os.environ ,{"WANDB_MODE": "offline"} ) def UpperCamelCase_ ( self : Optional[int] ): __A = self.get_auto_remove_tmp_dir() __A = f''' {self.examples_dir}/pytorch/image-classification/run_image_classification_no_trainer.py --model_name_or_path google/vit-base-patch16-224-in21k --dataset_name hf-internal-testing/cats_vs_dogs_sample --learning_rate 1e-4 --per_device_train_batch_size 2 --per_device_eval_batch_size 1 --max_train_steps 2 --train_val_split 0.1 --seed 42 --output_dir {tmp_dir} --with_tracking --checkpointing_steps 1 '''.split() if is_cuda_and_apex_available(): testargs.append("--fp16" ) run_command(self._launch_args + testargs ) __A = get_results(A ) # The base model scores a 25% self.assertGreaterEqual(result["eval_accuracy"] ,0.6 ) self.assertTrue(os.path.exists(os.path.join(A ,"step_1" ) ) ) self.assertTrue(os.path.exists(os.path.join(A ,"image_classification_no_trainer" ) ) )
55
import unittest import numpy as np from datasets import load_dataset 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 BeitImageProcessor class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self : Any ,A : List[str] ,A : str=7 ,A : Optional[Any]=3 ,A : Any=18 ,A : int=30 ,A : int=4_00 ,A : List[str]=True ,A : Union[str, Any]=None ,A : Union[str, Any]=True ,A : Tuple=None ,A : Tuple=True ,A : Union[str, Any]=[0.5, 0.5, 0.5] ,A : str=[0.5, 0.5, 0.5] ,A : List[Any]=False ,): __A = size if size is not None else {"height": 20, "width": 20} __A = crop_size if crop_size is not None else {"height": 18, "width": 18} __A = parent __A = batch_size __A = num_channels __A = image_size __A = min_resolution __A = max_resolution __A = do_resize __A = size __A = do_center_crop __A = crop_size __A = do_normalize __A = image_mean __A = image_std __A = do_reduce_labels def UpperCamelCase_ ( self : List[str] ): return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_reduce_labels": self.do_reduce_labels, } def UpperCAmelCase ( ) -> int: """simple docstring""" __A = load_dataset("hf-internal-testing/fixtures_ade20k" , split="test" ) __A = Image.open(dataset[0]["file"] ) __A = Image.open(dataset[1]["file"] ) return image, map def UpperCAmelCase ( ) -> Optional[int]: """simple docstring""" __A = load_dataset("hf-internal-testing/fixtures_ade20k" , split="test" ) __A = Image.open(ds[0]["file"] ) __A = Image.open(ds[1]["file"] ) __A = Image.open(ds[2]["file"] ) __A = Image.open(ds[3]["file"] ) return [imagea, imagea], [mapa, mapa] @require_torch @require_vision class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = BeitImageProcessor if is_vision_available() else None def UpperCamelCase_ ( self : List[Any] ): __A = BeitImageProcessingTester(self ) @property def UpperCamelCase_ ( self : List[Any] ): return self.image_processor_tester.prepare_image_processor_dict() def UpperCamelCase_ ( self : int ): __A = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(A ,"do_resize" ) ) self.assertTrue(hasattr(A ,"size" ) ) self.assertTrue(hasattr(A ,"do_center_crop" ) ) self.assertTrue(hasattr(A ,"center_crop" ) ) self.assertTrue(hasattr(A ,"do_normalize" ) ) self.assertTrue(hasattr(A ,"image_mean" ) ) self.assertTrue(hasattr(A ,"image_std" ) ) def UpperCamelCase_ ( self : List[str] ): __A = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size ,{"height": 20, "width": 20} ) self.assertEqual(image_processor.crop_size ,{"height": 18, "width": 18} ) self.assertEqual(image_processor.do_reduce_labels ,A ) __A = self.image_processing_class.from_dict( self.image_processor_dict ,size=42 ,crop_size=84 ,reduce_labels=A ) self.assertEqual(image_processor.size ,{"height": 42, "width": 42} ) self.assertEqual(image_processor.crop_size ,{"height": 84, "width": 84} ) self.assertEqual(image_processor.do_reduce_labels ,A ) def UpperCamelCase_ ( self : List[Any] ): pass def UpperCamelCase_ ( self : Optional[int] ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __A = prepare_image_inputs(self.image_processor_tester ,equal_resolution=A ) for image in image_inputs: self.assertIsInstance(A ,Image.Image ) # Test not batched input __A = 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 __A = image_processing(A ,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 UpperCamelCase_ ( self : List[str] ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __A = prepare_image_inputs(self.image_processor_tester ,equal_resolution=A ,numpify=A ) for image in image_inputs: self.assertIsInstance(A ,np.ndarray ) # Test not batched input __A = 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 __A = image_processing(A ,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 UpperCamelCase_ ( self : int ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A = prepare_image_inputs(self.image_processor_tester ,equal_resolution=A ,torchify=A ) for image in image_inputs: self.assertIsInstance(A ,torch.Tensor ) # Test not batched input __A = 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 __A = image_processing(A ,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 UpperCamelCase_ ( self : str ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A = prepare_image_inputs(self.image_processor_tester ,equal_resolution=A ,torchify=A ) __A = [] for image in image_inputs: self.assertIsInstance(A ,torch.Tensor ) maps.append(torch.zeros(image.shape[-2:] ).long() ) # Test not batched input __A = image_processing(image_inputs[0] ,maps[0] ,return_tensors="pt" ) self.assertEqual( encoding["pixel_values"].shape ,( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,) self.assertEqual( encoding["labels"].shape ,( 1, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,) self.assertEqual(encoding["labels"].dtype ,torch.long ) self.assertTrue(encoding["labels"].min().item() >= 0 ) self.assertTrue(encoding["labels"].max().item() <= 2_55 ) # Test batched __A = image_processing(A ,A ,return_tensors="pt" ) self.assertEqual( encoding["pixel_values"].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"], ) ,) self.assertEqual( encoding["labels"].shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,) self.assertEqual(encoding["labels"].dtype ,torch.long ) self.assertTrue(encoding["labels"].min().item() >= 0 ) self.assertTrue(encoding["labels"].max().item() <= 2_55 ) # Test not batched input (PIL images) __A , __A = prepare_semantic_single_inputs() __A = image_processing(A ,A ,return_tensors="pt" ) self.assertEqual( encoding["pixel_values"].shape ,( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,) self.assertEqual( encoding["labels"].shape ,( 1, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,) self.assertEqual(encoding["labels"].dtype ,torch.long ) self.assertTrue(encoding["labels"].min().item() >= 0 ) self.assertTrue(encoding["labels"].max().item() <= 2_55 ) # Test batched input (PIL images) __A , __A = prepare_semantic_batch_inputs() __A = image_processing(A ,A ,return_tensors="pt" ) self.assertEqual( encoding["pixel_values"].shape ,( 2, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,) self.assertEqual( encoding["labels"].shape ,( 2, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,) self.assertEqual(encoding["labels"].dtype ,torch.long ) self.assertTrue(encoding["labels"].min().item() >= 0 ) self.assertTrue(encoding["labels"].max().item() <= 2_55 ) def UpperCamelCase_ ( self : Dict ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # ADE20k has 150 classes, and the background is included, so labels should be between 0 and 150 __A , __A = prepare_semantic_single_inputs() __A = image_processing(A ,A ,return_tensors="pt" ) self.assertTrue(encoding["labels"].min().item() >= 0 ) self.assertTrue(encoding["labels"].max().item() <= 1_50 ) __A = True __A = image_processing(A ,A ,return_tensors="pt" ) self.assertTrue(encoding["labels"].min().item() >= 0 ) self.assertTrue(encoding["labels"].max().item() <= 2_55 )
55
1
from abc import ABC, abstractmethod from argparse import ArgumentParser class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' @staticmethod @abstractmethod def UpperCamelCase_ ( A : ArgumentParser ): raise NotImplementedError() @abstractmethod def UpperCamelCase_ ( self : int ): raise NotImplementedError()
55
from numpy import exp, pi, sqrt def UpperCAmelCase ( a_ , a_ = 0.0 , a_ = 1.0 ) -> int: """simple docstring""" return 1 / sqrt(2 * pi * sigma**2 ) * exp(-((x - mu) ** 2) / (2 * sigma**2) ) if __name__ == "__main__": import doctest doctest.testmod()
55
1
SCREAMING_SNAKE_CASE :Dict = '\n# Transformers installation\n! pip install transformers datasets\n# To install from source instead of the last release, comment the command above and uncomment the following one.\n# ! pip install git+https://github.com/huggingface/transformers.git\n' SCREAMING_SNAKE_CASE :int = [{'type': 'code', 'content': INSTALL_CONTENT}] SCREAMING_SNAKE_CASE :List[str] = { '{processor_class}': 'FakeProcessorClass', '{model_class}': 'FakeModelClass', '{object_class}': 'FakeObjectClass', }
55
import gc import unittest from diffusers import FlaxStableDiffusionInpaintPipeline from diffusers.utils import is_flax_available, load_image, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard @slow @require_flax class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase_ ( self : Tuple ): # clean up the VRAM after each test super().tearDown() gc.collect() def UpperCamelCase_ ( self : Optional[int] ): __A = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/sd2-inpaint/init_image.png" ) __A = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png" ) __A = "xvjiarui/stable-diffusion-2-inpainting" __A , __A = FlaxStableDiffusionInpaintPipeline.from_pretrained(A ,safety_checker=A ) __A = "Face of a yellow cat, high resolution, sitting on a park bench" __A = jax.random.PRNGKey(0 ) __A = 50 __A = jax.device_count() __A = num_samples * [prompt] __A = num_samples * [init_image] __A = num_samples * [mask_image] __A , __A , __A = pipeline.prepare_inputs(A ,A ,A ) # shard inputs and rng __A = replicate(A ) __A = jax.random.split(A ,jax.device_count() ) __A = shard(A ) __A = shard(A ) __A = shard(A ) __A = pipeline( A ,A ,A ,A ,A ,A ,jit=A ) __A = output.images.reshape(A ,5_12 ,5_12 ,3 ) __A = images[0, 2_53:2_56, 2_53:2_56, -1] __A = jnp.asarray(jax.device_get(image_slice.flatten() ) ) __A = jnp.array( [0.3_61_13_07, 0.37_64_97_36, 0.3_75_74_08, 0.38_21_39_53, 0.39_29_51_67, 0.3_84_16_31, 0.41_55_49_78, 0.4_13_74_75, 0.4_21_70_84] ) print(f'''output_slice: {output_slice}''' ) assert jnp.abs(output_slice - expected_slice ).max() < 1E-2
55
1
import torch from diffusers import CMStochasticIterativeScheduler from .test_schedulers import SchedulerCommonTest class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = (CMStochasticIterativeScheduler,) snake_case_ = 10 def UpperCamelCase_ ( self : str ,**A : List[str] ): __A = { "num_train_timesteps": 2_01, "sigma_min": 0.0_02, "sigma_max": 80.0, } config.update(**A ) return config def UpperCamelCase_ ( self : int ): __A = 10 __A = self.get_scheduler_config() __A = self.scheduler_classes[0](**A ) scheduler.set_timesteps(A ) __A = scheduler.timesteps[0] __A = scheduler.timesteps[1] __A = self.dummy_sample __A = 0.1 * sample __A = scheduler.step(A ,A ,A ).prev_sample __A = scheduler.step(A ,A ,A ).prev_sample self.assertEqual(output_a.shape ,sample.shape ) self.assertEqual(output_a.shape ,output_a.shape ) def UpperCamelCase_ ( self : Dict ): for timesteps in [10, 50, 1_00, 10_00]: self.check_over_configs(num_train_timesteps=A ) def UpperCamelCase_ ( self : Dict ): for clip_denoised in [True, False]: self.check_over_configs(clip_denoised=A ) def UpperCamelCase_ ( self : str ): __A = self.scheduler_classes[0] __A = self.get_scheduler_config() __A = scheduler_class(**A ) __A = 1 scheduler.set_timesteps(A ) __A = scheduler.timesteps __A = torch.manual_seed(0 ) __A = self.dummy_model() __A = self.dummy_sample_deter * scheduler.init_noise_sigma for i, t in enumerate(A ): # 1. scale model input __A = scheduler.scale_model_input(A ,A ) # 2. predict noise residual __A = model(A ,A ) # 3. predict previous sample x_t-1 __A = scheduler.step(A ,A ,A ,generator=A ).prev_sample __A = pred_prev_sample __A = torch.sum(torch.abs(A ) ) __A = torch.mean(torch.abs(A ) ) assert abs(result_sum.item() - 1_92.76_14 ) < 1E-2 assert abs(result_mean.item() - 0.25_10 ) < 1E-3 def UpperCamelCase_ ( self : Union[str, Any] ): __A = self.scheduler_classes[0] __A = self.get_scheduler_config() __A = scheduler_class(**A ) __A = [1_06, 0] scheduler.set_timesteps(timesteps=A ) __A = scheduler.timesteps __A = torch.manual_seed(0 ) __A = self.dummy_model() __A = self.dummy_sample_deter * scheduler.init_noise_sigma for t in timesteps: # 1. scale model input __A = scheduler.scale_model_input(A ,A ) # 2. predict noise residual __A = model(A ,A ) # 3. predict previous sample x_t-1 __A = scheduler.step(A ,A ,A ,generator=A ).prev_sample __A = pred_prev_sample __A = torch.sum(torch.abs(A ) ) __A = torch.mean(torch.abs(A ) ) assert abs(result_sum.item() - 3_47.63_57 ) < 1E-2 assert abs(result_mean.item() - 0.45_27 ) < 1E-3 def UpperCamelCase_ ( self : Dict ): __A = self.scheduler_classes[0] __A = self.get_scheduler_config() __A = scheduler_class(**A ) __A = [39, 30, 12, 15, 0] with self.assertRaises(A ,msg="`timesteps` must be in descending order." ): scheduler.set_timesteps(timesteps=A ) def UpperCamelCase_ ( self : Optional[Any] ): __A = self.scheduler_classes[0] __A = self.get_scheduler_config() __A = scheduler_class(**A ) __A = [39, 30, 12, 1, 0] __A = len(A ) with self.assertRaises(A ,msg="Can only pass one of `num_inference_steps` or `timesteps`." ): scheduler.set_timesteps(num_inference_steps=A ,timesteps=A ) def UpperCamelCase_ ( self : Optional[int] ): __A = self.scheduler_classes[0] __A = self.get_scheduler_config() __A = scheduler_class(**A ) __A = [scheduler.config.num_train_timesteps] with self.assertRaises( A ,msg="`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}" ,): scheduler.set_timesteps(timesteps=A )
55
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 GLPNImageProcessor class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self : Any ,A : Optional[int] ,A : Optional[int]=7 ,A : Optional[Any]=3 ,A : List[str]=18 ,A : Any=30 ,A : Tuple=4_00 ,A : Union[str, Any]=True ,A : Optional[Any]=32 ,A : Union[str, Any]=True ,): __A = parent __A = batch_size __A = num_channels __A = image_size __A = min_resolution __A = max_resolution __A = do_resize __A = size_divisor __A = do_rescale def UpperCamelCase_ ( self : Union[str, Any] ): return { "do_resize": self.do_resize, "size_divisor": self.size_divisor, "do_rescale": self.do_rescale, } @require_torch @require_vision class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = GLPNImageProcessor if is_vision_available() else None def UpperCamelCase_ ( self : int ): __A = GLPNImageProcessingTester(self ) @property def UpperCamelCase_ ( self : Optional[Any] ): return self.image_processor_tester.prepare_image_processor_dict() def UpperCamelCase_ ( self : Any ): __A = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(A ,"do_resize" ) ) self.assertTrue(hasattr(A ,"size_divisor" ) ) self.assertTrue(hasattr(A ,"resample" ) ) self.assertTrue(hasattr(A ,"do_rescale" ) ) def UpperCamelCase_ ( self : str ): pass def UpperCamelCase_ ( self : Dict ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __A = prepare_image_inputs(self.image_processor_tester ,equal_resolution=A ) for image in image_inputs: self.assertIsInstance(A ,Image.Image ) # Test not batched input (GLPNImageProcessor doesn't support batching) __A = image_processing(image_inputs[0] ,return_tensors="pt" ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 ) def UpperCamelCase_ ( self : Optional[Any] ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __A = prepare_image_inputs(self.image_processor_tester ,equal_resolution=A ,numpify=A ) for image in image_inputs: self.assertIsInstance(A ,np.ndarray ) # Test not batched input (GLPNImageProcessor doesn't support batching) __A = image_processing(image_inputs[0] ,return_tensors="pt" ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 ) def UpperCamelCase_ ( self : int ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A = prepare_image_inputs(self.image_processor_tester ,equal_resolution=A ,torchify=A ) for image in image_inputs: self.assertIsInstance(A ,torch.Tensor ) # Test not batched input (GLPNImageProcessor doesn't support batching) __A = image_processing(image_inputs[0] ,return_tensors="pt" ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 )
55
1
def UpperCAmelCase ( a_ ) -> int: """simple docstring""" __A = abs(a_ ) __A = 0 while n > 0: res += n % 1_0 n //= 1_0 return res def UpperCAmelCase ( a_ ) -> int: """simple docstring""" __A = abs(a_ ) return n if n < 1_0 else n % 1_0 + sum_of_digits(n // 1_0 ) def UpperCAmelCase ( a_ ) -> int: """simple docstring""" return sum(int(a_ ) for c in str(abs(a_ ) ) ) def UpperCAmelCase ( ) -> None: """simple docstring""" from collections.abc import Callable from timeit import timeit def benchmark_a_function(a_ , a_ ) -> None: __A = F'''{func.__name__}({value})''' __A = timeit(F'''__main__.{call}''' , setup="import __main__" ) print(F'''{call:56} = {func(a_ )} -- {timing:.4f} seconds''' ) for value in (2_6_2_1_4_4, 1_1_2_5_8_9_9_9_0_6_8_4_2_6_2_4, 1_2_6_7_6_5_0_6_0_0_2_2_8_2_2_9_4_0_1_4_9_6_7_0_3_2_0_5_3_7_6): for func in (sum_of_digits, sum_of_digits_recursion, sum_of_digits_compact): benchmark_a_function(a_ , a_ ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
55
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Image from .base import TaskTemplate @dataclass(frozen=__SCREAMING_SNAKE_CASE ) class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = field(default="image-classification" , metadata={"include_in_asdict_even_if_is_default": True} ) snake_case_ = Features({"image": Image()} ) snake_case_ = Features({"labels": ClassLabel} ) snake_case_ = "image" snake_case_ = "labels" def UpperCamelCase_ ( self : Optional[Any] ,A : Tuple ): if self.label_column not in features: raise ValueError(f'''Column {self.label_column} is not present in features.''' ) if not isinstance(features[self.label_column] ,A ): raise ValueError(f'''Column {self.label_column} is not a ClassLabel.''' ) __A = copy.deepcopy(self ) __A = self.label_schema.copy() __A = features[self.label_column] __A = label_schema return task_template @property def UpperCamelCase_ ( self : Any ): return { self.image_column: "image", self.label_column: "labels", }
55
1
from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def UpperCAmelCase ( a_ , a_ , a_ , a_ , ) -> list[float]: """simple docstring""" __A , __A = coefficient_matrix.shape __A , __A = constant_matrix.shape if rowsa != colsa: __A = F'''Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}''' raise ValueError(a_ ) if colsa != 1: __A = F'''Constant matrix must be nx1 but received {rowsa}x{colsa}''' raise ValueError(a_ ) if rowsa != rowsa: __A = ( "Coefficient and constant matrices dimensions must be nxn and nx1 but " F'''received {rowsa}x{colsa} and {rowsa}x{colsa}''' ) raise ValueError(a_ ) if len(a_ ) != rowsa: __A = ( "Number of initial values must be equal to number of rows in coefficient " F'''matrix but received {len(a_ )} and {rowsa}''' ) raise ValueError(a_ ) if iterations <= 0: raise ValueError("Iterations must be at least 1" ) __A = np.concatenate( (coefficient_matrix, constant_matrix) , axis=1 ) __A , __A = table.shape strictly_diagonally_dominant(a_ ) # Iterates the whole matrix for given number of times for _ in range(a_ ): __A = [] for row in range(a_ ): __A = 0 for col in range(a_ ): if col == row: __A = table[row][col] elif col == cols - 1: __A = table[row][col] else: temp += (-1) * table[row][col] * init_val[col] __A = (temp + val) / denom new_val.append(a_ ) __A = new_val return [float(a_ ) for i in new_val] def UpperCAmelCase ( a_ ) -> bool: """simple docstring""" __A , __A = table.shape __A = True for i in range(0 , a_ ): __A = 0 for j in range(0 , cols - 1 ): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError("Coefficient matrix is not strictly diagonally dominant" ) return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
55
from math import sqrt def UpperCAmelCase ( a_ ) -> bool: """simple docstring""" assert isinstance(a_ , a_ ) and ( number >= 0 ), "'number' must been an int and positive" __A = True # 0 and 1 are none primes. if number <= 1: __A = False for divisor in range(2 , int(round(sqrt(a_ ) ) ) + 1 ): # if 'number' divisible by 'divisor' then sets 'status' # of false and break up the loop. if number % divisor == 0: __A = False break # precondition assert isinstance(a_ , a_ ), "'status' must been from type bool" return status def UpperCAmelCase ( a_ ) -> Any: """simple docstring""" assert isinstance(a_ , a_ ) and (n > 2), "'N' must been an int and > 2" # beginList: contains all natural numbers from 2 up to N __A = list(range(2 , n + 1 ) ) __A = [] # this list will be returns. # actual sieve of erathostenes for i in range(len(a_ ) ): for j in range(i + 1 , len(a_ ) ): if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0): __A = 0 # filters actual prime numbers. __A = [x for x in begin_list if x != 0] # precondition assert isinstance(a_ , a_ ), "'ans' must been from type list" return ans def UpperCAmelCase ( a_ ) -> Optional[int]: """simple docstring""" assert isinstance(a_ , a_ ) and (n > 2), "'N' must been an int and > 2" __A = [] # iterates over all numbers between 2 up to N+1 # if a number is prime then appends to list 'ans' for number in range(2 , n + 1 ): if is_prime(a_ ): ans.append(a_ ) # precondition assert isinstance(a_ , a_ ), "'ans' must been from type list" return ans def UpperCAmelCase ( a_ ) -> Optional[int]: """simple docstring""" assert isinstance(a_ , a_ ) and number >= 0, "'number' must been an int and >= 0" __A = [] # this list will be returns of the function. # potential prime number factors. __A = 2 __A = number if number == 0 or number == 1: ans.append(a_ ) # if 'number' not prime then builds the prime factorization of 'number' elif not is_prime(a_ ): while quotient != 1: if is_prime(a_ ) and (quotient % factor == 0): ans.append(a_ ) quotient /= factor else: factor += 1 else: ans.append(a_ ) # precondition assert isinstance(a_ , a_ ), "'ans' must been from type list" return ans def UpperCAmelCase ( a_ ) -> Any: """simple docstring""" assert isinstance(a_ , a_ ) and ( number >= 0 ), "'number' bust been an int and >= 0" __A = 0 # prime factorization of 'number' __A = prime_factorization(a_ ) __A = max(a_ ) # precondition assert isinstance(a_ , a_ ), "'ans' must been from type int" return ans def UpperCAmelCase ( a_ ) -> Optional[Any]: """simple docstring""" assert isinstance(a_ , a_ ) and ( number >= 0 ), "'number' bust been an int and >= 0" __A = 0 # prime factorization of 'number' __A = prime_factorization(a_ ) __A = min(a_ ) # precondition assert isinstance(a_ , a_ ), "'ans' must been from type int" return ans def UpperCAmelCase ( a_ ) -> int: """simple docstring""" assert isinstance(a_ , a_ ), "'number' must been an int" assert isinstance(number % 2 == 0 , a_ ), "compare bust been from type bool" return number % 2 == 0 def UpperCAmelCase ( a_ ) -> List[Any]: """simple docstring""" assert isinstance(a_ , a_ ), "'number' must been an int" assert isinstance(number % 2 != 0 , a_ ), "compare bust been from type bool" return number % 2 != 0 def UpperCAmelCase ( a_ ) -> Optional[Any]: """simple docstring""" assert ( isinstance(a_ , a_ ) and (number > 2) and is_even(a_ ) ), "'number' must been an int, even and > 2" __A = [] # this list will returned # creates a list of prime numbers between 2 up to 'number' __A = get_prime_numbers(a_ ) __A = len(a_ ) # run variable for while-loops. __A = 0 __A = None # exit variable. for break up the loops __A = True while i < len_pn and loop: __A = i + 1 while j < len_pn and loop: if prime_numbers[i] + prime_numbers[j] == number: __A = False ans.append(prime_numbers[i] ) ans.append(prime_numbers[j] ) j += 1 i += 1 # precondition assert ( isinstance(a_ , a_ ) and (len(a_ ) == 2) and (ans[0] + ans[1] == number) and is_prime(ans[0] ) and is_prime(ans[1] ) ), "'ans' must contains two primes. And sum of elements must been eq 'number'" return ans def UpperCAmelCase ( a_ , a_ ) -> Optional[Any]: """simple docstring""" assert ( isinstance(a_ , a_ ) and isinstance(a_ , a_ ) and (numbera >= 0) and (numbera >= 0) ), "'number1' and 'number2' must been positive integer." __A = 0 while numbera != 0: __A = numbera % numbera __A = numbera __A = rest # precondition assert isinstance(a_ , a_ ) and ( numbera >= 0 ), "'number' must been from type int and positive" return numbera def UpperCAmelCase ( a_ , a_ ) -> List[str]: """simple docstring""" assert ( isinstance(a_ , a_ ) and isinstance(a_ , a_ ) and (numbera >= 1) and (numbera >= 1) ), "'number1' and 'number2' must been positive integer." __A = 1 # actual answer that will be return. # for kgV (x,1) if numbera > 1 and numbera > 1: # builds the prime factorization of 'number1' and 'number2' __A = prime_factorization(a_ ) __A = prime_factorization(a_ ) elif numbera == 1 or numbera == 1: __A = [] __A = [] __A = max(a_ , a_ ) __A = 0 __A = 0 __A = [] # captured numbers int both 'primeFac1' and 'primeFac2' # iterates through primeFac1 for n in prime_fac_a: if n not in done: if n in prime_fac_a: __A = prime_fac_a.count(a_ ) __A = prime_fac_a.count(a_ ) for _ in range(max(a_ , a_ ) ): ans *= n else: __A = prime_fac_a.count(a_ ) for _ in range(a_ ): ans *= n done.append(a_ ) # iterates through primeFac2 for n in prime_fac_a: if n not in done: __A = prime_fac_a.count(a_ ) for _ in range(a_ ): ans *= n done.append(a_ ) # precondition assert isinstance(a_ , a_ ) and ( ans >= 0 ), "'ans' must been from type int and positive" return ans def UpperCAmelCase ( a_ ) -> str: """simple docstring""" assert isinstance(a_ , a_ ) and (n >= 0), "'number' must been a positive int" __A = 0 __A = 2 # this variable holds the answer while index < n: index += 1 ans += 1 # counts to the next number # if ans not prime then # runs to the next prime number. while not is_prime(a_ ): ans += 1 # precondition assert isinstance(a_ , a_ ) and is_prime( a_ ), "'ans' must been a prime number and from type int" return ans def UpperCAmelCase ( a_ , a_ ) -> Tuple: """simple docstring""" assert ( is_prime(a_ ) and is_prime(a_ ) and (p_number_a < p_number_a) ), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'" __A = p_number_a + 1 # jump to the next number __A = [] # this list will be returns. # if number is not prime then # fetch the next prime number. while not is_prime(a_ ): number += 1 while number < p_number_a: ans.append(a_ ) number += 1 # fetch the next prime number. while not is_prime(a_ ): number += 1 # precondition assert ( isinstance(a_ , a_ ) and ans[0] != p_number_a and ans[len(a_ ) - 1] != p_number_a ), "'ans' must been a list without the arguments" # 'ans' contains not 'pNumber1' and 'pNumber2' ! return ans def UpperCAmelCase ( a_ ) -> str: """simple docstring""" assert isinstance(a_ , a_ ) and (n >= 1), "'n' must been int and >= 1" __A = [] # will be returned. for divisor in range(1 , n + 1 ): if n % divisor == 0: ans.append(a_ ) # precondition assert ans[0] == 1 and ans[len(a_ ) - 1] == n, "Error in function getDivisiors(...)" return ans def UpperCAmelCase ( a_ ) -> Dict: """simple docstring""" assert isinstance(a_ , a_ ) and ( number > 1 ), "'number' must been an int and >= 1" __A = get_divisors(a_ ) # precondition assert ( isinstance(a_ , a_ ) and (divisors[0] == 1) and (divisors[len(a_ ) - 1] == number) ), "Error in help-function getDivisiors(...)" # summed all divisors up to 'number' (exclusive), hence [:-1] return sum(divisors[:-1] ) == number def UpperCAmelCase ( a_ , a_ ) -> str: """simple docstring""" assert ( isinstance(a_ , a_ ) and isinstance(a_ , a_ ) and (denominator != 0) ), "The arguments must been from type int and 'denominator' != 0" # build the greatest common divisor of numerator and denominator. __A = gcd(abs(a_ ) , abs(a_ ) ) # precondition assert ( isinstance(a_ , a_ ) and (numerator % gcd_of_fraction == 0) and (denominator % gcd_of_fraction == 0) ), "Error in function gcd(...,...)" return (numerator // gcd_of_fraction, denominator // gcd_of_fraction) def UpperCAmelCase ( a_ ) -> Optional[int]: """simple docstring""" assert isinstance(a_ , a_ ) and (n >= 0), "'n' must been a int and >= 0" __A = 1 # this will be return. for factor in range(1 , n + 1 ): ans *= factor return ans def UpperCAmelCase ( a_ ) -> List[Any]: """simple docstring""" assert isinstance(a_ , a_ ) and (n >= 0), "'n' must been an int and >= 0" __A = 0 __A = 1 __A = 1 # this will be return for _ in range(n - 1 ): __A = ans ans += fiba __A = tmp return ans
55
1
from __future__ import annotations from collections import deque from collections.abc import Iterator from dataclasses import dataclass @dataclass class UpperCAmelCase : '''simple docstring''' snake_case_ = 42 snake_case_ = 42 class UpperCAmelCase : '''simple docstring''' def __init__( self : Any ,A : int ): __A = [[] for _ in range(A )] __A = size def __getitem__( self : str ,A : int ): return iter(self._graph[vertex] ) @property def UpperCamelCase_ ( self : List[Any] ): return self._size def UpperCamelCase_ ( self : Union[str, Any] ,A : int ,A : int ,A : int ): if weight not in (0, 1): raise ValueError("Edge weight must be either 0 or 1." ) if to_vertex < 0 or to_vertex >= self.size: raise ValueError("Vertex indexes must be in [0; size)." ) self._graph[from_vertex].append(Edge(A ,A ) ) def UpperCamelCase_ ( self : List[Any] ,A : int ,A : int ): __A = deque([start_vertex] ) __A = [None] * self.size __A = 0 while queue: __A = queue.popleft() __A = distances[current_vertex] if current_distance is None: continue for edge in self[current_vertex]: __A = current_distance + edge.weight __A = distances[edge.destination_vertex] if ( isinstance(A ,A ) and new_distance >= dest_vertex_distance ): continue __A = new_distance if edge.weight == 0: queue.appendleft(edge.destination_vertex ) else: queue.append(edge.destination_vertex ) if distances[finish_vertex] is None: raise ValueError("No path from start_vertex to finish_vertex." ) return distances[finish_vertex] if __name__ == "__main__": import doctest doctest.testmod()
55
import os def UpperCAmelCase ( ) -> Any: """simple docstring""" __A = os.path.dirname(os.path.realpath(a_ ) ) __A = os.path.join(a_ , "triangle.txt" ) with open(a_ ) as f: __A = f.readlines() __A = [] for line in triangle: __A = [] for number in line.strip().split(" " ): numbers_from_line.append(int(a_ ) ) a.append(a_ ) for i in range(1 , len(a_ ) ): for j in range(len(a[i] ) ): __A = a[i - 1][j] if j != len(a[i - 1] ) else 0 __A = a[i - 1][j - 1] if j > 0 else 0 a[i][j] += max(a_ , a_ ) return max(a[-1] ) if __name__ == "__main__": print(solution())
55
1
from __future__ import annotations import inspect import unittest import numpy as np from transformers import DeiTConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, TFDeiTModel, ) from transformers.models.deit.modeling_tf_deit import TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class UpperCAmelCase : '''simple docstring''' def __init__( self : List[Any] ,A : Union[str, Any] ,A : List[Any]=13 ,A : Optional[Any]=30 ,A : Union[str, Any]=2 ,A : Union[str, Any]=3 ,A : Any=True ,A : Dict=True ,A : str=32 ,A : Tuple=2 ,A : Optional[int]=4 ,A : Tuple=37 ,A : List[Any]="gelu" ,A : Dict=0.1 ,A : Optional[int]=0.1 ,A : List[Any]=10 ,A : Optional[Any]=0.02 ,A : Dict=3 ,A : Dict=None ,A : List[Any]=2 ,): __A = parent __A = batch_size __A = image_size __A = patch_size __A = num_channels __A = is_training __A = use_labels __A = hidden_size __A = num_hidden_layers __A = num_attention_heads __A = intermediate_size __A = hidden_act __A = hidden_dropout_prob __A = attention_probs_dropout_prob __A = type_sequence_label_size __A = initializer_range __A = scope __A = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) __A = (image_size // patch_size) ** 2 __A = num_patches + 2 def UpperCamelCase_ ( self : List[Any] ): __A = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __A = None if self.use_labels: __A = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) __A = self.get_config() return config, pixel_values, labels def UpperCamelCase_ ( self : Optional[int] ): return DeiTConfig( image_size=self.image_size ,patch_size=self.patch_size ,num_channels=self.num_channels ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,hidden_act=self.hidden_act ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,is_decoder=A ,initializer_range=self.initializer_range ,encoder_stride=self.encoder_stride ,) def UpperCamelCase_ ( self : List[str] ,A : List[Any] ,A : Optional[int] ,A : Union[str, Any] ): __A = TFDeiTModel(config=A ) __A = model(A ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase_ ( self : List[Any] ,A : List[Any] ,A : Optional[Any] ,A : Dict ): __A = TFDeiTForMaskedImageModeling(config=A ) __A = model(A ) self.parent.assertEqual( result.reconstruction.shape ,(self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images __A = 1 __A = TFDeiTForMaskedImageModeling(A ) __A = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __A = model(A ) self.parent.assertEqual(result.reconstruction.shape ,(self.batch_size, 1, self.image_size, self.image_size) ) def UpperCamelCase_ ( self : Optional[Any] ,A : Union[str, Any] ,A : Dict ,A : Union[str, Any] ): __A = self.type_sequence_label_size __A = TFDeiTForImageClassification(A ) __A = model(A ,labels=A ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) # test greyscale images __A = 1 __A = TFDeiTForImageClassification(A ) __A = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __A = model(A ,labels=A ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) def UpperCamelCase_ ( self : str ): __A = self.prepare_config_and_inputs() __A , __A , __A = config_and_inputs __A = {"pixel_values": pixel_values} return config, inputs_dict @require_tf class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = ( ( TFDeiTModel, TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, ) if is_tf_available() else () ) snake_case_ = ( { "feature-extraction": TFDeiTModel, "image-classification": (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher), } if is_tf_available() else {} ) snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = False def UpperCamelCase_ ( self : str ): __A = TFDeiTModelTester(self ) __A = ConfigTester(self ,config_class=A ,has_text_modality=A ,hidden_size=37 ) def UpperCamelCase_ ( self : Any ): self.config_tester.run_common_tests() @unittest.skip(reason="DeiT does not use inputs_embeds" ) def UpperCamelCase_ ( self : Union[str, Any] ): pass def UpperCamelCase_ ( self : List[Any] ): __A , __A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __A = model_class(A ) self.assertIsInstance(model.get_input_embeddings() ,(tf.keras.layers.Layer) ) __A = model.get_output_embeddings() self.assertTrue(x is None or isinstance(A ,tf.keras.layers.Dense ) ) def UpperCamelCase_ ( self : Union[str, Any] ): __A , __A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __A = model_class(A ) __A = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __A = [*signature.parameters.keys()] __A = ["pixel_values"] self.assertListEqual(arg_names[:1] ,A ) def UpperCamelCase_ ( self : Union[str, Any] ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A ) def UpperCamelCase_ ( self : Union[str, Any] ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*A ) def UpperCamelCase_ ( self : Optional[Any] ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*A ) def UpperCamelCase_ ( self : Optional[int] ,A : Union[str, Any] ,A : List[str] ,A : Optional[Any]=False ): __A = super()._prepare_for_class(A ,A ,return_labels=A ) if return_labels: if "labels" in inputs_dict and "labels" not in inspect.signature(model_class.call ).parameters: del inputs_dict["labels"] return inputs_dict @slow def UpperCamelCase_ ( self : Any ): for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __A = TFDeiTModel.from_pretrained(A ) self.assertIsNotNone(A ) def UpperCAmelCase ( ) -> str: """simple docstring""" __A = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_tf @require_vision class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def UpperCamelCase_ ( self : int ): return ( DeiTImageProcessor.from_pretrained("facebook/deit-base-distilled-patch16-224" ) if is_vision_available() else None ) @slow def UpperCamelCase_ ( self : Optional[int] ): __A = TFDeiTForImageClassificationWithTeacher.from_pretrained("facebook/deit-base-distilled-patch16-224" ) __A = self.default_image_processor __A = prepare_img() __A = image_processor(images=A ,return_tensors="tf" ) # forward pass __A = model(**A ) # verify the logits __A = tf.TensorShape((1, 10_00) ) self.assertEqual(outputs.logits.shape ,A ) __A = tf.constant([-1.02_66, 0.19_12, -1.28_61] ) self.assertTrue(np.allclose(outputs.logits[0, :3] ,A ,atol=1E-4 ) )
55
import re from flax.core.frozen_dict import freeze from flax.traverse_util import flatten_dict, unflatten_dict from jax.experimental import PartitionSpec as P # Sentinels SCREAMING_SNAKE_CASE :Union[str, Any] = object() # For specifying empty leaf dict `{}` SCREAMING_SNAKE_CASE :List[str] = object() def UpperCAmelCase ( a_ , a_ ) -> Tuple: """simple docstring""" __A = tuple((re.compile(x + "$" ) for x in qs) ) for i in range(len(a_ ) - len(a_ ) + 1 ): __A = [x.match(a_ ) for x, y in zip(a_ , ks[i:] )] if matches and all(a_ ): return True return False def UpperCAmelCase ( a_ ) -> Optional[int]: """simple docstring""" def replace(a_ , a_ ): for rule, replacement in rules: if _match(a_ , a_ ): return replacement return val return replace def UpperCAmelCase ( ) -> int: """simple docstring""" return [ # embeddings (("transformer", "wpe", "embedding"), P("mp" , a_ )), (("transformer", "wte", "embedding"), P("mp" , a_ )), # atention (("attention", "(q_proj|k_proj|v_proj)", "kernel"), P(a_ , "mp" )), (("attention", "out_proj", "kernel"), P("mp" , a_ )), (("attention", "out_proj", "bias"), None), # mlp (("mlp", "c_fc", "kernel"), P(a_ , "mp" )), (("mlp", "c_fc", "bias"), P("mp" )), (("mlp", "c_proj", "kernel"), P("mp" , a_ )), (("mlp", "c_proj", "bias"), None), # layer norms ((r"ln_\d+", "bias"), None), ((r"\d+", r"ln_\d+", "scale"), None), (("ln_f", "bias"), None), (("ln_f", "scale"), None), ] def UpperCAmelCase ( a_ ) -> List[Any]: """simple docstring""" __A = _get_partition_rules() __A = _replacement_rules(a_ ) __A = {k: _unmatched for k in flatten_dict(a_ )} __A = {k: replace(a_ , a_ ) for k, v in initd.items()} assert _unmatched not in result.values(), "Incomplete partition spec." return freeze(unflatten_dict(a_ ) )
55
1
import numpy as np def UpperCAmelCase ( a_ ) -> np.array: """simple docstring""" return 1 / (1 + np.exp(-vector )) if __name__ == "__main__": import doctest doctest.testmod()
55
from __future__ import annotations import inspect import unittest import numpy as np from transformers import DeiTConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, TFDeiTModel, ) from transformers.models.deit.modeling_tf_deit import TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class UpperCAmelCase : '''simple docstring''' def __init__( self : List[Any] ,A : Union[str, Any] ,A : List[Any]=13 ,A : Optional[Any]=30 ,A : Union[str, Any]=2 ,A : Union[str, Any]=3 ,A : Any=True ,A : Dict=True ,A : str=32 ,A : Tuple=2 ,A : Optional[int]=4 ,A : Tuple=37 ,A : List[Any]="gelu" ,A : Dict=0.1 ,A : Optional[int]=0.1 ,A : List[Any]=10 ,A : Optional[Any]=0.02 ,A : Dict=3 ,A : Dict=None ,A : List[Any]=2 ,): __A = parent __A = batch_size __A = image_size __A = patch_size __A = num_channels __A = is_training __A = use_labels __A = hidden_size __A = num_hidden_layers __A = num_attention_heads __A = intermediate_size __A = hidden_act __A = hidden_dropout_prob __A = attention_probs_dropout_prob __A = type_sequence_label_size __A = initializer_range __A = scope __A = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) __A = (image_size // patch_size) ** 2 __A = num_patches + 2 def UpperCamelCase_ ( self : List[Any] ): __A = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __A = None if self.use_labels: __A = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) __A = self.get_config() return config, pixel_values, labels def UpperCamelCase_ ( self : Optional[int] ): return DeiTConfig( image_size=self.image_size ,patch_size=self.patch_size ,num_channels=self.num_channels ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,hidden_act=self.hidden_act ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,is_decoder=A ,initializer_range=self.initializer_range ,encoder_stride=self.encoder_stride ,) def UpperCamelCase_ ( self : List[str] ,A : List[Any] ,A : Optional[int] ,A : Union[str, Any] ): __A = TFDeiTModel(config=A ) __A = model(A ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase_ ( self : List[Any] ,A : List[Any] ,A : Optional[Any] ,A : Dict ): __A = TFDeiTForMaskedImageModeling(config=A ) __A = model(A ) self.parent.assertEqual( result.reconstruction.shape ,(self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images __A = 1 __A = TFDeiTForMaskedImageModeling(A ) __A = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __A = model(A ) self.parent.assertEqual(result.reconstruction.shape ,(self.batch_size, 1, self.image_size, self.image_size) ) def UpperCamelCase_ ( self : Optional[Any] ,A : Union[str, Any] ,A : Dict ,A : Union[str, Any] ): __A = self.type_sequence_label_size __A = TFDeiTForImageClassification(A ) __A = model(A ,labels=A ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) # test greyscale images __A = 1 __A = TFDeiTForImageClassification(A ) __A = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __A = model(A ,labels=A ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) def UpperCamelCase_ ( self : str ): __A = self.prepare_config_and_inputs() __A , __A , __A = config_and_inputs __A = {"pixel_values": pixel_values} return config, inputs_dict @require_tf class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = ( ( TFDeiTModel, TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, ) if is_tf_available() else () ) snake_case_ = ( { "feature-extraction": TFDeiTModel, "image-classification": (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher), } if is_tf_available() else {} ) snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = False def UpperCamelCase_ ( self : str ): __A = TFDeiTModelTester(self ) __A = ConfigTester(self ,config_class=A ,has_text_modality=A ,hidden_size=37 ) def UpperCamelCase_ ( self : Any ): self.config_tester.run_common_tests() @unittest.skip(reason="DeiT does not use inputs_embeds" ) def UpperCamelCase_ ( self : Union[str, Any] ): pass def UpperCamelCase_ ( self : List[Any] ): __A , __A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __A = model_class(A ) self.assertIsInstance(model.get_input_embeddings() ,(tf.keras.layers.Layer) ) __A = model.get_output_embeddings() self.assertTrue(x is None or isinstance(A ,tf.keras.layers.Dense ) ) def UpperCamelCase_ ( self : Union[str, Any] ): __A , __A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __A = model_class(A ) __A = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __A = [*signature.parameters.keys()] __A = ["pixel_values"] self.assertListEqual(arg_names[:1] ,A ) def UpperCamelCase_ ( self : Union[str, Any] ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A ) def UpperCamelCase_ ( self : Union[str, Any] ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*A ) def UpperCamelCase_ ( self : Optional[Any] ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*A ) def UpperCamelCase_ ( self : Optional[int] ,A : Union[str, Any] ,A : List[str] ,A : Optional[Any]=False ): __A = super()._prepare_for_class(A ,A ,return_labels=A ) if return_labels: if "labels" in inputs_dict and "labels" not in inspect.signature(model_class.call ).parameters: del inputs_dict["labels"] return inputs_dict @slow def UpperCamelCase_ ( self : Any ): for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __A = TFDeiTModel.from_pretrained(A ) self.assertIsNotNone(A ) def UpperCAmelCase ( ) -> str: """simple docstring""" __A = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_tf @require_vision class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def UpperCamelCase_ ( self : int ): return ( DeiTImageProcessor.from_pretrained("facebook/deit-base-distilled-patch16-224" ) if is_vision_available() else None ) @slow def UpperCamelCase_ ( self : Optional[int] ): __A = TFDeiTForImageClassificationWithTeacher.from_pretrained("facebook/deit-base-distilled-patch16-224" ) __A = self.default_image_processor __A = prepare_img() __A = image_processor(images=A ,return_tensors="tf" ) # forward pass __A = model(**A ) # verify the logits __A = tf.TensorShape((1, 10_00) ) self.assertEqual(outputs.logits.shape ,A ) __A = tf.constant([-1.02_66, 0.19_12, -1.28_61] ) self.assertTrue(np.allclose(outputs.logits[0, :3] ,A ,atol=1E-4 ) )
55
1
from __future__ import annotations from typing import Any class UpperCAmelCase : '''simple docstring''' def __init__( self : str ,A : int = 6 ): __A = None __A = None self.create_linked_list(A ) def UpperCamelCase_ ( self : Optional[Any] ,A : int ): __A = Node() __A = current_node __A = current_node __A = current_node for _ in range(1 ,A ): __A = Node() __A = current_node __A = previous_node __A = current_node __A = self.front __A = previous_node def UpperCamelCase_ ( self : Optional[int] ): return ( self.front == self.rear and self.front is not None and self.front.data is None ) def UpperCamelCase_ ( self : Optional[int] ): self.check_can_perform_operation() return self.front.data if self.front else None def UpperCamelCase_ ( self : Any ,A : Any ): if self.rear is None: return self.check_is_full() if not self.is_empty(): __A = self.rear.next if self.rear: __A = data def UpperCamelCase_ ( self : List[Any] ): self.check_can_perform_operation() if self.rear is None or self.front is None: return None if self.front == self.rear: __A = self.front.data __A = None return data __A = self.front __A = old_front.next __A = old_front.data __A = None return data def UpperCamelCase_ ( self : str ): if self.is_empty(): raise Exception("Empty Queue" ) def UpperCamelCase_ ( self : List[str] ): if self.rear and self.rear.next == self.front: raise Exception("Full Queue" ) class UpperCAmelCase : '''simple docstring''' def __init__( self : Any ): __A = None __A = None __A = None if __name__ == "__main__": import doctest doctest.testmod()
55
SCREAMING_SNAKE_CASE :List[Any] = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] SCREAMING_SNAKE_CASE :Union[str, Any] = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] SCREAMING_SNAKE_CASE :int = { 0: 'Sunday', 1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday', 5: 'Friday', 6: 'Saturday', } def UpperCAmelCase ( a_ , a_ , a_ ) -> str: """simple docstring""" assert len(str(a_ ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 1_2, "month should be between 1 to 12" assert 1 <= day <= 3_1, "day should be between 1 to 31" # Doomsday algorithm: __A = year // 1_0_0 __A = (5 * (century % 4) + 2) % 7 __A = year % 1_0_0 __A = centurian % 1_2 __A = ( (centurian // 1_2) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 __A = ( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 4_0_0) == 0) else DOOMSDAY_LEAP[month - 1] ) __A = (dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
55
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE :Tuple = {'configuration_vit_msn': ['VIT_MSN_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ViTMSNConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE :Optional[int] = [ 'VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST', 'ViTMSNModel', 'ViTMSNForImageClassification', 'ViTMSNPreTrainedModel', ] if TYPE_CHECKING: from .configuration_vit_msn import VIT_MSN_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTMSNConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vit_msn import ( VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST, ViTMSNForImageClassification, ViTMSNModel, ViTMSNPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE :List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
55
from json import JSONDecodeError # Workaround for requests.exceptions.JSONDecodeError import requests def UpperCAmelCase ( a_ = "isbn/0140328726" ) -> dict: """simple docstring""" __A = olid.strip().strip("/" ) # Remove leading/trailing whitespace & slashes if new_olid.count("/" ) != 1: __A = F'''{olid} is not a valid Open Library olid''' raise ValueError(a_ ) return requests.get(F'''https://openlibrary.org/{new_olid}.json''' ).json() def UpperCAmelCase ( a_ ) -> dict: """simple docstring""" __A = { "title": "Title", "publish_date": "Publish date", "authors": "Authors", "number_of_pages": "Number of pages:", "first_sentence": "First sentence", "isbn_10": "ISBN (10)", "isbn_13": "ISBN (13)", } __A = {better_key: ol_book_data[key] for key, better_key in desired_keys.items()} __A = [ get_openlibrary_data(author["key"] )["name"] for author in data["Authors"] ] __A = data["First sentence"]["value"] for key, value in data.items(): if isinstance(a_ , a_ ): __A = ", ".join(a_ ) return data if __name__ == "__main__": import doctest doctest.testmod() while True: SCREAMING_SNAKE_CASE :int = input('\nEnter the ISBN code to search (or \'quit\' to stop): ').strip() if isbn.lower() in ("", "q", "quit", "exit", "stop"): break if len(isbn) not in (10, 13) or not isbn.isdigit(): print(f'''Sorry, {isbn} is not a valid ISBN. Please, input a valid ISBN.''') continue print(f'''\nSearching Open Library for ISBN: {isbn}...\n''') try: SCREAMING_SNAKE_CASE :Any = summarize_book(get_openlibrary_data(f'''isbn/{isbn}''')) print('\n'.join(f'''{key}: {value}''' for key, value in book_summary.items())) except JSONDecodeError: # Workaround for requests.exceptions.RequestException: print(f'''Sorry, there are no results for ISBN: {isbn}.''')
55
1
from ....configuration_utils import PretrainedConfig from ....utils import logging SCREAMING_SNAKE_CASE :Tuple = logging.get_logger(__name__) SCREAMING_SNAKE_CASE :Any = { 'Visual-Attention-Network/van-base': ( 'https://huggingface.co/Visual-Attention-Network/van-base/blob/main/config.json' ), } class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = "van" def __init__( self : int ,A : str=2_24 ,A : int=3 ,A : Optional[Any]=[7, 3, 3, 3] ,A : Tuple=[4, 2, 2, 2] ,A : Union[str, Any]=[64, 1_28, 3_20, 5_12] ,A : Optional[int]=[3, 3, 12, 3] ,A : Optional[int]=[8, 8, 4, 4] ,A : Any="gelu" ,A : Union[str, Any]=0.02 ,A : Union[str, Any]=1E-6 ,A : Dict=1E-2 ,A : str=0.0 ,A : Optional[int]=0.0 ,**A : List[Any] ,): super().__init__(**A ) __A = image_size __A = num_channels __A = patch_sizes __A = strides __A = hidden_sizes __A = depths __A = mlp_ratios __A = hidden_act __A = initializer_range __A = layer_norm_eps __A = layer_scale_init_value __A = drop_path_rate __A = dropout_rate
55
import requests SCREAMING_SNAKE_CASE :List[str] = 'YOUR API KEY' def UpperCAmelCase ( a_ , a_ = giphy_api_key ) -> list: """simple docstring""" __A = "+".join(query.split() ) __A = F'''https://api.giphy.com/v1/gifs/search?q={formatted_query}&api_key={api_key}''' __A = requests.get(a_ ).json()["data"] return [gif["url"] for gif in gifs] if __name__ == "__main__": print('\n'.join(get_gifs('space ship')))
55
1
from maths.prime_factors import prime_factors def UpperCAmelCase ( a_ ) -> int: """simple docstring""" if not isinstance(a_ , a_ ): __A = F'''Input value of [number={number}] must be an integer''' raise TypeError(a_ ) if number < 1: raise ValueError("Input must be a positive integer" ) return -1 if len(prime_factors(a_ ) ) % 2 else 1 if __name__ == "__main__": import doctest doctest.testmod()
55
import itertools import math def UpperCAmelCase ( a_ ) -> bool: """simple docstring""" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(a_ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def UpperCAmelCase ( ) -> Optional[Any]: """simple docstring""" __A = 2 while True: if is_prime(a_ ): yield num num += 1 def UpperCAmelCase ( a_ = 1_0_0_0_1 ) -> int: """simple docstring""" return next(itertools.islice(prime_generator() , nth - 1 , a_ ) ) if __name__ == "__main__": print(f'''{solution() = }''')
55
1
import importlib.util import os import platform from argparse import ArgumentParser import huggingface_hub from .. import __version__ as version from ..utils import ( is_accelerate_available, is_flax_available, is_safetensors_available, is_tf_available, is_torch_available, ) from . import BaseTransformersCLICommand def UpperCAmelCase ( a_ ) -> Any: """simple docstring""" return EnvironmentCommand() def UpperCAmelCase ( a_ ) -> Any: """simple docstring""" return EnvironmentCommand(args.accelerate_config_file ) class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' @staticmethod def UpperCamelCase_ ( A : ArgumentParser ): __A = parser.add_parser("env" ) download_parser.set_defaults(func=A ) download_parser.add_argument( "--accelerate-config_file" ,default=A ,help="The accelerate config file to use for the default values in the launching script." ,) download_parser.set_defaults(func=A ) def __init__( self : List[str] ,A : str ,*A : str ): __A = accelerate_config_file def UpperCamelCase_ ( self : int ): __A = "not installed" if is_safetensors_available(): import safetensors __A = safetensors.__version__ elif importlib.util.find_spec("safetensors" ) is not None: import safetensors __A = f'''{safetensors.__version__} but is ignored because of PyTorch version too old.''' __A = "not installed" __A = __A = "not found" if is_accelerate_available(): import accelerate from accelerate.commands.config import default_config_file, load_config_from_file __A = accelerate.__version__ # Get the default from the config file. if self._accelerate_config_file is not None or os.path.isfile(A ): __A = load_config_from_file(self._accelerate_config_file ).to_dict() __A = ( "\n".join([f'''\t- {prop}: {val}''' for prop, val in accelerate_config.items()] ) if isinstance(A ,A ) else f'''\t{accelerate_config}''' ) __A = "not installed" __A = "NA" if is_torch_available(): import torch __A = torch.__version__ __A = torch.cuda.is_available() __A = "not installed" __A = "NA" if is_tf_available(): import tensorflow as tf __A = tf.__version__ try: # deprecated in v2.1 __A = tf.test.is_gpu_available() except AttributeError: # returns list of devices, convert to bool __A = bool(tf.config.list_physical_devices("GPU" ) ) __A = "not installed" __A = "not installed" __A = "not installed" __A = "NA" if is_flax_available(): import flax import jax import jaxlib __A = flax.__version__ __A = jax.__version__ __A = jaxlib.__version__ __A = jax.lib.xla_bridge.get_backend().platform __A = { "`transformers` version": version, "Platform": platform.platform(), "Python version": platform.python_version(), "Huggingface_hub version": huggingface_hub.__version__, "Safetensors version": f'''{safetensors_version}''', "Accelerate version": f'''{accelerate_version}''', "Accelerate config": f'''{accelerate_config_str}''', "PyTorch version (GPU?)": f'''{pt_version} ({pt_cuda_available})''', "Tensorflow version (GPU?)": f'''{tf_version} ({tf_cuda_available})''', "Flax version (CPU?/GPU?/TPU?)": f'''{flax_version} ({jax_backend})''', "Jax version": f'''{jax_version}''', "JaxLib version": f'''{jaxlib_version}''', "Using GPU in script?": "<fill in>", "Using distributed or parallel set-up in script?": "<fill in>", } print("\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n" ) print(self.format_dict(A ) ) return info @staticmethod def UpperCamelCase_ ( A : Tuple ): return "\n".join([f'''- {prop}: {val}''' for prop, val in d.items()] ) + "\n"
55
import argparse import os import numpy as np import tensorflow as tf import torch from transformers import BertModel def UpperCAmelCase ( a_ , a_ , a_ ) -> List[str]: """simple docstring""" __A = ("dense.weight", "attention.self.query", "attention.self.key", "attention.self.value") __A = ( ("layer.", "layer_"), ("word_embeddings.weight", "word_embeddings"), ("position_embeddings.weight", "position_embeddings"), ("token_type_embeddings.weight", "token_type_embeddings"), (".", "/"), ("LayerNorm/weight", "LayerNorm/gamma"), ("LayerNorm/bias", "LayerNorm/beta"), ("weight", "kernel"), ) if not os.path.isdir(a_ ): os.makedirs(a_ ) __A = model.state_dict() def to_tf_var_name(a_ ): for patt, repl in iter(a_ ): __A = name.replace(a_ , a_ ) return F'''bert/{name}''' def create_tf_var(a_ , a_ , a_ ): __A = tf.dtypes.as_dtype(tensor.dtype ) __A = tf.get_variable(dtype=a_ , shape=tensor.shape , name=a_ , initializer=tf.zeros_initializer() ) session.run(tf.variables_initializer([tf_var] ) ) session.run(a_ ) return tf_var tf.reset_default_graph() with tf.Session() as session: for var_name in state_dict: __A = to_tf_var_name(a_ ) __A = state_dict[var_name].numpy() if any(x in var_name for x in tensors_to_transpose ): __A = torch_tensor.T __A = create_tf_var(tensor=a_ , name=a_ , session=a_ ) tf.keras.backend.set_value(a_ , a_ ) __A = session.run(a_ ) print(F'''Successfully created {tf_name}: {np.allclose(a_ , a_ )}''' ) __A = tf.train.Saver(tf.trainable_variables() ) saver.save(a_ , os.path.join(a_ , model_name.replace("-" , "_" ) + ".ckpt" ) ) def UpperCAmelCase ( a_=None ) -> List[Any]: """simple docstring""" __A = argparse.ArgumentParser() parser.add_argument("--model_name" , type=a_ , required=a_ , help="model name e.g. bert-base-uncased" ) parser.add_argument( "--cache_dir" , type=a_ , default=a_ , required=a_ , help="Directory containing pytorch model" ) parser.add_argument("--pytorch_model_path" , type=a_ , required=a_ , help="/path/to/<pytorch-model-name>.bin" ) parser.add_argument("--tf_cache_dir" , type=a_ , required=a_ , help="Directory in which to save tensorflow model" ) __A = parser.parse_args(a_ ) __A = BertModel.from_pretrained( pretrained_model_name_or_path=args.model_name , state_dict=torch.load(args.pytorch_model_path ) , cache_dir=args.cache_dir , ) convert_pytorch_checkpoint_to_tf(model=a_ , ckpt_dir=args.tf_cache_dir , model_name=args.model_name ) if __name__ == "__main__": main()
55
1
def UpperCAmelCase ( a_ , a_ ) -> str: """simple docstring""" if a < 0 or b < 0: raise ValueError("the value of both inputs must be positive" ) __A = str(bin(a_ ) )[2:] # remove the leading "0b" __A = str(bin(a_ ) )[2:] # remove the leading "0b" __A = max(len(a_ ) , len(a_ ) ) return "0b" + "".join( str(int(char_a == "1" and char_b == "1" ) ) for char_a, char_b in zip(a_binary.zfill(a_ ) , b_binary.zfill(a_ ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
55
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE :Any = { 'configuration_pegasus_x': ['PEGASUS_X_PRETRAINED_CONFIG_ARCHIVE_MAP', 'PegasusXConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE :Any = [ 'PEGASUS_X_PRETRAINED_MODEL_ARCHIVE_LIST', 'PegasusXForConditionalGeneration', 'PegasusXModel', 'PegasusXPreTrainedModel', ] if TYPE_CHECKING: from .configuration_pegasus_x import PEGASUS_X_PRETRAINED_CONFIG_ARCHIVE_MAP, PegasusXConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pegasus_x import ( PEGASUS_X_PRETRAINED_MODEL_ARCHIVE_LIST, PegasusXForConditionalGeneration, PegasusXModel, PegasusXPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE :Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
55
1
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 FEATURE_EXTRACTOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor, ChineseCLIPProcessor @require_vision class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase_ ( self : str ): __A = tempfile.mkdtemp() __A = [ "[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "的", "价", "格", "是", "15", "便", "alex", "##andra", ",", "。", "-", "t", "shirt", ] __A = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file ,"w" ,encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) __A = { "do_resize": True, "size": {"height": 2_24, "width": 2_24}, "do_center_crop": True, "crop_size": {"height": 18, "width": 18}, "do_normalize": True, "image_mean": [0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73], "image_std": [0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11], "do_convert_rgb": True, } __A = os.path.join(self.tmpdirname ,A ) with open(self.image_processor_file ,"w" ,encoding="utf-8" ) as fp: json.dump(A ,A ) def UpperCamelCase_ ( self : Any ,**A : Dict ): return BertTokenizer.from_pretrained(self.tmpdirname ,**A ) def UpperCamelCase_ ( self : Dict ,**A : str ): return BertTokenizerFast.from_pretrained(self.tmpdirname ,**A ) def UpperCamelCase_ ( self : Optional[Any] ,**A : Dict ): return ChineseCLIPImageProcessor.from_pretrained(self.tmpdirname ,**A ) def UpperCamelCase_ ( self : Dict ): shutil.rmtree(self.tmpdirname ) def UpperCamelCase_ ( self : Any ): __A = [np.random.randint(2_55 ,size=(3, 30, 4_00) ,dtype=np.uinta )] __A = [Image.fromarray(np.moveaxis(A ,0 ,-1 ) ) for x in image_inputs] return image_inputs def UpperCamelCase_ ( self : Optional[int] ): __A = self.get_tokenizer() __A = self.get_rust_tokenizer() __A = self.get_image_processor() __A = ChineseCLIPProcessor(tokenizer=A ,image_processor=A ) processor_slow.save_pretrained(self.tmpdirname ) __A = ChineseCLIPProcessor.from_pretrained(self.tmpdirname ,use_fast=A ) __A = ChineseCLIPProcessor(tokenizer=A ,image_processor=A ) processor_fast.save_pretrained(self.tmpdirname ) __A = ChineseCLIPProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() ,tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() ,tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() ,tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer ,A ) self.assertIsInstance(processor_fast.tokenizer ,A ) self.assertEqual(processor_slow.image_processor.to_json_string() ,image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() ,image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor ,A ) self.assertIsInstance(processor_fast.image_processor ,A ) def UpperCamelCase_ ( self : List[str] ): __A = ChineseCLIPProcessor(tokenizer=self.get_tokenizer() ,image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __A = self.get_tokenizer(cls_token="(CLS)" ,sep_token="(SEP)" ) __A = self.get_image_processor(do_normalize=A ) __A = ChineseCLIPProcessor.from_pretrained( self.tmpdirname ,cls_token="(CLS)" ,sep_token="(SEP)" ,do_normalize=A ) self.assertEqual(processor.tokenizer.get_vocab() ,tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer ,A ) self.assertEqual(processor.image_processor.to_json_string() ,image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor ,A ) def UpperCamelCase_ ( self : List[Any] ): __A = self.get_image_processor() __A = self.get_tokenizer() __A = ChineseCLIPProcessor(tokenizer=A ,image_processor=A ) __A = self.prepare_image_inputs() __A = image_processor(A ,return_tensors="np" ) __A = processor(images=A ,return_tensors="np" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() ,input_processor[key].sum() ,delta=1E-2 ) def UpperCamelCase_ ( self : Any ): __A = self.get_image_processor() __A = self.get_tokenizer() __A = ChineseCLIPProcessor(tokenizer=A ,image_processor=A ) __A = "Alexandra,T-shirt的价格是15便士。" __A = processor(text=A ) __A = tokenizer(A ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] ,encoded_processor[key] ) def UpperCamelCase_ ( self : List[Any] ): __A = self.get_image_processor() __A = self.get_tokenizer() __A = ChineseCLIPProcessor(tokenizer=A ,image_processor=A ) __A = "Alexandra,T-shirt的价格是15便士。" __A = self.prepare_image_inputs() __A = processor(text=A ,images=A ) self.assertListEqual(list(inputs.keys() ) ,["input_ids", "token_type_ids", "attention_mask", "pixel_values"] ) # test if it raises when no input is passed with pytest.raises(A ): processor() def UpperCamelCase_ ( self : Optional[int] ): __A = self.get_image_processor() __A = self.get_tokenizer() __A = ChineseCLIPProcessor(tokenizer=A ,image_processor=A ) __A = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __A = processor.batch_decode(A ) __A = tokenizer.batch_decode(A ) self.assertListEqual(A ,A ) def UpperCamelCase_ ( self : Tuple ): __A = self.get_image_processor() __A = self.get_tokenizer() __A = ChineseCLIPProcessor(tokenizer=A ,image_processor=A ) __A = "Alexandra,T-shirt的价格是15便士。" __A = self.prepare_image_inputs() __A = processor(text=A ,images=A ) self.assertListEqual(list(inputs.keys() ) ,processor.model_input_names )
55
from __future__ import annotations from collections.abc import Generator import requests from bsa import BeautifulSoup SCREAMING_SNAKE_CASE :int = 'https://www.indeed.co.in/jobs?q=mobile+app+development&l=' def UpperCAmelCase ( a_ = "mumbai" ) -> Generator[tuple[str, str], None, None]: """simple docstring""" __A = BeautifulSoup(requests.get(url + location ).content , "html.parser" ) # This attribute finds out all the specifics listed in a job for job in soup.find_all("div" , attrs={"data-tn-component": "organicJob"} ): __A = job.find("a" , attrs={"data-tn-element": "jobTitle"} ).text.strip() __A = job.find("span" , {"class": "company"} ).text.strip() yield job_title, company_name if __name__ == "__main__": for i, job in enumerate(fetch_jobs('Bangalore'), 1): print(f'''Job {i:>2} is {job[0]} at {job[1]}''')
55
1
SCREAMING_SNAKE_CASE :List[Any] = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] SCREAMING_SNAKE_CASE :Union[str, Any] = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] SCREAMING_SNAKE_CASE :int = { 0: 'Sunday', 1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday', 5: 'Friday', 6: 'Saturday', } def UpperCAmelCase ( a_ , a_ , a_ ) -> str: """simple docstring""" assert len(str(a_ ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 1_2, "month should be between 1 to 12" assert 1 <= day <= 3_1, "day should be between 1 to 31" # Doomsday algorithm: __A = year // 1_0_0 __A = (5 * (century % 4) + 2) % 7 __A = year % 1_0_0 __A = centurian % 1_2 __A = ( (centurian // 1_2) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 __A = ( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 4_0_0) == 0) else DOOMSDAY_LEAP[month - 1] ) __A = (dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
55
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, BlipaProcessor, BlipImageProcessor, GPTaTokenizer, PreTrainedTokenizerFast @require_vision class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase_ ( self : List[str] ): __A = tempfile.mkdtemp() __A = BlipImageProcessor() __A = GPTaTokenizer.from_pretrained("hf-internal-testing/tiny-random-GPT2Model" ) __A = BlipaProcessor(A ,A ) processor.save_pretrained(self.tmpdirname ) def UpperCamelCase_ ( self : Dict ,**A : int ): return AutoProcessor.from_pretrained(self.tmpdirname ,**A ).tokenizer def UpperCamelCase_ ( self : Dict ,**A : Optional[int] ): return AutoProcessor.from_pretrained(self.tmpdirname ,**A ).image_processor def UpperCamelCase_ ( self : Dict ): shutil.rmtree(self.tmpdirname ) def UpperCamelCase_ ( self : Optional[int] ): __A = [np.random.randint(2_55 ,size=(3, 30, 4_00) ,dtype=np.uinta )] __A = [Image.fromarray(np.moveaxis(A ,0 ,-1 ) ) for x in image_inputs] return image_inputs def UpperCamelCase_ ( self : Any ): __A = BlipaProcessor(tokenizer=self.get_tokenizer() ,image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __A = self.get_tokenizer(bos_token="(BOS)" ,eos_token="(EOS)" ) __A = self.get_image_processor(do_normalize=A ,padding_value=1.0 ) __A = BlipaProcessor.from_pretrained( self.tmpdirname ,bos_token="(BOS)" ,eos_token="(EOS)" ,do_normalize=A ,padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() ,tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer ,A ) self.assertEqual(processor.image_processor.to_json_string() ,image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor ,A ) def UpperCamelCase_ ( self : List[Any] ): __A = self.get_image_processor() __A = self.get_tokenizer() __A = BlipaProcessor(tokenizer=A ,image_processor=A ) __A = self.prepare_image_inputs() __A = image_processor(A ,return_tensors="np" ) __A = processor(images=A ,return_tensors="np" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() ,input_processor[key].sum() ,delta=1E-2 ) def UpperCamelCase_ ( self : Tuple ): __A = self.get_image_processor() __A = self.get_tokenizer() __A = BlipaProcessor(tokenizer=A ,image_processor=A ) __A = "lower newer" __A = processor(text=A ) __A = tokenizer(A ,return_token_type_ids=A ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] ,encoded_processor[key] ) def UpperCamelCase_ ( self : int ): __A = self.get_image_processor() __A = self.get_tokenizer() __A = BlipaProcessor(tokenizer=A ,image_processor=A ) __A = "lower newer" __A = self.prepare_image_inputs() __A = processor(text=A ,images=A ) self.assertListEqual(list(inputs.keys() ) ,["pixel_values", "input_ids", "attention_mask"] ) # test if it raises when no input is passed with pytest.raises(A ): processor() def UpperCamelCase_ ( self : Optional[Any] ): __A = self.get_image_processor() __A = self.get_tokenizer() __A = BlipaProcessor(tokenizer=A ,image_processor=A ) __A = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __A = processor.batch_decode(A ) __A = tokenizer.batch_decode(A ) self.assertListEqual(A ,A ) def UpperCamelCase_ ( self : Optional[Any] ): __A = self.get_image_processor() __A = self.get_tokenizer() __A = BlipaProcessor(tokenizer=A ,image_processor=A ) __A = "lower newer" __A = self.prepare_image_inputs() __A = processor(text=A ,images=A ) # For now the processor supports only ['pixel_values', 'input_ids', 'attention_mask'] self.assertListEqual(list(inputs.keys() ) ,["pixel_values", "input_ids", "attention_mask"] )
55
1
import math def UpperCAmelCase ( a_ ) -> bool: """simple docstring""" assert isinstance(a_ , a_ ) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or not number % 2: # Negatives, 0, 1 and all even numbers are not primes return False __A = range(3 , int(math.sqrt(a_ ) + 1 ) , 2 ) return not any(not number % i for i in odd_numbers ) def UpperCAmelCase ( a_ , a_=1 , **a_ ) -> Union[str, Any]: """simple docstring""" __A = factor * value __A = value while not is_prime(a_ ): value += 1 if not ("desc" in kwargs and kwargs["desc"] is True) else -1 if value == first_value_val: return next_prime(value + 1 , **a_ ) return value
55
import logging import torch from accelerate import Accelerator from arguments import EvaluationArguments from datasets import load_dataset from torch.utils.data import IterableDataset from torch.utils.data.dataloader import DataLoader from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, set_seed class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self : int ,A : Any ,A : List[str] ,A : Union[str, Any]=10_24 ,A : int=10_24 ,A : Optional[Any]=3.6 ): __A = tokenizer __A = tokenizer.bos_token_id __A = dataset __A = seq_length __A = seq_length * chars_per_token * num_of_sequences def __iter__( self : List[Any] ): __A = iter(self.dataset ) __A = True while more_examples: __A , __A = [], 0 while True: if buffer_len >= self.input_characters: break try: buffer.append(next(A )["content"] ) buffer_len += len(buffer[-1] ) except StopIteration: __A = False break __A = tokenizer(A ,truncation=A )["input_ids"] __A = [] for tokenized_input in tokenized_inputs: all_token_ids.extend(tokenized_input + [self.concat_token_id] ) for i in range(0 ,len(A ) ,self.seq_length ): __A = all_token_ids[i : i + self.seq_length] if len(A ) == self.seq_length: yield torch.tensor(A ) def UpperCAmelCase ( a_ ) -> Optional[int]: """simple docstring""" __A = {"streaming": True} __A = load_dataset(args.dataset_name , split="train" , **a_ ) __A = ConstantLengthDataset(a_ , a_ , seq_length=args.seq_length ) __A = DataLoader(a_ , batch_size=args.batch_size ) return eval_dataloader def UpperCAmelCase ( a_ ) -> Union[str, Any]: """simple docstring""" model.eval() __A = [] for step, batch in enumerate(a_ ): with torch.no_grad(): __A = model(a_ , labels=a_ ) __A = outputs.loss.repeat(args.batch_size ) losses.append(accelerator.gather(a_ ) ) if args.max_eval_steps > 0 and step >= args.max_eval_steps: break __A = torch.mean(torch.cat(a_ ) ) try: __A = torch.exp(a_ ) except OverflowError: __A = float("inf" ) return loss.item(), perplexity.item() # Setup Accelerator SCREAMING_SNAKE_CASE :Optional[int] = Accelerator() # Parse configuration SCREAMING_SNAKE_CASE :str = HfArgumentParser(EvaluationArguments) SCREAMING_SNAKE_CASE :int = parser.parse_args() set_seed(args.seed) # Logging SCREAMING_SNAKE_CASE :Dict = logging.getLogger(__name__) logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO ) # Load model and tokenizer SCREAMING_SNAKE_CASE :List[Any] = AutoModelForCausalLM.from_pretrained(args.model_ckpt) SCREAMING_SNAKE_CASE :int = AutoTokenizer.from_pretrained(args.model_ckpt) # Load dataset and dataloader SCREAMING_SNAKE_CASE :List[str] = create_dataloader(args) # Prepare everything with our `accelerator`. SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE :List[Any] = accelerator.prepare(model, eval_dataloader) # Evaluate and save the last checkpoint logger.info('Evaluating and saving model after training') SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE :List[Any] = evaluate(args) logger.info(f'''loss/eval: {eval_loss}, perplexity: {perplexity}''')
55
1
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 :Union[str, 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 UpperCAmelCase ( a_ , a_ , a_=8 ) -> List[str]: """simple docstring""" __A = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 __A = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor def UpperCAmelCase ( a_ , a_=5_1_2 , a_=5_1_2 ) -> List[Any]: """simple docstring""" __A = pil_image.resize((w, h) , resample=Image.BICUBIC , reducing_gap=1 ) __A = np.array(pil_image.convert("RGB" ) ) __A = arr.astype(np.floataa ) / 127.5 - 1 __A = np.transpose(a_ , [2, 0, 1] ) __A = torch.from_numpy(a_ ).unsqueeze(0 ) return image class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self : Dict ,A : UNetaDConditionModel ,A : DDPMScheduler ,A : VQModel ,): super().__init__() self.register_modules( unet=A ,scheduler=A ,movq=A ,) __A = 2 ** (len(self.movq.config.block_out_channels ) - 1) def UpperCamelCase_ ( self : List[str] ,A : Optional[Any] ,A : Dict ,A : Union[str, Any] ): # get the original timestep using init_timestep __A = min(int(num_inference_steps * strength ) ,A ) __A = max(num_inference_steps - init_timestep ,0 ) __A = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def UpperCamelCase_ ( self : List[Any] ,A : Tuple ,A : Optional[int] ,A : List[str] ,A : Dict ,A : Union[str, Any] ,A : Tuple ,A : Tuple=None ): if not isinstance(A ,(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(A )}''' ) __A = image.to(device=A ,dtype=A ) __A = batch_size * num_images_per_prompt if image.shape[1] == 4: __A = image else: if isinstance(A ,A ) and len(A ) != batch_size: raise ValueError( f'''You have passed a list of generators of length {len(A )}, but requested an effective batch''' f''' size of {batch_size}. Make sure the batch size matches the length of the generators.''' ) elif isinstance(A ,A ): __A = [ self.movq.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(A ) ] __A = torch.cat(A ,dim=0 ) else: __A = self.movq.encode(A ).latent_dist.sample(A ) __A = self.movq.config.scaling_factor * init_latents __A = torch.cat([init_latents] ,dim=0 ) __A = init_latents.shape __A = randn_tensor(A ,generator=A ,device=A ,dtype=A ) # get latents __A = self.scheduler.add_noise(A ,A ,A ) __A = init_latents return latents def UpperCamelCase_ ( self : Optional[int] ,A : Union[str, Any]=0 ): if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("Please install accelerate via `pip install accelerate`" ) __A = torch.device(f'''cuda:{gpu_id}''' ) __A = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(A ,A ) def UpperCamelCase_ ( self : Dict ,A : List[Any]=0 ): if is_accelerate_available() and is_accelerate_version(">=" ,"0.17.0.dev0" ): from accelerate import cpu_offload_with_hook else: raise ImportError("`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher." ) __A = torch.device(f'''cuda:{gpu_id}''' ) if self.device.type != "cpu": self.to("cpu" ,silence_dtype_warnings=A ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) __A = None for cpu_offloaded_model in [self.unet, self.movq]: __A , __A = cpu_offload_with_hook(A ,A ,prev_module_hook=A ) # We'll offload the last model manually. __A = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def UpperCamelCase_ ( self : Optional[Any] ): if not hasattr(self.unet ,"_hf_hook" ): return self.device for module in self.unet.modules(): if ( hasattr(A ,"_hf_hook" ) and hasattr(module._hf_hook ,"execution_device" ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(A ) def __call__( self : Tuple ,A : Union[torch.FloatTensor, List[torch.FloatTensor]] ,A : Union[torch.FloatTensor, PIL.Image.Image, List[torch.FloatTensor], List[PIL.Image.Image]] ,A : Union[torch.FloatTensor, List[torch.FloatTensor]] ,A : int = 5_12 ,A : int = 5_12 ,A : int = 1_00 ,A : float = 4.0 ,A : float = 0.3 ,A : int = 1 ,A : Optional[Union[torch.Generator, List[torch.Generator]]] = None ,A : Optional[str] = "pil" ,A : bool = True ,): __A = self._execution_device __A = guidance_scale > 1.0 if isinstance(A ,A ): __A = torch.cat(A ,dim=0 ) __A = image_embeds.shape[0] if isinstance(A ,A ): __A = torch.cat(A ,dim=0 ) if do_classifier_free_guidance: __A = image_embeds.repeat_interleave(A ,dim=0 ) __A = negative_image_embeds.repeat_interleave(A ,dim=0 ) __A = torch.cat([negative_image_embeds, image_embeds] ,dim=0 ).to(dtype=self.unet.dtype ,device=A ) if not isinstance(A ,A ): __A = [image] if not all(isinstance(A ,(PIL.Image.Image, torch.Tensor) ) for i in image ): raise ValueError( f'''Input is in incorrect format: {[type(A ) for i in image]}. Currently, we only support PIL image and pytorch tensor''' ) __A = torch.cat([prepare_image(A ,A ,A ) for i in image] ,dim=0 ) __A = image.to(dtype=image_embeds.dtype ,device=A ) __A = self.movq.encode(A )["latents"] __A = latents.repeat_interleave(A ,dim=0 ) self.scheduler.set_timesteps(A ,device=A ) __A , __A = self.get_timesteps(A ,A ,A ) __A = timesteps[:1].repeat(batch_size * num_images_per_prompt ) __A , __A = downscale_height_and_width(A ,A ,self.movq_scale_factor ) __A = self.prepare_latents( A ,A ,A ,A ,image_embeds.dtype ,A ,A ) for i, t in enumerate(self.progress_bar(A ) ): # expand the latents if we are doing classifier free guidance __A = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents __A = {"image_embeds": image_embeds} __A = self.unet( sample=A ,timestep=A ,encoder_hidden_states=A ,added_cond_kwargs=A ,return_dict=A ,)[0] if do_classifier_free_guidance: __A , __A = noise_pred.split(latents.shape[1] ,dim=1 ) __A , __A = noise_pred.chunk(2 ) __A , __A = variance_pred.chunk(2 ) __A = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) __A = torch.cat([noise_pred, variance_pred_text] ,dim=1 ) if not ( hasattr(self.scheduler.config ,"variance_type" ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): __A , __A = noise_pred.split(latents.shape[1] ,dim=1 ) # compute the previous noisy sample x_t -> x_t-1 __A = self.scheduler.step( A ,A ,A ,generator=A ,)[0] # post-processing __A = self.movq.decode(A ,force_not_quantize=A )["sample"] if output_type not in ["pt", "np", "pil"]: raise ValueError(f'''Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}''' ) if output_type in ["np", "pil"]: __A = image * 0.5 + 0.5 __A = image.clamp(0 ,1 ) __A = image.cpu().permute(0 ,2 ,3 ,1 ).float().numpy() if output_type == "pil": __A = self.numpy_to_pil(A ) if not return_dict: return (image,) return ImagePipelineOutput(images=A )
55
import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = LayoutLMTokenizer snake_case_ = LayoutLMTokenizerFast snake_case_ = True snake_case_ = True def UpperCamelCase_ ( self : Any ): super().setUp() __A = [ "[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest", ] __A = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file ,"w" ,encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) def UpperCamelCase_ ( self : Tuple ,**A : int ): return LayoutLMTokenizer.from_pretrained(self.tmpdirname ,**A ) def UpperCamelCase_ ( self : Optional[Any] ,A : Any ): __A = "UNwant\u00E9d,running" __A = "unwanted, running" return input_text, output_text def UpperCamelCase_ ( self : str ): __A = self.tokenizer_class(self.vocab_file ) __A = tokenizer.tokenize("UNwant\u00E9d,running" ) self.assertListEqual(A ,["un", "##want", "##ed", ",", "runn", "##ing"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(A ) ,[7, 4, 5, 10, 8, 9] ) def UpperCamelCase_ ( self : int ): pass
55
1
from json import JSONDecodeError # Workaround for requests.exceptions.JSONDecodeError import requests def UpperCAmelCase ( a_ = "isbn/0140328726" ) -> dict: """simple docstring""" __A = olid.strip().strip("/" ) # Remove leading/trailing whitespace & slashes if new_olid.count("/" ) != 1: __A = F'''{olid} is not a valid Open Library olid''' raise ValueError(a_ ) return requests.get(F'''https://openlibrary.org/{new_olid}.json''' ).json() def UpperCAmelCase ( a_ ) -> dict: """simple docstring""" __A = { "title": "Title", "publish_date": "Publish date", "authors": "Authors", "number_of_pages": "Number of pages:", "first_sentence": "First sentence", "isbn_10": "ISBN (10)", "isbn_13": "ISBN (13)", } __A = {better_key: ol_book_data[key] for key, better_key in desired_keys.items()} __A = [ get_openlibrary_data(author["key"] )["name"] for author in data["Authors"] ] __A = data["First sentence"]["value"] for key, value in data.items(): if isinstance(a_ , a_ ): __A = ", ".join(a_ ) return data if __name__ == "__main__": import doctest doctest.testmod() while True: SCREAMING_SNAKE_CASE :int = input('\nEnter the ISBN code to search (or \'quit\' to stop): ').strip() if isbn.lower() in ("", "q", "quit", "exit", "stop"): break if len(isbn) not in (10, 13) or not isbn.isdigit(): print(f'''Sorry, {isbn} is not a valid ISBN. Please, input a valid ISBN.''') continue print(f'''\nSearching Open Library for ISBN: {isbn}...\n''') try: SCREAMING_SNAKE_CASE :Any = summarize_book(get_openlibrary_data(f'''isbn/{isbn}''')) print('\n'.join(f'''{key}: {value}''' for key, value in book_summary.items())) except JSONDecodeError: # Workaround for requests.exceptions.RequestException: print(f'''Sorry, there are no results for ISBN: {isbn}.''')
55
SCREAMING_SNAKE_CASE :int = {str(digit): digit**5 for digit in range(10)} def UpperCAmelCase ( a_ ) -> int: """simple docstring""" return sum(DIGITS_FIFTH_POWER[digit] for digit in str(a_ ) ) def UpperCAmelCase ( ) -> int: """simple docstring""" return sum( number for number in range(1_0_0_0 , 1_0_0_0_0_0_0 ) if number == digits_fifth_powers_sum(a_ ) ) if __name__ == "__main__": print(solution())
55
1
import argparse import json import os from collections import OrderedDict import numpy as np import tensorflow as tf import torch def UpperCAmelCase ( a_ ) -> List[Any]: """simple docstring""" __A = os.path.join(args.tf_model_dir , "parameters.json" ) __A = json.loads(open(a_ ).read() ) if not params: raise ValueError( F'''It seems that the json file at {parameter_file} is empty. Make sure you have a correct json file.''' ) if not args.output.endswith(".pt" ): __A = args.output + ".pt" __A = OrderedDict() with tf.device("/CPU:0" ): __A = tf.train.load_checkpoint(args.tf_model_dir ) __A = reader.get_variable_to_shape_map() for key_name in shapes.keys(): __A = reader.get_tensor(a_ ).astype(np.floataa ) if key_name.endswith("/adam_m" ) or key_name.endswith("/adam_v" ): continue if key_name.startswith("pasts/" ): if key_name.startswith("pasts/mlp" ): __A = int(key_name[9] ) elif key_name.startswith("pasts/out" ): __A = 8 __A = "model.sqout.%d.weight" % (player * 2) # enter to nn.Sequencial with Tanh, so 2 at a time __A = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix __A = torch.tensor(a_ ) elif key_name.startswith("model/moe" ): __A = int(key_name[9:].split("/" )[0] ) if key_name.endswith("/switch_gating/kernel" ): __A = "model.blocks.%d.feed_forward.mlp.router.classifier.weight" % player __A = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix __A = torch.tensor(a_ ) elif key_name.endswith("/softmlp/kernel" ): __A = "model.blocks.%d.feed_forward.soft_bypass_mlp.weight" % player __A = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix __A = torch.tensor(a_ ) elif key_name.endswith("/wo/kernel" ) or key_name.endswith("/wi/kernel" ): __A = key_name[-9:-7] for i in range(1_6 ): __A = "model.blocks.%d.feed_forward.mlp.experts.expert_%d.%s.weight" % (player, i, nlayer) __A = ( vnp[i].transpose([1, 0] ).copy() ) # In Mesh-Tensorflow, it is one array, so it is divided __A = torch.tensor(a_ ) elif key_name.startswith("model/mlp" ): __A = int(key_name[9:].split("/" )[0] ) if key_name.endswith("/p1/kernel" ): __A = "model.blocks.%d.feed_forward.mlp.wi.weight" % player __A = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix __A = torch.tensor(a_ ) elif key_name.endswith("/p1/bias" ): __A = "model.blocks.%d.feed_forward.mlp.wi.bias" % player __A = vnp.copy() # same because it is one dimensional __A = torch.tensor(a_ ) elif key_name.endswith("/p2/kernel" ): __A = "model.blocks.%d.feed_forward.mlp.wo.weight" % player __A = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix __A = torch.tensor(a_ ) elif key_name.endswith("/p2/bias" ): __A = "model.blocks.%d.feed_forward.mlp.wo.bias" % player __A = vnp.copy() # same because it is one dimensional __A = torch.tensor(a_ ) elif key_name.startswith("model/ln" ): __A = int(key_name[8:].split("/" )[0] ) if key_name.endswith("/b" ): __A = "model.blocks.%d.feed_forward.norm.bias" % player __A = vnp.copy() # same because it is one dimensional __A = torch.tensor(a_ ) elif key_name.endswith("/g" ): __A = "model.blocks.%d.feed_forward.norm.weight" % player __A = vnp.copy() # same because it is one dimensional __A = torch.tensor(a_ ) elif key_name.startswith("model/att" ): __A = int(key_name[9:].split("/" )[0] ) if key_name.endswith("/qkv/kernel" ): __A = vnp.copy() # Compute same dimension as Mesh-tensorflow using einsum __A = state[:, 0, :, :] __A = state[:, 1, :, :] __A = state[:, 2, :, :] __A = ( state_q.reshape([state_q.shape[0], state_q.shape[1] * state_q.shape[2]] ) .transpose([1, 0] ) .copy() ) # Mesh-Tensorflow is a diagonal matrix __A = ( state_k.reshape([state_k.shape[0], state_k.shape[1] * state_k.shape[2]] ) .transpose([1, 0] ) .copy() ) # Mesh-Tensorflow is a diagonal matrix __A = ( state_v.reshape([state_v.shape[0], state_v.shape[1] * state_v.shape[2]] ) .transpose([1, 0] ) .copy() ) # Mesh-Tensorflow is a diagonal matrix __A = "model.blocks.%d.self_attn.self_attn.q_proj.weight" % player __A = torch.tensor(a_ ) __A = "model.blocks.%d.self_attn.self_attn.k_proj.weight" % player __A = torch.tensor(a_ ) __A = "model.blocks.%d.self_attn.self_attn.v_proj.weight" % player __A = torch.tensor(a_ ) elif key_name.endswith("/o/kernel" ): __A = "model.blocks.%d.self_attn.self_attn.out_proj.weight" % player __A = ( vnp.reshape([vnp.shape[0] * vnp.shape[1], vnp.shape[2]] ).transpose([1, 0] ).copy() ) # Mesh-Tensorflow is a diagonal matrix __A = torch.tensor(a_ ) elif key_name.startswith("model/an" ): __A = int(key_name[8:].split("/" )[0] ) if key_name.endswith("/b" ): __A = "model.blocks.%d.self_attn.norm.bias" % player __A = vnp.copy() # same because it is one dimensional __A = torch.tensor(a_ ) elif key_name.endswith("/g" ): __A = "model.blocks.%d.self_attn.norm.weight" % player __A = vnp.copy() # same because it is one dimensional __A = torch.tensor(a_ ) elif ( key_name.startswith("model/wte" ) or key_name.startswith("model/wpe" ) or key_name.startswith("model/ete" ) ): __A = {"wte": "embed_tokens", "wpe": "position_embeddings", "ete": "extra_position_embeddings"}[ key_name[-3:] ] __A = "model.%s.weight" % nlayer __A = vnp.copy() # same in embedded __A = torch.tensor(a_ ) if key_name.startswith("model/wte" ): __A = "lm_head.weight" __A = vnp.copy() # same in embedded __A = torch.tensor(a_ ) elif key_name.startswith("model/wob" ): __A = "final_logits_bias" __A = vnp.copy() # same in embedded __A = state.reshape((1, -1) ) __A = torch.tensor(a_ ) elif key_name == "model/dense/kernel": __A = "model.last_project.weight" __A = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix __A = torch.tensor(a_ ) elif key_name == "model/dense_1/bias": __A = "model.last_project.bias" __A = vnp.copy() # same because it is one dimensional __A = torch.tensor(a_ ) torch.save(a_ , args.output ) if __name__ == "__main__": SCREAMING_SNAKE_CASE :Optional[int] = argparse.ArgumentParser( description='model converter.', formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument('--tf_model_dir', metavar='PATH', type=str, required=True, help='import model') parser.add_argument('--output', metavar='PATH', type=str, required=True, help='output model') SCREAMING_SNAKE_CASE :Optional[Any] = parser.parse_args() convert_tf_gptsan_to_pt(args)
55
import inspect import unittest from transformers import MobileNetVaConfig 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 MobileNetVaForImageClassification, MobileNetVaModel from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileNetVaImageProcessor class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def UpperCamelCase_ ( self : Any ): __A = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(A ,"tf_padding" ) ) self.parent.assertTrue(hasattr(A ,"depth_multiplier" ) ) class UpperCAmelCase : '''simple docstring''' def __init__( self : Optional[Any] ,A : int ,A : List[Any]=13 ,A : int=3 ,A : Optional[Any]=32 ,A : Union[str, Any]=0.25 ,A : Tuple=8 ,A : Optional[int]=True ,A : Union[str, Any]=10_24 ,A : Any=32 ,A : Optional[int]="relu6" ,A : int=0.1 ,A : Optional[Any]=0.02 ,A : Optional[Any]=True ,A : List[str]=True ,A : str=10 ,A : str=None ,): __A = parent __A = batch_size __A = num_channels __A = image_size __A = depth_multiplier __A = min_depth __A = tf_padding __A = int(last_hidden_size * depth_multiplier ) __A = output_stride __A = hidden_act __A = classifier_dropout_prob __A = use_labels __A = is_training __A = num_labels __A = initializer_range __A = scope def UpperCamelCase_ ( self : Optional[int] ): __A = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __A = None __A = None if self.use_labels: __A = ids_tensor([self.batch_size] ,self.num_labels ) __A = ids_tensor([self.batch_size, self.image_size, self.image_size] ,self.num_labels ) __A = self.get_config() return config, pixel_values, labels, pixel_labels def UpperCamelCase_ ( self : Any ): return MobileNetVaConfig( num_channels=self.num_channels ,image_size=self.image_size ,depth_multiplier=self.depth_multiplier ,min_depth=self.min_depth ,tf_padding=self.tf_padding ,hidden_act=self.hidden_act ,classifier_dropout_prob=self.classifier_dropout_prob ,initializer_range=self.initializer_range ,) def UpperCamelCase_ ( self : Optional[int] ,A : str ,A : Tuple ,A : Optional[int] ,A : List[str] ): __A = MobileNetVaModel(config=A ) model.to(A ) model.eval() __A = model(A ) self.parent.assertEqual( result.last_hidden_state.shape ,( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) ,) def UpperCamelCase_ ( self : List[Any] ,A : Union[str, Any] ,A : List[Any] ,A : int ,A : Union[str, Any] ): __A = self.num_labels __A = MobileNetVaForImageClassification(A ) model.to(A ) model.eval() __A = model(A ,labels=A ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def UpperCamelCase_ ( self : Tuple ): __A = self.prepare_config_and_inputs() __A , __A , __A , __A = config_and_inputs __A = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = (MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else () snake_case_ = ( {"feature-extraction": MobileNetVaModel, "image-classification": MobileNetVaForImageClassification} if is_torch_available() else {} ) snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = False def UpperCamelCase_ ( self : Any ): __A = MobileNetVaModelTester(self ) __A = MobileNetVaConfigTester(self ,config_class=A ,has_text_modality=A ) def UpperCamelCase_ ( self : str ): self.config_tester.run_common_tests() @unittest.skip(reason="MobileNetV1 does not use inputs_embeds" ) def UpperCamelCase_ ( self : Union[str, Any] ): pass @unittest.skip(reason="MobileNetV1 does not support input and output embeddings" ) def UpperCamelCase_ ( self : Tuple ): pass @unittest.skip(reason="MobileNetV1 does not output attentions" ) def UpperCamelCase_ ( self : Any ): pass def UpperCamelCase_ ( self : Optional[int] ): __A , __A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __A = model_class(A ) __A = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __A = [*signature.parameters.keys()] __A = ["pixel_values"] self.assertListEqual(arg_names[:1] ,A ) def UpperCamelCase_ ( self : List[Any] ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A ) def UpperCamelCase_ ( self : Optional[int] ): def check_hidden_states_output(A : List[Any] ,A : List[Any] ,A : Optional[int] ): __A = model_class(A ) model.to(A ) model.eval() with torch.no_grad(): __A = model(**self._prepare_for_class(A ,A ) ) __A = outputs.hidden_states __A = 26 self.assertEqual(len(A ) ,A ) __A , __A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __A = True check_hidden_states_output(A ,A ,A ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __A = True check_hidden_states_output(A ,A ,A ) def UpperCamelCase_ ( self : Tuple ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*A ) @slow def UpperCamelCase_ ( self : Union[str, Any] ): for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __A = MobileNetVaModel.from_pretrained(A ) self.assertIsNotNone(A ) def UpperCAmelCase ( ) -> str: """simple docstring""" __A = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def UpperCamelCase_ ( self : List[str] ): return ( MobileNetVaImageProcessor.from_pretrained("google/mobilenet_v1_1.0_224" ) if is_vision_available() else None ) @slow def UpperCamelCase_ ( self : Optional[Any] ): __A = MobileNetVaForImageClassification.from_pretrained("google/mobilenet_v1_1.0_224" ).to(A ) __A = self.default_image_processor __A = prepare_img() __A = image_processor(images=A ,return_tensors="pt" ).to(A ) # forward pass with torch.no_grad(): __A = model(**A ) # verify the logits __A = torch.Size((1, 10_01) ) self.assertEqual(outputs.logits.shape ,A ) __A = torch.tensor([-4.17_39, -1.12_33, 3.12_05] ).to(A ) self.assertTrue(torch.allclose(outputs.logits[0, :3] ,A ,atol=1E-4 ) )
55
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) SCREAMING_SNAKE_CASE :str = { 'configuration_swiftformer': [ 'SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SwiftFormerConfig', 'SwiftFormerOnnxConfig', ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE :Any = [ 'SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'SwiftFormerForImageClassification', 'SwiftFormerModel', 'SwiftFormerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_swiftformer import ( SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, SwiftFormerConfig, SwiftFormerOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swiftformer import ( SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, SwiftFormerForImageClassification, SwiftFormerModel, SwiftFormerPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE :Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
55
import copy import unittest from transformers.models.auto import get_values from transformers.testing_utils import require_torch, 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, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_MULTIPLE_CHOICE_MAPPING, MODEL_FOR_QUESTION_ANSWERING_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaModel, ) from transformers.models.layoutlmva.modeling_layoutlmva import LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class UpperCAmelCase : '''simple docstring''' def __init__( self : str ,A : int ,A : int=2 ,A : Optional[Any]=3 ,A : Dict=4 ,A : Optional[int]=2 ,A : Union[str, Any]=7 ,A : List[str]=True ,A : Union[str, Any]=True ,A : Optional[int]=True ,A : Optional[int]=True ,A : Tuple=99 ,A : Optional[int]=36 ,A : Dict=3 ,A : str=4 ,A : Optional[Any]=37 ,A : Dict="gelu" ,A : Dict=0.1 ,A : Union[str, Any]=0.1 ,A : Union[str, Any]=5_12 ,A : Any=16 ,A : Union[str, Any]=2 ,A : List[Any]=0.02 ,A : List[Any]=6 ,A : Optional[int]=6 ,A : List[Any]=3 ,A : Union[str, Any]=4 ,A : Tuple=None ,A : List[str]=10_00 ,): __A = parent __A = batch_size __A = num_channels __A = image_size __A = patch_size __A = text_seq_length __A = is_training __A = use_input_mask __A = use_token_type_ids __A = use_labels __A = vocab_size __A = hidden_size __A = num_hidden_layers __A = num_attention_heads __A = intermediate_size __A = hidden_act __A = hidden_dropout_prob __A = attention_probs_dropout_prob __A = max_position_embeddings __A = type_vocab_size __A = type_sequence_label_size __A = initializer_range __A = coordinate_size __A = shape_size __A = num_labels __A = num_choices __A = scope __A = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) __A = text_seq_length __A = (image_size // patch_size) ** 2 + 1 __A = self.text_seq_length + self.image_seq_length def UpperCamelCase_ ( self : int ): __A = ids_tensor([self.batch_size, self.text_seq_length] ,self.vocab_size ) __A = ids_tensor([self.batch_size, self.text_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]: __A = bbox[i, j, 3] __A = bbox[i, j, 1] __A = t if bbox[i, j, 2] < bbox[i, j, 0]: __A = bbox[i, j, 2] __A = bbox[i, j, 0] __A = t __A = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __A = None if self.use_input_mask: __A = random_attention_mask([self.batch_size, self.text_seq_length] ) __A = None if self.use_token_type_ids: __A = ids_tensor([self.batch_size, self.text_seq_length] ,self.type_vocab_size ) __A = None __A = None if self.use_labels: __A = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) __A = ids_tensor([self.batch_size, self.text_seq_length] ,self.num_labels ) __A = LayoutLMvaConfig( 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 ,coordinate_size=self.coordinate_size ,shape_size=self.shape_size ,input_size=self.image_size ,patch_size=self.patch_size ,) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def UpperCamelCase_ ( self : Optional[int] ,A : List[str] ,A : Any ,A : Dict ,A : List[Any] ,A : Optional[int] ,A : Any ,A : Dict ,A : List[Any] ): __A = LayoutLMvaModel(config=A ) model.to(A ) model.eval() # text + image __A = model(A ,pixel_values=A ) __A = model( A ,bbox=A ,pixel_values=A ,attention_mask=A ,token_type_ids=A ) __A = model(A ,bbox=A ,pixel_values=A ,token_type_ids=A ) __A = model(A ,bbox=A ,pixel_values=A ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) # text only __A = model(A ) self.parent.assertEqual( result.last_hidden_state.shape ,(self.batch_size, self.text_seq_length, self.hidden_size) ) # image only __A = model(pixel_values=A ) self.parent.assertEqual( result.last_hidden_state.shape ,(self.batch_size, self.image_seq_length, self.hidden_size) ) def UpperCamelCase_ ( self : Optional[int] ,A : Dict ,A : List[str] ,A : Any ,A : List[Any] ,A : Any ,A : Any ,A : Dict ,A : Optional[Any] ): __A = self.num_labels __A = LayoutLMvaForSequenceClassification(A ) model.to(A ) model.eval() __A = model( A ,bbox=A ,pixel_values=A ,attention_mask=A ,token_type_ids=A ,labels=A ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def UpperCamelCase_ ( self : str ,A : Optional[Any] ,A : Dict ,A : str ,A : Tuple ,A : Union[str, Any] ,A : List[Any] ,A : Any ,A : Union[str, Any] ): __A = self.num_labels __A = LayoutLMvaForTokenClassification(config=A ) model.to(A ) model.eval() __A = model( A ,bbox=A ,pixel_values=A ,attention_mask=A ,token_type_ids=A ,labels=A ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.text_seq_length, self.num_labels) ) def UpperCamelCase_ ( self : Optional[int] ,A : Optional[Any] ,A : int ,A : str ,A : List[str] ,A : int ,A : List[str] ,A : List[str] ,A : Dict ): __A = LayoutLMvaForQuestionAnswering(config=A ) model.to(A ) model.eval() __A = model( A ,bbox=A ,pixel_values=A ,attention_mask=A ,token_type_ids=A ,start_positions=A ,end_positions=A ,) self.parent.assertEqual(result.start_logits.shape ,(self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape ,(self.batch_size, self.seq_length) ) def UpperCamelCase_ ( self : str ): __A = self.prepare_config_and_inputs() ( ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ) = config_and_inputs __A = { "input_ids": input_ids, "bbox": bbox, "pixel_values": pixel_values, "token_type_ids": token_type_ids, "attention_mask": input_mask, } return config, inputs_dict @require_torch class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = ( ( LayoutLMvaModel, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaForQuestionAnswering, ) if is_torch_available() else () ) snake_case_ = ( {"document-question-answering": LayoutLMvaForQuestionAnswering, "feature-extraction": LayoutLMvaModel} if is_torch_available() else {} ) def UpperCamelCase_ ( self : str ,A : Any ,A : Any ,A : Tuple ,A : List[Any] ,A : Optional[Any] ): # `DocumentQuestionAnsweringPipeline` is expected to work with this model, but it combines the text and visual # embedding along the sequence dimension (dim 1), which causes an error during post-processing as `p_mask` has # the sequence dimension of the text embedding only. # (see the line `embedding_output = torch.cat([embedding_output, visual_embeddings], dim=1)`) return True def UpperCamelCase_ ( self : Union[str, Any] ): __A = LayoutLMvaModelTester(self ) __A = ConfigTester(self ,config_class=A ,hidden_size=37 ) def UpperCamelCase_ ( self : List[Any] ,A : int ,A : List[str] ,A : Dict=False ): __A = copy.deepcopy(A ) if model_class in get_values(A ): __A = { k: v.unsqueeze(1 ).expand(-1 ,self.model_tester.num_choices ,-1 ).contiguous() if isinstance(A ,torch.Tensor ) and v.ndim > 1 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(A ): __A = torch.ones(self.model_tester.batch_size ,dtype=torch.long ,device=A ) elif model_class in get_values(A ): __A = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=A ) __A = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=A ) elif model_class in [ *get_values(A ), ]: __A = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=A ) elif model_class in [ *get_values(A ), ]: __A = torch.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) ,dtype=torch.long ,device=A ,) return inputs_dict def UpperCamelCase_ ( self : List[Any] ): self.config_tester.run_common_tests() def UpperCamelCase_ ( self : Union[str, Any] ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A ) def UpperCamelCase_ ( self : str ): __A = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __A = type self.model_tester.create_and_check_model(*A ) def UpperCamelCase_ ( self : Optional[Any] ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*A ) def UpperCamelCase_ ( self : Optional[Any] ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*A ) def UpperCamelCase_ ( self : str ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*A ) @slow def UpperCamelCase_ ( self : Optional[int] ): for model_name in LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __A = LayoutLMvaModel.from_pretrained(A ) self.assertIsNotNone(A ) def UpperCAmelCase ( ) -> Dict: """simple docstring""" __A = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def UpperCamelCase_ ( self : Any ): return LayoutLMvaImageProcessor(apply_ocr=A ) if is_vision_available() else None @slow def UpperCamelCase_ ( self : Dict ): __A = LayoutLMvaModel.from_pretrained("microsoft/layoutlmv3-base" ).to(A ) __A = self.default_image_processor __A = prepare_img() __A = image_processor(images=A ,return_tensors="pt" ).pixel_values.to(A ) __A = torch.tensor([[1, 2]] ) __A = torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]] ).unsqueeze(0 ) # forward pass __A = model( input_ids=input_ids.to(A ) ,bbox=bbox.to(A ) ,pixel_values=pixel_values.to(A ) ,) # verify the logits __A = torch.Size((1, 1_99, 7_68) ) self.assertEqual(outputs.last_hidden_state.shape ,A ) __A = torch.tensor( [[-0.05_29, 0.36_18, 0.16_32], [-0.15_87, -0.16_67, -0.04_00], [-0.15_57, -0.16_71, -0.05_05]] ).to(A ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] ,A ,atol=1E-4 ) )
55
1
from .imports import is_rich_available if is_rich_available(): from rich.traceback import install install(show_locals=False) else: raise ModuleNotFoundError('To use the rich extension, install rich with `pip install rich`')
55
import unittest import numpy as np from datasets import load_dataset 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 BeitImageProcessor class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self : Any ,A : List[str] ,A : str=7 ,A : Optional[Any]=3 ,A : Any=18 ,A : int=30 ,A : int=4_00 ,A : List[str]=True ,A : Union[str, Any]=None ,A : Union[str, Any]=True ,A : Tuple=None ,A : Tuple=True ,A : Union[str, Any]=[0.5, 0.5, 0.5] ,A : str=[0.5, 0.5, 0.5] ,A : List[Any]=False ,): __A = size if size is not None else {"height": 20, "width": 20} __A = crop_size if crop_size is not None else {"height": 18, "width": 18} __A = parent __A = batch_size __A = num_channels __A = image_size __A = min_resolution __A = max_resolution __A = do_resize __A = size __A = do_center_crop __A = crop_size __A = do_normalize __A = image_mean __A = image_std __A = do_reduce_labels def UpperCamelCase_ ( self : List[str] ): return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_reduce_labels": self.do_reduce_labels, } def UpperCAmelCase ( ) -> int: """simple docstring""" __A = load_dataset("hf-internal-testing/fixtures_ade20k" , split="test" ) __A = Image.open(dataset[0]["file"] ) __A = Image.open(dataset[1]["file"] ) return image, map def UpperCAmelCase ( ) -> Optional[int]: """simple docstring""" __A = load_dataset("hf-internal-testing/fixtures_ade20k" , split="test" ) __A = Image.open(ds[0]["file"] ) __A = Image.open(ds[1]["file"] ) __A = Image.open(ds[2]["file"] ) __A = Image.open(ds[3]["file"] ) return [imagea, imagea], [mapa, mapa] @require_torch @require_vision class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = BeitImageProcessor if is_vision_available() else None def UpperCamelCase_ ( self : List[Any] ): __A = BeitImageProcessingTester(self ) @property def UpperCamelCase_ ( self : List[Any] ): return self.image_processor_tester.prepare_image_processor_dict() def UpperCamelCase_ ( self : int ): __A = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(A ,"do_resize" ) ) self.assertTrue(hasattr(A ,"size" ) ) self.assertTrue(hasattr(A ,"do_center_crop" ) ) self.assertTrue(hasattr(A ,"center_crop" ) ) self.assertTrue(hasattr(A ,"do_normalize" ) ) self.assertTrue(hasattr(A ,"image_mean" ) ) self.assertTrue(hasattr(A ,"image_std" ) ) def UpperCamelCase_ ( self : List[str] ): __A = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size ,{"height": 20, "width": 20} ) self.assertEqual(image_processor.crop_size ,{"height": 18, "width": 18} ) self.assertEqual(image_processor.do_reduce_labels ,A ) __A = self.image_processing_class.from_dict( self.image_processor_dict ,size=42 ,crop_size=84 ,reduce_labels=A ) self.assertEqual(image_processor.size ,{"height": 42, "width": 42} ) self.assertEqual(image_processor.crop_size ,{"height": 84, "width": 84} ) self.assertEqual(image_processor.do_reduce_labels ,A ) def UpperCamelCase_ ( self : List[Any] ): pass def UpperCamelCase_ ( self : Optional[int] ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __A = prepare_image_inputs(self.image_processor_tester ,equal_resolution=A ) for image in image_inputs: self.assertIsInstance(A ,Image.Image ) # Test not batched input __A = 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 __A = image_processing(A ,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 UpperCamelCase_ ( self : List[str] ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __A = prepare_image_inputs(self.image_processor_tester ,equal_resolution=A ,numpify=A ) for image in image_inputs: self.assertIsInstance(A ,np.ndarray ) # Test not batched input __A = 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 __A = image_processing(A ,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 UpperCamelCase_ ( self : int ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A = prepare_image_inputs(self.image_processor_tester ,equal_resolution=A ,torchify=A ) for image in image_inputs: self.assertIsInstance(A ,torch.Tensor ) # Test not batched input __A = 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 __A = image_processing(A ,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 UpperCamelCase_ ( self : str ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A = prepare_image_inputs(self.image_processor_tester ,equal_resolution=A ,torchify=A ) __A = [] for image in image_inputs: self.assertIsInstance(A ,torch.Tensor ) maps.append(torch.zeros(image.shape[-2:] ).long() ) # Test not batched input __A = image_processing(image_inputs[0] ,maps[0] ,return_tensors="pt" ) self.assertEqual( encoding["pixel_values"].shape ,( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,) self.assertEqual( encoding["labels"].shape ,( 1, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,) self.assertEqual(encoding["labels"].dtype ,torch.long ) self.assertTrue(encoding["labels"].min().item() >= 0 ) self.assertTrue(encoding["labels"].max().item() <= 2_55 ) # Test batched __A = image_processing(A ,A ,return_tensors="pt" ) self.assertEqual( encoding["pixel_values"].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"], ) ,) self.assertEqual( encoding["labels"].shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,) self.assertEqual(encoding["labels"].dtype ,torch.long ) self.assertTrue(encoding["labels"].min().item() >= 0 ) self.assertTrue(encoding["labels"].max().item() <= 2_55 ) # Test not batched input (PIL images) __A , __A = prepare_semantic_single_inputs() __A = image_processing(A ,A ,return_tensors="pt" ) self.assertEqual( encoding["pixel_values"].shape ,( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,) self.assertEqual( encoding["labels"].shape ,( 1, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,) self.assertEqual(encoding["labels"].dtype ,torch.long ) self.assertTrue(encoding["labels"].min().item() >= 0 ) self.assertTrue(encoding["labels"].max().item() <= 2_55 ) # Test batched input (PIL images) __A , __A = prepare_semantic_batch_inputs() __A = image_processing(A ,A ,return_tensors="pt" ) self.assertEqual( encoding["pixel_values"].shape ,( 2, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,) self.assertEqual( encoding["labels"].shape ,( 2, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,) self.assertEqual(encoding["labels"].dtype ,torch.long ) self.assertTrue(encoding["labels"].min().item() >= 0 ) self.assertTrue(encoding["labels"].max().item() <= 2_55 ) def UpperCamelCase_ ( self : Dict ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # ADE20k has 150 classes, and the background is included, so labels should be between 0 and 150 __A , __A = prepare_semantic_single_inputs() __A = image_processing(A ,A ,return_tensors="pt" ) self.assertTrue(encoding["labels"].min().item() >= 0 ) self.assertTrue(encoding["labels"].max().item() <= 1_50 ) __A = True __A = image_processing(A ,A ,return_tensors="pt" ) self.assertTrue(encoding["labels"].min().item() >= 0 ) self.assertTrue(encoding["labels"].max().item() <= 2_55 )
55
1
import uuid from typing import Any, Dict, List, Optional, Union from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf if is_torch_available(): import torch SCREAMING_SNAKE_CASE :List[str] = logging.get_logger(__name__) class UpperCAmelCase : '''simple docstring''' def __init__( self : Optional[int] ,A : str = None ,A : uuid.UUID = None ,A : List[Any]=None ,A : str=None ): if not conversation_id: __A = uuid.uuida() if past_user_inputs is None: __A = [] if generated_responses is None: __A = [] __A = conversation_id __A = past_user_inputs __A = generated_responses __A = text def __eq__( self : int ,A : str ): if not isinstance(A ,A ): return False if self.uuid == other.uuid: return True return ( self.new_user_input == other.new_user_input and self.past_user_inputs == other.past_user_inputs and self.generated_responses == other.generated_responses ) def UpperCamelCase_ ( self : Tuple ,A : str ,A : bool = False ): if self.new_user_input: if overwrite: logger.warning( f'''User input added while unprocessed input was existing: "{self.new_user_input}" was overwritten ''' f'''with: "{text}".''' ) __A = text else: logger.warning( f'''User input added while unprocessed input was existing: "{self.new_user_input}" new input ''' f'''ignored: "{text}". Set `overwrite` to True to overwrite unprocessed user input''' ) else: __A = text def UpperCamelCase_ ( self : List[str] ): if self.new_user_input: self.past_user_inputs.append(self.new_user_input ) __A = None def UpperCamelCase_ ( self : int ,A : str ): self.generated_responses.append(A ) def UpperCamelCase_ ( self : Dict ): for user_input, generated_response in zip(self.past_user_inputs ,self.generated_responses ): yield True, user_input yield False, generated_response if self.new_user_input: yield True, self.new_user_input def __repr__( self : Tuple ): __A = f'''Conversation id: {self.uuid} \n''' for is_user, text in self.iter_texts(): __A = "user" if is_user else "bot" output += f'''{name} >> {text} \n''' return output @add_end_docstrings( __SCREAMING_SNAKE_CASE , R"\n min_length_for_response (`int`, *optional*, defaults to 32):\n The minimum length (in number of tokens) for a response.\n minimum_tokens (`int`, *optional*, defaults to 10):\n The minimum length of tokens to leave for a response.\n " , ) class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self : List[str] ,*A : int ,**A : Any ): super().__init__(*A ,**A ) if self.tokenizer.pad_token_id is None: __A = self.tokenizer.eos_token def UpperCamelCase_ ( self : Dict ,A : Tuple=None ,A : int=None ,A : Union[str, Any]=None ,**A : Dict ): __A = {} __A = {} __A = {} if min_length_for_response is not None: __A = min_length_for_response if minimum_tokens is not None: __A = minimum_tokens if "max_length" in generate_kwargs: __A = generate_kwargs["max_length"] # self.max_length = generate_kwargs.get("max_length", self.model.config.max_length) if clean_up_tokenization_spaces is not None: __A = clean_up_tokenization_spaces if generate_kwargs: forward_params.update(A ) return preprocess_params, forward_params, postprocess_params def __call__( self : Optional[Any] ,A : Union[Conversation, List[Conversation]] ,A : Tuple=0 ,**A : int ): __A = super().__call__(A ,num_workers=A ,**A ) if isinstance(A ,A ) and len(A ) == 1: return outputs[0] return outputs def UpperCamelCase_ ( self : Tuple ,A : Conversation ,A : Union[str, Any]=32 ): if not isinstance(A ,A ): raise ValueError("ConversationalPipeline, expects Conversation as inputs" ) if conversation.new_user_input is None: raise ValueError( f'''Conversation with UUID {type(conversation.uuid )} does not contain new user input to process. ''' "Add user inputs with the conversation's `add_user_input` method" ) if hasattr(self.tokenizer ,"_build_conversation_input_ids" ): __A = self.tokenizer._build_conversation_input_ids(A ) else: # If the tokenizer cannot handle conversations, we default to only the old version __A = self._legacy_parse_and_tokenize(A ) if self.framework == "pt": __A = torch.LongTensor([input_ids] ) elif self.framework == "tf": __A = tf.constant([input_ids] ) return {"input_ids": input_ids, "conversation": conversation} def UpperCamelCase_ ( self : Tuple ,A : str ,A : Union[str, Any]=10 ,**A : Union[str, Any] ): __A = generate_kwargs.get("max_length" ,self.model.config.max_length ) __A = model_inputs["input_ids"].shape[1] if max_length - minimum_tokens < n: logger.warning(f'''Conversation input is to long ({n}), trimming it to ({max_length} - {minimum_tokens})''' ) __A = max_length - minimum_tokens __A = model_inputs["input_ids"][:, -trim:] if "attention_mask" in model_inputs: __A = model_inputs["attention_mask"][:, -trim:] __A = model_inputs.pop("conversation" ) __A = max_length __A = self.model.generate(**A ,**A ) if self.model.config.is_encoder_decoder: __A = 1 else: __A = n return {"output_ids": output_ids[:, start_position:], "conversation": conversation} def UpperCamelCase_ ( self : Any ,A : str ,A : Tuple=True ): __A = model_outputs["output_ids"] __A = self.tokenizer.decode( output_ids[0] ,skip_special_tokens=A ,clean_up_tokenization_spaces=A ,) __A = model_outputs["conversation"] conversation.mark_processed() conversation.append_response(A ) return conversation def UpperCamelCase_ ( self : Any ,A : Conversation ): __A = self.tokenizer.eos_token_id __A = [] for is_user, text in conversation.iter_texts(): if eos_token_id is not None: input_ids.extend(self.tokenizer.encode(A ,add_special_tokens=A ) + [eos_token_id] ) else: input_ids.extend(self.tokenizer.encode(A ,add_special_tokens=A ) ) if len(A ) > self.tokenizer.model_max_length: __A = input_ids[-self.tokenizer.model_max_length :] return input_ids
55
from numpy import exp, pi, sqrt def UpperCAmelCase ( a_ , a_ = 0.0 , a_ = 1.0 ) -> int: """simple docstring""" return 1 / sqrt(2 * pi * sigma**2 ) * exp(-((x - mu) ** 2) / (2 * sigma**2) ) if __name__ == "__main__": import doctest doctest.testmod()
55
1
from manim import * class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def UpperCamelCase_ ( self : str ): __A = Rectangle(height=0.5 ,width=0.5 ) __A = Rectangle(height=0.46 ,width=0.46 ).set_stroke(width=0 ) __A = [mem.copy() for i in range(6 )] __A = [mem.copy() for i in range(6 )] __A = VGroup(*A ).arrange(A ,buff=0 ) __A = VGroup(*A ).arrange(A ,buff=0 ) __A = VGroup(A ,A ).arrange(A ,buff=0 ) __A = Text("CPU" ,font_size=24 ) __A = Group(A ,A ).arrange(A ,buff=0.5 ,aligned_edge=A ) cpu.move_to([-2.5, -0.5, 0] ) self.add(A ) __A = [mem.copy() for i in range(1 )] __A = VGroup(*A ).arrange(A ,buff=0 ) __A = Text("GPU" ,font_size=24 ) __A = Group(A ,A ).arrange(A ,buff=0.5 ,aligned_edge=A ) gpu.align_to(A ,A ) gpu.set_x(gpu.get_x() - 1 ) self.add(A ) __A = [mem.copy() for i in range(6 )] __A = VGroup(*A ).arrange(A ,buff=0 ) __A = Text("Model" ,font_size=24 ) __A = Group(A ,A ).arrange(A ,buff=0.5 ,aligned_edge=A ) model.move_to([3, -1.0, 0] ) self.play( Create(A ,run_time=1 ) ,Create(A ,run_time=1 ) ,Create(A ,run_time=1 ) ,) __A = MarkupText( f'''First, an empty model skeleton is loaded\ninto <span fgcolor=\'{YELLOW}\'>memory</span> without using much RAM.''' ,font_size=24 ,) __A = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) __A = MarkupText( f'''<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model''' ,font_size=18 ,) key_text.move_to([-5, 2.4, 0] ) step_a.move_to([2, 2, 0] ) self.play(Write(A ,run_time=2.5 ) ,Write(A ) ,Write(A ) ) self.add(A ) __A = [] __A = [] __A = [] for i, rect in enumerate(A ): __A = Rectangle(height=0.46 ,width=0.46 ).set_stroke(width=0.0 ).set_fill(A ,opacity=0.7 ) cpu_target.move_to(A ) cpu_target.generate_target() __A = 0.46 / 4 __A = 0.46 / 3 if i == 0: cpu_target.target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) ,buff=0.02 ,direction=A ) cpu_target.target.set_x(cpu_target.target.get_x() + 0.1 ) elif i == 3: cpu_target.target.next_to(cpu_targs[0].target ,direction=A ,buff=0.0 ) else: cpu_target.target.next_to(cpu_targs[i - 1].target ,direction=A ,buff=0.0 ) cpu_targs.append(A ) first_animations.append(rect.animate(run_time=0.5 ).set_stroke(A ) ) second_animations.append(MoveToTarget(A ,run_time=1.5 ) ) self.play(*A ) self.play(*A ) self.wait()
55
import gc import unittest from diffusers import FlaxStableDiffusionInpaintPipeline from diffusers.utils import is_flax_available, load_image, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard @slow @require_flax class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase_ ( self : Tuple ): # clean up the VRAM after each test super().tearDown() gc.collect() def UpperCamelCase_ ( self : Optional[int] ): __A = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/sd2-inpaint/init_image.png" ) __A = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png" ) __A = "xvjiarui/stable-diffusion-2-inpainting" __A , __A = FlaxStableDiffusionInpaintPipeline.from_pretrained(A ,safety_checker=A ) __A = "Face of a yellow cat, high resolution, sitting on a park bench" __A = jax.random.PRNGKey(0 ) __A = 50 __A = jax.device_count() __A = num_samples * [prompt] __A = num_samples * [init_image] __A = num_samples * [mask_image] __A , __A , __A = pipeline.prepare_inputs(A ,A ,A ) # shard inputs and rng __A = replicate(A ) __A = jax.random.split(A ,jax.device_count() ) __A = shard(A ) __A = shard(A ) __A = shard(A ) __A = pipeline( A ,A ,A ,A ,A ,A ,jit=A ) __A = output.images.reshape(A ,5_12 ,5_12 ,3 ) __A = images[0, 2_53:2_56, 2_53:2_56, -1] __A = jnp.asarray(jax.device_get(image_slice.flatten() ) ) __A = jnp.array( [0.3_61_13_07, 0.37_64_97_36, 0.3_75_74_08, 0.38_21_39_53, 0.39_29_51_67, 0.3_84_16_31, 0.41_55_49_78, 0.4_13_74_75, 0.4_21_70_84] ) print(f'''output_slice: {output_slice}''' ) assert jnp.abs(output_slice - expected_slice ).max() < 1E-2
55
1
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 if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self : Any ,A : str ,A : List[str]=7 ,A : Optional[Any]=3 ,A : int=18 ,A : Union[str, Any]=30 ,A : Dict=4_00 ,A : int=True ,A : Tuple=None ,A : Optional[int]=True ,A : str=None ,A : Optional[Any]=True ,A : List[str]=[0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73] ,A : Dict=[0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11] ,A : Tuple=True ,): __A = size if size is not None else {"height": 2_24, "width": 2_24} __A = crop_size if crop_size is not None else {"height": 18, "width": 18} __A = parent __A = batch_size __A = num_channels __A = image_size __A = min_resolution __A = max_resolution __A = do_resize __A = size __A = do_center_crop __A = crop_size __A = do_normalize __A = image_mean __A = image_std __A = do_convert_rgb def UpperCamelCase_ ( self : str ): return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_convert_rgb": self.do_convert_rgb, } def UpperCamelCase_ ( self : str ,A : List[Any]=False ,A : int=False ,A : Optional[int]=False ): assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time" if equal_resolution: __A = [] for i in range(self.batch_size ): image_inputs.append( np.random.randint( 2_55 ,size=(self.num_channels, self.max_resolution, self.max_resolution) ,dtype=np.uinta ) ) else: __A = [] for i in range(self.batch_size ): __A , __A = np.random.choice(np.arange(self.min_resolution ,self.max_resolution ) ,2 ) image_inputs.append(np.random.randint(2_55 ,size=(self.num_channels, width, height) ,dtype=np.uinta ) ) if not numpify and not torchify: # PIL expects the channel dimension as last dimension __A = [Image.fromarray(np.moveaxis(A ,0 ,-1 ) ) for x in image_inputs] if torchify: __A = [torch.from_numpy(A ) for x in image_inputs] return image_inputs @require_torch @require_vision class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = ChineseCLIPImageProcessor if is_vision_available() else None def UpperCamelCase_ ( self : List[Any] ): __A = ChineseCLIPImageProcessingTester(self ,do_center_crop=A ) @property def UpperCamelCase_ ( self : Tuple ): return self.image_processor_tester.prepare_image_processor_dict() def UpperCamelCase_ ( self : Union[str, Any] ): __A = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(A ,"do_resize" ) ) self.assertTrue(hasattr(A ,"size" ) ) self.assertTrue(hasattr(A ,"do_center_crop" ) ) self.assertTrue(hasattr(A ,"center_crop" ) ) self.assertTrue(hasattr(A ,"do_normalize" ) ) self.assertTrue(hasattr(A ,"image_mean" ) ) self.assertTrue(hasattr(A ,"image_std" ) ) self.assertTrue(hasattr(A ,"do_convert_rgb" ) ) def UpperCamelCase_ ( self : Dict ): __A = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size ,{"height": 2_24, "width": 2_24} ) self.assertEqual(image_processor.crop_size ,{"height": 18, "width": 18} ) __A = 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 UpperCamelCase_ ( self : Dict ): pass def UpperCamelCase_ ( self : List[Any] ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __A = self.image_processor_tester.prepare_inputs(equal_resolution=A ) for image in image_inputs: self.assertIsInstance(A ,Image.Image ) # Test not batched input __A = 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 __A = image_processing(A ,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 UpperCamelCase_ ( self : Any ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __A = self.image_processor_tester.prepare_inputs(equal_resolution=A ,numpify=A ) for image in image_inputs: self.assertIsInstance(A ,np.ndarray ) # Test not batched input __A = 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 __A = image_processing(A ,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 UpperCamelCase_ ( self : Any ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A = self.image_processor_tester.prepare_inputs(equal_resolution=A ,torchify=A ) for image in image_inputs: self.assertIsInstance(A ,torch.Tensor ) # Test not batched input __A = 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 __A = image_processing(A ,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"], ) ,) @require_torch @require_vision class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = ChineseCLIPImageProcessor if is_vision_available() else None def UpperCamelCase_ ( self : List[Any] ): __A = ChineseCLIPImageProcessingTester(self ,num_channels=4 ,do_center_crop=A ) __A = 3 @property def UpperCamelCase_ ( self : Dict ): return self.image_processor_tester.prepare_image_processor_dict() def UpperCamelCase_ ( self : Dict ): __A = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(A ,"do_resize" ) ) self.assertTrue(hasattr(A ,"size" ) ) self.assertTrue(hasattr(A ,"do_center_crop" ) ) self.assertTrue(hasattr(A ,"center_crop" ) ) self.assertTrue(hasattr(A ,"do_normalize" ) ) self.assertTrue(hasattr(A ,"image_mean" ) ) self.assertTrue(hasattr(A ,"image_std" ) ) self.assertTrue(hasattr(A ,"do_convert_rgb" ) ) def UpperCamelCase_ ( self : int ): pass def UpperCamelCase_ ( self : Union[str, Any] ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __A = self.image_processor_tester.prepare_inputs(equal_resolution=A ) for image in image_inputs: self.assertIsInstance(A ,Image.Image ) # Test not batched input __A = image_processing(image_inputs[0] ,return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape ,( 1, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,) # Test batched __A = image_processing(A ,return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape ,( self.image_processor_tester.batch_size, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,)
55
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 GLPNImageProcessor class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self : Any ,A : Optional[int] ,A : Optional[int]=7 ,A : Optional[Any]=3 ,A : List[str]=18 ,A : Any=30 ,A : Tuple=4_00 ,A : Union[str, Any]=True ,A : Optional[Any]=32 ,A : Union[str, Any]=True ,): __A = parent __A = batch_size __A = num_channels __A = image_size __A = min_resolution __A = max_resolution __A = do_resize __A = size_divisor __A = do_rescale def UpperCamelCase_ ( self : Union[str, Any] ): return { "do_resize": self.do_resize, "size_divisor": self.size_divisor, "do_rescale": self.do_rescale, } @require_torch @require_vision class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = GLPNImageProcessor if is_vision_available() else None def UpperCamelCase_ ( self : int ): __A = GLPNImageProcessingTester(self ) @property def UpperCamelCase_ ( self : Optional[Any] ): return self.image_processor_tester.prepare_image_processor_dict() def UpperCamelCase_ ( self : Any ): __A = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(A ,"do_resize" ) ) self.assertTrue(hasattr(A ,"size_divisor" ) ) self.assertTrue(hasattr(A ,"resample" ) ) self.assertTrue(hasattr(A ,"do_rescale" ) ) def UpperCamelCase_ ( self : str ): pass def UpperCamelCase_ ( self : Dict ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __A = prepare_image_inputs(self.image_processor_tester ,equal_resolution=A ) for image in image_inputs: self.assertIsInstance(A ,Image.Image ) # Test not batched input (GLPNImageProcessor doesn't support batching) __A = image_processing(image_inputs[0] ,return_tensors="pt" ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 ) def UpperCamelCase_ ( self : Optional[Any] ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __A = prepare_image_inputs(self.image_processor_tester ,equal_resolution=A ,numpify=A ) for image in image_inputs: self.assertIsInstance(A ,np.ndarray ) # Test not batched input (GLPNImageProcessor doesn't support batching) __A = image_processing(image_inputs[0] ,return_tensors="pt" ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 ) def UpperCamelCase_ ( self : int ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A = prepare_image_inputs(self.image_processor_tester ,equal_resolution=A ,torchify=A ) for image in image_inputs: self.assertIsInstance(A ,torch.Tensor ) # Test not batched input (GLPNImageProcessor doesn't support batching) __A = image_processing(image_inputs[0] ,return_tensors="pt" ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 )
55
1
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import KandinskyPipeline, KandinskyPriorPipeline else: from .pipeline_kandinsky import KandinskyPipeline from .pipeline_kandinsky_imgaimg import KandinskyImgaImgPipeline from .pipeline_kandinsky_inpaint import KandinskyInpaintPipeline from .pipeline_kandinsky_prior import KandinskyPriorPipeline, KandinskyPriorPipelineOutput from .text_encoder import MultilingualCLIP
55
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Image from .base import TaskTemplate @dataclass(frozen=__SCREAMING_SNAKE_CASE ) class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = field(default="image-classification" , metadata={"include_in_asdict_even_if_is_default": True} ) snake_case_ = Features({"image": Image()} ) snake_case_ = Features({"labels": ClassLabel} ) snake_case_ = "image" snake_case_ = "labels" def UpperCamelCase_ ( self : Optional[Any] ,A : Tuple ): if self.label_column not in features: raise ValueError(f'''Column {self.label_column} is not present in features.''' ) if not isinstance(features[self.label_column] ,A ): raise ValueError(f'''Column {self.label_column} is not a ClassLabel.''' ) __A = copy.deepcopy(self ) __A = self.label_schema.copy() __A = features[self.label_column] __A = label_schema return task_template @property def UpperCamelCase_ ( self : Any ): return { self.image_column: "image", self.label_column: "labels", }
55
1
import logging import os import sys from dataclasses import dataclass, field from itertools import chain from typing import Optional, Union import datasets import numpy as np import torch from datasets import load_dataset import transformers from transformers import ( AutoConfig, AutoModelForMultipleChoice, AutoTokenizer, HfArgumentParser, Trainer, TrainingArguments, default_data_collator, set_seed, ) from transformers.tokenization_utils_base import PreTrainedTokenizerBase from transformers.trainer_utils import get_last_checkpoint from transformers.utils import PaddingStrategy, check_min_version, send_example_telemetry # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('4.31.0') SCREAMING_SNAKE_CASE :Union[str, Any] = logging.getLogger(__name__) @dataclass class UpperCAmelCase : '''simple docstring''' snake_case_ = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) snake_case_ = field( default=__SCREAMING_SNAKE_CASE , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) snake_case_ = field( default=__SCREAMING_SNAKE_CASE , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) snake_case_ = field( default=__SCREAMING_SNAKE_CASE , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) snake_case_ = field( default=__SCREAMING_SNAKE_CASE , metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."} , ) snake_case_ = field( default="main" , metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} , ) snake_case_ = field( default=__SCREAMING_SNAKE_CASE , metadata={ "help": ( "Will use the token generated when running `huggingface-cli login` (necessary to use this script " "with private models)." ) } , ) @dataclass class UpperCAmelCase : '''simple docstring''' snake_case_ = field(default=__SCREAMING_SNAKE_CASE , metadata={"help": "The input training data file (a text file)."} ) snake_case_ = field( default=__SCREAMING_SNAKE_CASE , metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."} , ) snake_case_ = field( default=__SCREAMING_SNAKE_CASE , metadata={"help": "Overwrite the cached training and evaluation sets"} ) snake_case_ = field( default=__SCREAMING_SNAKE_CASE , metadata={"help": "The number of processes to use for the preprocessing."} , ) snake_case_ = field( default=__SCREAMING_SNAKE_CASE , metadata={ "help": ( "The maximum total input sequence length after tokenization. If passed, sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) snake_case_ = field( default=__SCREAMING_SNAKE_CASE , metadata={ "help": ( "Whether to pad all samples to the maximum sentence length. " "If False, will pad the samples dynamically when batching to the maximum length in the batch. More " "efficient on GPU but very bad for TPU." ) } , ) snake_case_ = field( default=__SCREAMING_SNAKE_CASE , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) } , ) snake_case_ = field( default=__SCREAMING_SNAKE_CASE , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) } , ) def UpperCamelCase_ ( self : Optional[int] ): if self.train_file is not None: __A = self.train_file.split("." )[-1] assert extension in ["csv", "json"], "`train_file` should be a csv or a json file." if self.validation_file is not None: __A = self.validation_file.split("." )[-1] assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file." @dataclass class UpperCAmelCase : '''simple docstring''' snake_case_ = 42 snake_case_ = True snake_case_ = None snake_case_ = None def __call__( self : Optional[Any] ,A : str ): __A = "label" if "label" in features[0].keys() else "labels" __A = [feature.pop(A ) for feature in features] __A = len(A ) __A = len(features[0]["input_ids"] ) __A = [ [{k: v[i] for k, v in feature.items()} for i in range(A )] for feature in features ] __A = list(chain(*A ) ) __A = self.tokenizer.pad( A ,padding=self.padding ,max_length=self.max_length ,pad_to_multiple_of=self.pad_to_multiple_of ,return_tensors="pt" ,) # Un-flatten __A = {k: v.view(A ,A ,-1 ) for k, v in batch.items()} # Add back labels __A = torch.tensor(A ,dtype=torch.intaa ) return batch def UpperCAmelCase ( ) -> List[str]: """simple docstring""" __A = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(".json" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. __A , __A , __A = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: __A , __A , __A = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry("run_swag" , a_ , a_ ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() __A = training_args.get_process_log_level() logger.setLevel(a_ ) datasets.utils.logging.set_verbosity(a_ ) transformers.utils.logging.set_verbosity(a_ ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}''' + F'''distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}''' ) logger.info(F'''Training/evaluation parameters {training_args}''' ) # Detecting last checkpoint. __A = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: __A = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F'''Output directory ({training_args.output_dir}) already exists and is not empty. ''' "Use --overwrite_output_dir to overcome." ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( F'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ''' "the `--output_dir` or add `--overwrite_output_dir` to train from scratch." ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.train_file is not None or data_args.validation_file is not None: __A = {} if data_args.train_file is not None: __A = data_args.train_file if data_args.validation_file is not None: __A = data_args.validation_file __A = data_args.train_file.split("." )[-1] __A = load_dataset( a_ , data_files=a_ , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) else: # Downloading and loading the swag dataset from the hub. __A = load_dataset( "swag" , "regular" , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Load pretrained model and tokenizer # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. __A = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) __A = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast_tokenizer , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) __A = AutoModelForMultipleChoice.from_pretrained( model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path ) , config=a_ , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # When using your own dataset or a different dataset from swag, you will probably need to change this. __A = [F'''ending{i}''' for i in range(4 )] __A = "sent1" __A = "sent2" if data_args.max_seq_length is None: __A = tokenizer.model_max_length if max_seq_length > 1_0_2_4: logger.warning( "The chosen tokenizer supports a `model_max_length` that is longer than the default `block_size` value" " of 1024. If you would like to use a longer `block_size` up to `tokenizer.model_max_length` you can" " override this default with `--block_size xxx`." ) __A = 1_0_2_4 else: if data_args.max_seq_length > tokenizer.model_max_length: logger.warning( F'''The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the''' F'''model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.''' ) __A = min(data_args.max_seq_length , tokenizer.model_max_length ) # Preprocessing the datasets. def preprocess_function(a_ ): __A = [[context] * 4 for context in examples[context_name]] __A = examples[question_header_name] __A = [ [F'''{header} {examples[end][i]}''' for end in ending_names] for i, header in enumerate(a_ ) ] # Flatten out __A = list(chain(*a_ ) ) __A = list(chain(*a_ ) ) # Tokenize __A = tokenizer( a_ , a_ , truncation=a_ , max_length=a_ , padding="max_length" if data_args.pad_to_max_length else False , ) # Un-flatten return {k: [v[i : i + 4] for i in range(0 , len(a_ ) , 4 )] for k, v in tokenized_examples.items()} if training_args.do_train: if "train" not in raw_datasets: raise ValueError("--do_train requires a train dataset" ) __A = raw_datasets["train"] if data_args.max_train_samples is not None: __A = min(len(a_ ) , data_args.max_train_samples ) __A = train_dataset.select(range(a_ ) ) with training_args.main_process_first(desc="train dataset map pre-processing" ): __A = train_dataset.map( a_ , batched=a_ , num_proc=data_args.preprocessing_num_workers , load_from_cache_file=not data_args.overwrite_cache , ) if training_args.do_eval: if "validation" not in raw_datasets: raise ValueError("--do_eval requires a validation dataset" ) __A = raw_datasets["validation"] if data_args.max_eval_samples is not None: __A = min(len(a_ ) , data_args.max_eval_samples ) __A = eval_dataset.select(range(a_ ) ) with training_args.main_process_first(desc="validation dataset map pre-processing" ): __A = eval_dataset.map( a_ , batched=a_ , num_proc=data_args.preprocessing_num_workers , load_from_cache_file=not data_args.overwrite_cache , ) # Data collator __A = ( default_data_collator if data_args.pad_to_max_length else DataCollatorForMultipleChoice(tokenizer=a_ , pad_to_multiple_of=8 if training_args.fpaa else None ) ) # Metric def compute_metrics(a_ ): __A , __A = eval_predictions __A = np.argmax(a_ , axis=1 ) return {"accuracy": (preds == label_ids).astype(np.floataa ).mean().item()} # Initialize our Trainer __A = Trainer( model=a_ , args=a_ , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , tokenizer=a_ , data_collator=a_ , compute_metrics=a_ , ) # Training if training_args.do_train: __A = None if training_args.resume_from_checkpoint is not None: __A = training_args.resume_from_checkpoint elif last_checkpoint is not None: __A = last_checkpoint __A = trainer.train(resume_from_checkpoint=a_ ) trainer.save_model() # Saves the tokenizer too for easy upload __A = train_result.metrics __A = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(a_ ) ) __A = min(a_ , len(a_ ) ) trainer.log_metrics("train" , a_ ) trainer.save_metrics("train" , a_ ) trainer.save_state() # Evaluation if training_args.do_eval: logger.info("*** Evaluate ***" ) __A = trainer.evaluate() __A = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(a_ ) __A = min(a_ , len(a_ ) ) trainer.log_metrics("eval" , a_ ) trainer.save_metrics("eval" , a_ ) __A = { "finetuned_from": model_args.model_name_or_path, "tasks": "multiple-choice", "dataset_tags": "swag", "dataset_args": "regular", "dataset": "SWAG", "language": "en", } if training_args.push_to_hub: trainer.push_to_hub(**a_ ) else: trainer.create_model_card(**a_ ) def UpperCAmelCase ( a_ ) -> List[str]: """simple docstring""" main() if __name__ == "__main__": main()
55
from math import sqrt def UpperCAmelCase ( a_ ) -> bool: """simple docstring""" assert isinstance(a_ , a_ ) and ( number >= 0 ), "'number' must been an int and positive" __A = True # 0 and 1 are none primes. if number <= 1: __A = False for divisor in range(2 , int(round(sqrt(a_ ) ) ) + 1 ): # if 'number' divisible by 'divisor' then sets 'status' # of false and break up the loop. if number % divisor == 0: __A = False break # precondition assert isinstance(a_ , a_ ), "'status' must been from type bool" return status def UpperCAmelCase ( a_ ) -> Any: """simple docstring""" assert isinstance(a_ , a_ ) and (n > 2), "'N' must been an int and > 2" # beginList: contains all natural numbers from 2 up to N __A = list(range(2 , n + 1 ) ) __A = [] # this list will be returns. # actual sieve of erathostenes for i in range(len(a_ ) ): for j in range(i + 1 , len(a_ ) ): if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0): __A = 0 # filters actual prime numbers. __A = [x for x in begin_list if x != 0] # precondition assert isinstance(a_ , a_ ), "'ans' must been from type list" return ans def UpperCAmelCase ( a_ ) -> Optional[int]: """simple docstring""" assert isinstance(a_ , a_ ) and (n > 2), "'N' must been an int and > 2" __A = [] # iterates over all numbers between 2 up to N+1 # if a number is prime then appends to list 'ans' for number in range(2 , n + 1 ): if is_prime(a_ ): ans.append(a_ ) # precondition assert isinstance(a_ , a_ ), "'ans' must been from type list" return ans def UpperCAmelCase ( a_ ) -> Optional[int]: """simple docstring""" assert isinstance(a_ , a_ ) and number >= 0, "'number' must been an int and >= 0" __A = [] # this list will be returns of the function. # potential prime number factors. __A = 2 __A = number if number == 0 or number == 1: ans.append(a_ ) # if 'number' not prime then builds the prime factorization of 'number' elif not is_prime(a_ ): while quotient != 1: if is_prime(a_ ) and (quotient % factor == 0): ans.append(a_ ) quotient /= factor else: factor += 1 else: ans.append(a_ ) # precondition assert isinstance(a_ , a_ ), "'ans' must been from type list" return ans def UpperCAmelCase ( a_ ) -> Any: """simple docstring""" assert isinstance(a_ , a_ ) and ( number >= 0 ), "'number' bust been an int and >= 0" __A = 0 # prime factorization of 'number' __A = prime_factorization(a_ ) __A = max(a_ ) # precondition assert isinstance(a_ , a_ ), "'ans' must been from type int" return ans def UpperCAmelCase ( a_ ) -> Optional[Any]: """simple docstring""" assert isinstance(a_ , a_ ) and ( number >= 0 ), "'number' bust been an int and >= 0" __A = 0 # prime factorization of 'number' __A = prime_factorization(a_ ) __A = min(a_ ) # precondition assert isinstance(a_ , a_ ), "'ans' must been from type int" return ans def UpperCAmelCase ( a_ ) -> int: """simple docstring""" assert isinstance(a_ , a_ ), "'number' must been an int" assert isinstance(number % 2 == 0 , a_ ), "compare bust been from type bool" return number % 2 == 0 def UpperCAmelCase ( a_ ) -> List[Any]: """simple docstring""" assert isinstance(a_ , a_ ), "'number' must been an int" assert isinstance(number % 2 != 0 , a_ ), "compare bust been from type bool" return number % 2 != 0 def UpperCAmelCase ( a_ ) -> Optional[Any]: """simple docstring""" assert ( isinstance(a_ , a_ ) and (number > 2) and is_even(a_ ) ), "'number' must been an int, even and > 2" __A = [] # this list will returned # creates a list of prime numbers between 2 up to 'number' __A = get_prime_numbers(a_ ) __A = len(a_ ) # run variable for while-loops. __A = 0 __A = None # exit variable. for break up the loops __A = True while i < len_pn and loop: __A = i + 1 while j < len_pn and loop: if prime_numbers[i] + prime_numbers[j] == number: __A = False ans.append(prime_numbers[i] ) ans.append(prime_numbers[j] ) j += 1 i += 1 # precondition assert ( isinstance(a_ , a_ ) and (len(a_ ) == 2) and (ans[0] + ans[1] == number) and is_prime(ans[0] ) and is_prime(ans[1] ) ), "'ans' must contains two primes. And sum of elements must been eq 'number'" return ans def UpperCAmelCase ( a_ , a_ ) -> Optional[Any]: """simple docstring""" assert ( isinstance(a_ , a_ ) and isinstance(a_ , a_ ) and (numbera >= 0) and (numbera >= 0) ), "'number1' and 'number2' must been positive integer." __A = 0 while numbera != 0: __A = numbera % numbera __A = numbera __A = rest # precondition assert isinstance(a_ , a_ ) and ( numbera >= 0 ), "'number' must been from type int and positive" return numbera def UpperCAmelCase ( a_ , a_ ) -> List[str]: """simple docstring""" assert ( isinstance(a_ , a_ ) and isinstance(a_ , a_ ) and (numbera >= 1) and (numbera >= 1) ), "'number1' and 'number2' must been positive integer." __A = 1 # actual answer that will be return. # for kgV (x,1) if numbera > 1 and numbera > 1: # builds the prime factorization of 'number1' and 'number2' __A = prime_factorization(a_ ) __A = prime_factorization(a_ ) elif numbera == 1 or numbera == 1: __A = [] __A = [] __A = max(a_ , a_ ) __A = 0 __A = 0 __A = [] # captured numbers int both 'primeFac1' and 'primeFac2' # iterates through primeFac1 for n in prime_fac_a: if n not in done: if n in prime_fac_a: __A = prime_fac_a.count(a_ ) __A = prime_fac_a.count(a_ ) for _ in range(max(a_ , a_ ) ): ans *= n else: __A = prime_fac_a.count(a_ ) for _ in range(a_ ): ans *= n done.append(a_ ) # iterates through primeFac2 for n in prime_fac_a: if n not in done: __A = prime_fac_a.count(a_ ) for _ in range(a_ ): ans *= n done.append(a_ ) # precondition assert isinstance(a_ , a_ ) and ( ans >= 0 ), "'ans' must been from type int and positive" return ans def UpperCAmelCase ( a_ ) -> str: """simple docstring""" assert isinstance(a_ , a_ ) and (n >= 0), "'number' must been a positive int" __A = 0 __A = 2 # this variable holds the answer while index < n: index += 1 ans += 1 # counts to the next number # if ans not prime then # runs to the next prime number. while not is_prime(a_ ): ans += 1 # precondition assert isinstance(a_ , a_ ) and is_prime( a_ ), "'ans' must been a prime number and from type int" return ans def UpperCAmelCase ( a_ , a_ ) -> Tuple: """simple docstring""" assert ( is_prime(a_ ) and is_prime(a_ ) and (p_number_a < p_number_a) ), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'" __A = p_number_a + 1 # jump to the next number __A = [] # this list will be returns. # if number is not prime then # fetch the next prime number. while not is_prime(a_ ): number += 1 while number < p_number_a: ans.append(a_ ) number += 1 # fetch the next prime number. while not is_prime(a_ ): number += 1 # precondition assert ( isinstance(a_ , a_ ) and ans[0] != p_number_a and ans[len(a_ ) - 1] != p_number_a ), "'ans' must been a list without the arguments" # 'ans' contains not 'pNumber1' and 'pNumber2' ! return ans def UpperCAmelCase ( a_ ) -> str: """simple docstring""" assert isinstance(a_ , a_ ) and (n >= 1), "'n' must been int and >= 1" __A = [] # will be returned. for divisor in range(1 , n + 1 ): if n % divisor == 0: ans.append(a_ ) # precondition assert ans[0] == 1 and ans[len(a_ ) - 1] == n, "Error in function getDivisiors(...)" return ans def UpperCAmelCase ( a_ ) -> Dict: """simple docstring""" assert isinstance(a_ , a_ ) and ( number > 1 ), "'number' must been an int and >= 1" __A = get_divisors(a_ ) # precondition assert ( isinstance(a_ , a_ ) and (divisors[0] == 1) and (divisors[len(a_ ) - 1] == number) ), "Error in help-function getDivisiors(...)" # summed all divisors up to 'number' (exclusive), hence [:-1] return sum(divisors[:-1] ) == number def UpperCAmelCase ( a_ , a_ ) -> str: """simple docstring""" assert ( isinstance(a_ , a_ ) and isinstance(a_ , a_ ) and (denominator != 0) ), "The arguments must been from type int and 'denominator' != 0" # build the greatest common divisor of numerator and denominator. __A = gcd(abs(a_ ) , abs(a_ ) ) # precondition assert ( isinstance(a_ , a_ ) and (numerator % gcd_of_fraction == 0) and (denominator % gcd_of_fraction == 0) ), "Error in function gcd(...,...)" return (numerator // gcd_of_fraction, denominator // gcd_of_fraction) def UpperCAmelCase ( a_ ) -> Optional[int]: """simple docstring""" assert isinstance(a_ , a_ ) and (n >= 0), "'n' must been a int and >= 0" __A = 1 # this will be return. for factor in range(1 , n + 1 ): ans *= factor return ans def UpperCAmelCase ( a_ ) -> List[Any]: """simple docstring""" assert isinstance(a_ , a_ ) and (n >= 0), "'n' must been an int and >= 0" __A = 0 __A = 1 __A = 1 # this will be return for _ in range(n - 1 ): __A = ans ans += fiba __A = tmp return ans
55
1
from __future__ import annotations from collections.abc import Generator import requests from bsa import BeautifulSoup SCREAMING_SNAKE_CASE :int = 'https://www.indeed.co.in/jobs?q=mobile+app+development&l=' def UpperCAmelCase ( a_ = "mumbai" ) -> Generator[tuple[str, str], None, None]: """simple docstring""" __A = BeautifulSoup(requests.get(url + location ).content , "html.parser" ) # This attribute finds out all the specifics listed in a job for job in soup.find_all("div" , attrs={"data-tn-component": "organicJob"} ): __A = job.find("a" , attrs={"data-tn-element": "jobTitle"} ).text.strip() __A = job.find("span" , {"class": "company"} ).text.strip() yield job_title, company_name if __name__ == "__main__": for i, job in enumerate(fetch_jobs('Bangalore'), 1): print(f'''Job {i:>2} is {job[0]} at {job[1]}''')
55
import os def UpperCAmelCase ( ) -> Any: """simple docstring""" __A = os.path.dirname(os.path.realpath(a_ ) ) __A = os.path.join(a_ , "triangle.txt" ) with open(a_ ) as f: __A = f.readlines() __A = [] for line in triangle: __A = [] for number in line.strip().split(" " ): numbers_from_line.append(int(a_ ) ) a.append(a_ ) for i in range(1 , len(a_ ) ): for j in range(len(a[i] ) ): __A = a[i - 1][j] if j != len(a[i - 1] ) else 0 __A = a[i - 1][j - 1] if j > 0 else 0 a[i][j] += max(a_ , a_ ) return max(a[-1] ) if __name__ == "__main__": print(solution())
55
1
from math import factorial class UpperCAmelCase : '''simple docstring''' def __init__( self : List[str] ,A : Optional[int] ,A : int ): __A = real if isinstance(A ,A ): __A = [1] * rank else: __A = rank def __repr__( self : Tuple ): return ( f'''{self.real}+''' f'''{'+'.join(str(A )+'E'+str(n+1 )for n,dual in enumerate(self.duals ) )}''' ) def UpperCamelCase_ ( self : List[Any] ): __A = self.duals.copy() while cur[-1] == 0: cur.pop(-1 ) return Dual(self.real ,A ) def __add__( self : Optional[Any] ,A : List[Any] ): if not isinstance(A ,A ): return Dual(self.real + other ,self.duals ) __A = self.duals.copy() __A = other.duals.copy() if len(A ) > len(A ): o_dual.extend([1] * (len(A ) - len(A )) ) elif len(A ) < len(A ): s_dual.extend([1] * (len(A ) - len(A )) ) __A = [] for i in range(len(A ) ): new_duals.append(s_dual[i] + o_dual[i] ) return Dual(self.real + other.real ,A ) snake_case_ = __add__ def __sub__( self : int ,A : Dict ): return self + other * -1 def __mul__( self : List[Any] ,A : List[str] ): if not isinstance(A ,A ): __A = [] for i in self.duals: new_duals.append(i * other ) return Dual(self.real * other ,A ) __A = [0] * (len(self.duals ) + len(other.duals ) + 1) for i, item in enumerate(self.duals ): for j, jtem in enumerate(other.duals ): new_duals[i + j + 1] += item * jtem for k in range(len(self.duals ) ): new_duals[k] += self.duals[k] * other.real for index in range(len(other.duals ) ): new_duals[index] += other.duals[index] * self.real return Dual(self.real * other.real ,A ) snake_case_ = __mul__ def __truediv__( self : Tuple ,A : Dict ): if not isinstance(A ,A ): __A = [] for i in self.duals: new_duals.append(i / other ) return Dual(self.real / other ,A ) raise ValueError def __floordiv__( self : List[str] ,A : Tuple ): if not isinstance(A ,A ): __A = [] for i in self.duals: new_duals.append(i // other ) return Dual(self.real // other ,A ) raise ValueError def __pow__( self : Optional[Any] ,A : List[str] ): if n < 0 or isinstance(A ,A ): raise ValueError("power must be a positive integer" ) if n == 0: return 1 if n == 1: return self __A = self for _ in range(n - 1 ): x *= self return x def UpperCAmelCase ( a_ , a_ , a_ ) -> List[str]: """simple docstring""" if not callable(a_ ): raise ValueError("differentiate() requires a function as input for func" ) if not isinstance(a_ , (float, int) ): raise ValueError("differentiate() requires a float as input for position" ) if not isinstance(a_ , a_ ): raise ValueError("differentiate() requires an int as input for order" ) __A = Dual(a_ , 1 ) __A = func(a_ ) if order == 0: return result.real return result.duals[order - 1] * factorial(a_ ) if __name__ == "__main__": import doctest doctest.testmod() def UpperCAmelCase ( a_ ) -> Dict: """simple docstring""" return y**2 * y**4 print(differentiate(f, 9, 2))
55
import re from flax.core.frozen_dict import freeze from flax.traverse_util import flatten_dict, unflatten_dict from jax.experimental import PartitionSpec as P # Sentinels SCREAMING_SNAKE_CASE :Union[str, Any] = object() # For specifying empty leaf dict `{}` SCREAMING_SNAKE_CASE :List[str] = object() def UpperCAmelCase ( a_ , a_ ) -> Tuple: """simple docstring""" __A = tuple((re.compile(x + "$" ) for x in qs) ) for i in range(len(a_ ) - len(a_ ) + 1 ): __A = [x.match(a_ ) for x, y in zip(a_ , ks[i:] )] if matches and all(a_ ): return True return False def UpperCAmelCase ( a_ ) -> Optional[int]: """simple docstring""" def replace(a_ , a_ ): for rule, replacement in rules: if _match(a_ , a_ ): return replacement return val return replace def UpperCAmelCase ( ) -> int: """simple docstring""" return [ # embeddings (("transformer", "wpe", "embedding"), P("mp" , a_ )), (("transformer", "wte", "embedding"), P("mp" , a_ )), # atention (("attention", "(q_proj|k_proj|v_proj)", "kernel"), P(a_ , "mp" )), (("attention", "out_proj", "kernel"), P("mp" , a_ )), (("attention", "out_proj", "bias"), None), # mlp (("mlp", "c_fc", "kernel"), P(a_ , "mp" )), (("mlp", "c_fc", "bias"), P("mp" )), (("mlp", "c_proj", "kernel"), P("mp" , a_ )), (("mlp", "c_proj", "bias"), None), # layer norms ((r"ln_\d+", "bias"), None), ((r"\d+", r"ln_\d+", "scale"), None), (("ln_f", "bias"), None), (("ln_f", "scale"), None), ] def UpperCAmelCase ( a_ ) -> List[Any]: """simple docstring""" __A = _get_partition_rules() __A = _replacement_rules(a_ ) __A = {k: _unmatched for k in flatten_dict(a_ )} __A = {k: replace(a_ , a_ ) for k, v in initd.items()} assert _unmatched not in result.values(), "Incomplete partition spec." return freeze(unflatten_dict(a_ ) )
55
1
import unittest from transformers import MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING, AutoTokenizer, is_vision_available from transformers.pipelines import pipeline from transformers.pipelines.document_question_answering import apply_tesseract from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_detectrona, require_pytesseract, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image from transformers.image_utils import load_image else: class UpperCAmelCase : '''simple docstring''' @staticmethod def UpperCamelCase_ ( *A : List[Any] ,**A : Tuple ): pass def UpperCAmelCase ( a_ ) -> int: """simple docstring""" return None # This is a pinned image from a specific revision of a document question answering space, hosted by HuggingFace, # so we can expect it to be available. SCREAMING_SNAKE_CASE :Any = ( 'https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png' ) @is_pipeline_test @require_torch @require_vision class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' snake_case_ = MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING @require_pytesseract @require_vision def UpperCamelCase_ ( self : Tuple ,A : List[str] ,A : List[str] ,A : int ): __A = pipeline( "document-question-answering" ,model=A ,tokenizer=A ,image_processor=A ) __A = INVOICE_URL __A = list(zip(*apply_tesseract(load_image(A ) ,A ,"" ) ) ) __A = "What is the placebo?" __A = [ { "image": load_image(A ), "question": question, }, { "image": image, "question": question, }, { "image": image, "question": question, "word_boxes": word_boxes, }, ] return dqa_pipeline, examples def UpperCamelCase_ ( self : Optional[int] ,A : Union[str, Any] ,A : Optional[Any] ): __A = dqa_pipeline(A ,top_k=2 ) self.assertEqual( A ,[ [ {"score": ANY(A ), "answer": ANY(A ), "start": ANY(A ), "end": ANY(A )}, {"score": ANY(A ), "answer": ANY(A ), "start": ANY(A ), "end": ANY(A )}, ] ] * 3 ,) @require_torch @require_detectrona @require_pytesseract def UpperCamelCase_ ( self : Any ): __A = pipeline("document-question-answering" ,model="hf-internal-testing/tiny-random-layoutlmv2" ) __A = INVOICE_URL __A = "How many cats are there?" __A = [ {"score": 0.00_01, "answer": "oy 2312/2019", "start": 38, "end": 39}, {"score": 0.00_01, "answer": "oy 2312/2019 DUE", "start": 38, "end": 40}, ] __A = dqa_pipeline(image=A ,question=A ,top_k=2 ) self.assertEqual(nested_simplify(A ,decimals=4 ) ,A ) __A = dqa_pipeline({"image": image, "question": question} ,top_k=2 ) self.assertEqual(nested_simplify(A ,decimals=4 ) ,A ) # This image does not detect ANY text in it, meaning layoutlmv2 should fail. # Empty answer probably __A = "./tests/fixtures/tests_samples/COCO/000000039769.png" __A = dqa_pipeline(image=A ,question=A ,top_k=2 ) self.assertEqual(A ,[] ) # We can optionnally pass directly the words and bounding boxes __A = "./tests/fixtures/tests_samples/COCO/000000039769.png" __A = [] __A = [] __A = dqa_pipeline(image=A ,question=A ,words=A ,boxes=A ,top_k=2 ) self.assertEqual(A ,[] ) @slow @require_torch @require_detectrona @require_pytesseract def UpperCamelCase_ ( self : Union[str, Any] ): __A = pipeline( "document-question-answering" ,model="tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa" ,revision="9977165" ,) __A = INVOICE_URL __A = "What is the invoice number?" __A = dqa_pipeline(image=A ,question=A ,top_k=2 ) self.assertEqual( nested_simplify(A ,decimals=4 ) ,[ {"score": 0.99_44, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.00_09, "answer": "us-001", "start": 16, "end": 16}, ] ,) __A = dqa_pipeline({"image": image, "question": question} ,top_k=2 ) self.assertEqual( nested_simplify(A ,decimals=4 ) ,[ {"score": 0.99_44, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.00_09, "answer": "us-001", "start": 16, "end": 16}, ] ,) __A = dqa_pipeline( [{"image": image, "question": question}, {"image": image, "question": question}] ,top_k=2 ) self.assertEqual( nested_simplify(A ,decimals=4 ) ,[ [ {"score": 0.99_44, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.00_09, "answer": "us-001", "start": 16, "end": 16}, ], ] * 2 ,) @slow @require_torch @require_detectrona @require_pytesseract def UpperCamelCase_ ( self : Any ): __A = pipeline( "document-question-answering" ,model="tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa" ,revision="9977165" ,max_seq_len=50 ,) __A = INVOICE_URL __A = "What is the invoice number?" __A = dqa_pipeline(image=A ,question=A ,top_k=2 ) self.assertEqual( nested_simplify(A ,decimals=4 ) ,[ {"score": 0.99_74, "answer": "1110212019", "start": 23, "end": 23}, {"score": 0.99_48, "answer": "us-001", "start": 16, "end": 16}, ] ,) __A = dqa_pipeline({"image": image, "question": question} ,top_k=2 ) self.assertEqual( nested_simplify(A ,decimals=4 ) ,[ {"score": 0.99_74, "answer": "1110212019", "start": 23, "end": 23}, {"score": 0.99_48, "answer": "us-001", "start": 16, "end": 16}, ] ,) __A = dqa_pipeline( [{"image": image, "question": question}, {"image": image, "question": question}] ,top_k=2 ) self.assertEqual( nested_simplify(A ,decimals=4 ) ,[ [ {"score": 0.99_74, "answer": "1110212019", "start": 23, "end": 23}, {"score": 0.99_48, "answer": "us-001", "start": 16, "end": 16}, ] ] * 2 ,) @slow @require_torch @require_pytesseract @require_vision def UpperCamelCase_ ( self : Any ): __A = AutoTokenizer.from_pretrained( "impira/layoutlm-document-qa" ,revision="3dc6de3" ,add_prefix_space=A ) __A = pipeline( "document-question-answering" ,model="impira/layoutlm-document-qa" ,tokenizer=A ,revision="3dc6de3" ,) __A = INVOICE_URL __A = "What is the invoice number?" __A = dqa_pipeline(image=A ,question=A ,top_k=2 ) self.assertEqual( nested_simplify(A ,decimals=4 ) ,[ {"score": 0.42_51, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.08_19, "answer": "1110212019", "start": 23, "end": 23}, ] ,) __A = dqa_pipeline({"image": image, "question": question} ,top_k=2 ) self.assertEqual( nested_simplify(A ,decimals=4 ) ,[ {"score": 0.42_51, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.08_19, "answer": "1110212019", "start": 23, "end": 23}, ] ,) __A = dqa_pipeline( [{"image": image, "question": question}, {"image": image, "question": question}] ,top_k=2 ) self.assertEqual( nested_simplify(A ,decimals=4 ) ,[ [ {"score": 0.42_51, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.08_19, "answer": "1110212019", "start": 23, "end": 23}, ] ] * 2 ,) __A = list(zip(*apply_tesseract(load_image(A ) ,A ,"" ) ) ) # This model should also work if `image` is set to None __A = dqa_pipeline({"image": None, "word_boxes": word_boxes, "question": question} ,top_k=2 ) self.assertEqual( nested_simplify(A ,decimals=4 ) ,[ {"score": 0.42_51, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.08_19, "answer": "1110212019", "start": 23, "end": 23}, ] ,) @slow @require_torch @require_pytesseract @require_vision def UpperCamelCase_ ( self : Optional[Any] ): __A = AutoTokenizer.from_pretrained( "impira/layoutlm-document-qa" ,revision="3dc6de3" ,add_prefix_space=A ) __A = pipeline( "document-question-answering" ,model="impira/layoutlm-document-qa" ,tokenizer=A ,revision="3dc6de3" ,max_seq_len=50 ,) __A = INVOICE_URL __A = "What is the invoice number?" __A = dqa_pipeline(image=A ,question=A ,top_k=2 ) self.assertEqual( nested_simplify(A ,decimals=4 ) ,[ {"score": 0.99_99, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.99_98, "answer": "us-001", "start": 16, "end": 16}, ] ,) __A = dqa_pipeline( [{"image": image, "question": question}, {"image": image, "question": question}] ,top_k=2 ) self.assertEqual( nested_simplify(A ,decimals=4 ) ,[ [ {"score": 0.99_99, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.99_98, "answer": "us-001", "start": 16, "end": 16}, ] ] * 2 ,) __A = list(zip(*apply_tesseract(load_image(A ) ,A ,"" ) ) ) # This model should also work if `image` is set to None __A = dqa_pipeline({"image": None, "word_boxes": word_boxes, "question": question} ,top_k=2 ) self.assertEqual( nested_simplify(A ,decimals=4 ) ,[ {"score": 0.99_99, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.99_98, "answer": "us-001", "start": 16, "end": 16}, ] ,) @slow @require_torch def UpperCamelCase_ ( self : List[str] ): __A = pipeline( "document-question-answering" ,model="naver-clova-ix/donut-base-finetuned-docvqa" ,tokenizer=AutoTokenizer.from_pretrained("naver-clova-ix/donut-base-finetuned-docvqa" ) ,feature_extractor="naver-clova-ix/donut-base-finetuned-docvqa" ,) __A = INVOICE_URL __A = "What is the invoice number?" __A = dqa_pipeline(image=A ,question=A ,top_k=2 ) self.assertEqual(nested_simplify(A ,decimals=4 ) ,[{"answer": "us-001"}] ) @require_tf @unittest.skip("Document question answering not implemented in TF" ) def UpperCamelCase_ ( self : Any ): pass
55
from __future__ import annotations import inspect import unittest import numpy as np from transformers import DeiTConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, TFDeiTModel, ) from transformers.models.deit.modeling_tf_deit import TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class UpperCAmelCase : '''simple docstring''' def __init__( self : List[Any] ,A : Union[str, Any] ,A : List[Any]=13 ,A : Optional[Any]=30 ,A : Union[str, Any]=2 ,A : Union[str, Any]=3 ,A : Any=True ,A : Dict=True ,A : str=32 ,A : Tuple=2 ,A : Optional[int]=4 ,A : Tuple=37 ,A : List[Any]="gelu" ,A : Dict=0.1 ,A : Optional[int]=0.1 ,A : List[Any]=10 ,A : Optional[Any]=0.02 ,A : Dict=3 ,A : Dict=None ,A : List[Any]=2 ,): __A = parent __A = batch_size __A = image_size __A = patch_size __A = num_channels __A = is_training __A = use_labels __A = hidden_size __A = num_hidden_layers __A = num_attention_heads __A = intermediate_size __A = hidden_act __A = hidden_dropout_prob __A = attention_probs_dropout_prob __A = type_sequence_label_size __A = initializer_range __A = scope __A = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) __A = (image_size // patch_size) ** 2 __A = num_patches + 2 def UpperCamelCase_ ( self : List[Any] ): __A = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __A = None if self.use_labels: __A = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) __A = self.get_config() return config, pixel_values, labels def UpperCamelCase_ ( self : Optional[int] ): return DeiTConfig( image_size=self.image_size ,patch_size=self.patch_size ,num_channels=self.num_channels ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,hidden_act=self.hidden_act ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,is_decoder=A ,initializer_range=self.initializer_range ,encoder_stride=self.encoder_stride ,) def UpperCamelCase_ ( self : List[str] ,A : List[Any] ,A : Optional[int] ,A : Union[str, Any] ): __A = TFDeiTModel(config=A ) __A = model(A ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase_ ( self : List[Any] ,A : List[Any] ,A : Optional[Any] ,A : Dict ): __A = TFDeiTForMaskedImageModeling(config=A ) __A = model(A ) self.parent.assertEqual( result.reconstruction.shape ,(self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images __A = 1 __A = TFDeiTForMaskedImageModeling(A ) __A = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __A = model(A ) self.parent.assertEqual(result.reconstruction.shape ,(self.batch_size, 1, self.image_size, self.image_size) ) def UpperCamelCase_ ( self : Optional[Any] ,A : Union[str, Any] ,A : Dict ,A : Union[str, Any] ): __A = self.type_sequence_label_size __A = TFDeiTForImageClassification(A ) __A = model(A ,labels=A ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) # test greyscale images __A = 1 __A = TFDeiTForImageClassification(A ) __A = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __A = model(A ,labels=A ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) def UpperCamelCase_ ( self : str ): __A = self.prepare_config_and_inputs() __A , __A , __A = config_and_inputs __A = {"pixel_values": pixel_values} return config, inputs_dict @require_tf class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = ( ( TFDeiTModel, TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, ) if is_tf_available() else () ) snake_case_ = ( { "feature-extraction": TFDeiTModel, "image-classification": (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher), } if is_tf_available() else {} ) snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = False def UpperCamelCase_ ( self : str ): __A = TFDeiTModelTester(self ) __A = ConfigTester(self ,config_class=A ,has_text_modality=A ,hidden_size=37 ) def UpperCamelCase_ ( self : Any ): self.config_tester.run_common_tests() @unittest.skip(reason="DeiT does not use inputs_embeds" ) def UpperCamelCase_ ( self : Union[str, Any] ): pass def UpperCamelCase_ ( self : List[Any] ): __A , __A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __A = model_class(A ) self.assertIsInstance(model.get_input_embeddings() ,(tf.keras.layers.Layer) ) __A = model.get_output_embeddings() self.assertTrue(x is None or isinstance(A ,tf.keras.layers.Dense ) ) def UpperCamelCase_ ( self : Union[str, Any] ): __A , __A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __A = model_class(A ) __A = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __A = [*signature.parameters.keys()] __A = ["pixel_values"] self.assertListEqual(arg_names[:1] ,A ) def UpperCamelCase_ ( self : Union[str, Any] ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A ) def UpperCamelCase_ ( self : Union[str, Any] ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*A ) def UpperCamelCase_ ( self : Optional[Any] ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*A ) def UpperCamelCase_ ( self : Optional[int] ,A : Union[str, Any] ,A : List[str] ,A : Optional[Any]=False ): __A = super()._prepare_for_class(A ,A ,return_labels=A ) if return_labels: if "labels" in inputs_dict and "labels" not in inspect.signature(model_class.call ).parameters: del inputs_dict["labels"] return inputs_dict @slow def UpperCamelCase_ ( self : Any ): for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __A = TFDeiTModel.from_pretrained(A ) self.assertIsNotNone(A ) def UpperCAmelCase ( ) -> str: """simple docstring""" __A = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_tf @require_vision class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def UpperCamelCase_ ( self : int ): return ( DeiTImageProcessor.from_pretrained("facebook/deit-base-distilled-patch16-224" ) if is_vision_available() else None ) @slow def UpperCamelCase_ ( self : Optional[int] ): __A = TFDeiTForImageClassificationWithTeacher.from_pretrained("facebook/deit-base-distilled-patch16-224" ) __A = self.default_image_processor __A = prepare_img() __A = image_processor(images=A ,return_tensors="tf" ) # forward pass __A = model(**A ) # verify the logits __A = tf.TensorShape((1, 10_00) ) self.assertEqual(outputs.logits.shape ,A ) __A = tf.constant([-1.02_66, 0.19_12, -1.28_61] ) self.assertTrue(np.allclose(outputs.logits[0, :3] ,A ,atol=1E-4 ) )
55
1
import argparse import glob import logging import os import time from argparse import Namespace import numpy as np import torch from lightning_base import BaseTransformer, add_generic_args, generic_train from torch.utils.data import DataLoader, TensorDataset from transformers import glue_compute_metrics as compute_metrics from transformers import glue_convert_examples_to_features as convert_examples_to_features from transformers import glue_output_modes, glue_tasks_num_labels from transformers import glue_processors as processors SCREAMING_SNAKE_CASE :List[Any] = logging.getLogger(__name__) class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = "sequence-classification" def __init__( self : Tuple ,A : List[Any] ): if type(A ) == dict: __A = Namespace(**A ) __A = glue_output_modes[hparams.task] __A = glue_tasks_num_labels[hparams.task] super().__init__(A ,A ,self.mode ) def UpperCamelCase_ ( self : List[Any] ,**A : Optional[Any] ): return self.model(**A ) def UpperCamelCase_ ( self : Optional[Any] ,A : int ,A : Any ): __A = {"input_ids": batch[0], "attention_mask": batch[1], "labels": batch[3]} if self.config.model_type not in ["distilbert", "bart"]: __A = batch[2] if self.config.model_type in ["bert", "xlnet", "albert"] else None __A = self(**A ) __A = outputs[0] __A = self.trainer.lr_schedulers[0]["scheduler"] __A = {"loss": loss, "rate": lr_scheduler.get_last_lr()[-1]} return {"loss": loss, "log": tensorboard_logs} def UpperCamelCase_ ( self : Optional[int] ): __A = self.hparams __A = processors[args.task]() __A = processor.get_labels() for mode in ["train", "dev"]: __A = self._feature_file(A ) if os.path.exists(A ) and not args.overwrite_cache: logger.info("Loading features from cached file %s" ,A ) else: logger.info("Creating features from dataset file at %s" ,args.data_dir ) __A = ( processor.get_dev_examples(args.data_dir ) if mode == "dev" else processor.get_train_examples(args.data_dir ) ) __A = convert_examples_to_features( A ,self.tokenizer ,max_length=args.max_seq_length ,label_list=self.labels ,output_mode=args.glue_output_mode ,) logger.info("Saving features into cached file %s" ,A ) torch.save(A ,A ) def UpperCamelCase_ ( self : Union[str, Any] ,A : str ,A : int ,A : bool = False ): __A = "dev" if mode == "test" else mode __A = self._feature_file(A ) logger.info("Loading features from cached file %s" ,A ) __A = torch.load(A ) __A = torch.tensor([f.input_ids for f in features] ,dtype=torch.long ) __A = torch.tensor([f.attention_mask for f in features] ,dtype=torch.long ) __A = torch.tensor([f.token_type_ids for f in features] ,dtype=torch.long ) if self.hparams.glue_output_mode == "classification": __A = torch.tensor([f.label for f in features] ,dtype=torch.long ) elif self.hparams.glue_output_mode == "regression": __A = torch.tensor([f.label for f in features] ,dtype=torch.float ) return DataLoader( TensorDataset(A ,A ,A ,A ) ,batch_size=A ,shuffle=A ,) def UpperCamelCase_ ( self : Optional[Any] ,A : Optional[Any] ,A : int ): __A = {"input_ids": batch[0], "attention_mask": batch[1], "labels": batch[3]} if self.config.model_type not in ["distilbert", "bart"]: __A = batch[2] if self.config.model_type in ["bert", "xlnet", "albert"] else None __A = self(**A ) __A , __A = outputs[:2] __A = logits.detach().cpu().numpy() __A = inputs["labels"].detach().cpu().numpy() return {"val_loss": tmp_eval_loss.detach().cpu(), "pred": preds, "target": out_label_ids} def UpperCamelCase_ ( self : Optional[Any] ,A : int ): __A = torch.stack([x["val_loss"] for x in outputs] ).mean().detach().cpu().item() __A = np.concatenate([x["pred"] for x in outputs] ,axis=0 ) if self.hparams.glue_output_mode == "classification": __A = np.argmax(A ,axis=1 ) elif self.hparams.glue_output_mode == "regression": __A = np.squeeze(A ) __A = np.concatenate([x["target"] for x in outputs] ,axis=0 ) __A = [[] for _ in range(out_label_ids.shape[0] )] __A = [[] for _ in range(out_label_ids.shape[0] )] __A = {**{"val_loss": val_loss_mean}, **compute_metrics(self.hparams.task ,A ,A )} __A = dict(results.items() ) __A = results return ret, preds_list, out_label_list def UpperCamelCase_ ( self : Any ,A : list ): __A , __A , __A = self._eval_end(A ) __A = ret["log"] return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs} def UpperCamelCase_ ( self : List[str] ,A : Union[str, Any] ): __A , __A , __A = self._eval_end(A ) __A = ret["log"] # `val_loss` is the key returned by `self._eval_end()` but actually refers to `test_loss` return {"avg_test_loss": logs["val_loss"], "log": logs, "progress_bar": logs} @staticmethod def UpperCamelCase_ ( A : Any ,A : List[Any] ): BaseTransformer.add_model_specific_args(A ,A ) parser.add_argument( "--max_seq_length" ,default=1_28 ,type=A ,help=( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) ,) parser.add_argument( "--task" ,default="" ,type=A ,required=A ,help="The GLUE task to run" ,) parser.add_argument( "--gpus" ,default=0 ,type=A ,help="The number of GPUs allocated for this, it is by default 0 meaning none" ,) parser.add_argument( "--overwrite_cache" ,action="store_true" ,help="Overwrite the cached training and evaluation sets" ) return parser def UpperCAmelCase ( ) -> Any: """simple docstring""" __A = argparse.ArgumentParser() add_generic_args(a_ , os.getcwd() ) __A = GLUETransformer.add_model_specific_args(a_ , os.getcwd() ) __A = parser.parse_args() # If output_dir not provided, a folder will be generated in pwd if args.output_dir is None: __A = os.path.join( "./results" , F'''{args.task}_{time.strftime('%Y%m%d_%H%M%S' )}''' , ) os.makedirs(args.output_dir ) __A = GLUETransformer(a_ ) __A = generic_train(a_ , a_ ) # Optionally, predict on dev set and write to output_dir if args.do_predict: __A = sorted(glob.glob(os.path.join(args.output_dir , "checkpoint-epoch=*.ckpt" ) , recursive=a_ ) ) __A = model.load_from_checkpoint(checkpoints[-1] ) return trainer.test(a_ ) if __name__ == "__main__": main()
55
SCREAMING_SNAKE_CASE :List[Any] = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] SCREAMING_SNAKE_CASE :Union[str, Any] = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] SCREAMING_SNAKE_CASE :int = { 0: 'Sunday', 1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday', 5: 'Friday', 6: 'Saturday', } def UpperCAmelCase ( a_ , a_ , a_ ) -> str: """simple docstring""" assert len(str(a_ ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 1_2, "month should be between 1 to 12" assert 1 <= day <= 3_1, "day should be between 1 to 31" # Doomsday algorithm: __A = year // 1_0_0 __A = (5 * (century % 4) + 2) % 7 __A = year % 1_0_0 __A = centurian % 1_2 __A = ( (centurian // 1_2) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 __A = ( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 4_0_0) == 0) else DOOMSDAY_LEAP[month - 1] ) __A = (dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
55
1
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch from ..models.speechta import SpeechTaForTextToSpeech, SpeechTaHifiGan, SpeechTaProcessor from ..utils import is_datasets_available from .base import PipelineTool if is_datasets_available(): from datasets import load_dataset class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = "microsoft/speecht5_tts" snake_case_ = ( "This is a tool that reads an English text out loud. It takes an input named `text` which should contain the " "text to read (in English) and returns a waveform object containing the sound." ) snake_case_ = "text_reader" snake_case_ = SpeechTaProcessor snake_case_ = SpeechTaForTextToSpeech snake_case_ = SpeechTaHifiGan snake_case_ = ["text"] snake_case_ = ["audio"] def UpperCamelCase_ ( self : Any ): if self.post_processor is None: __A = "microsoft/speecht5_hifigan" super().setup() def UpperCamelCase_ ( self : Union[str, Any] ,A : Optional[Any] ,A : Union[str, Any]=None ): __A = self.pre_processor(text=A ,return_tensors="pt" ,truncation=A ) if speaker_embeddings is None: if not is_datasets_available(): raise ImportError("Datasets needs to be installed if not passing speaker embeddings." ) __A = load_dataset("Matthijs/cmu-arctic-xvectors" ,split="validation" ) __A = torch.tensor(embeddings_dataset[73_05]["xvector"] ).unsqueeze(0 ) return {"input_ids": inputs["input_ids"], "speaker_embeddings": speaker_embeddings} def UpperCamelCase_ ( self : List[str] ,A : Any ): with torch.no_grad(): return self.model.generate_speech(**A ) def UpperCamelCase_ ( self : List[Any] ,A : Optional[int] ): with torch.no_grad(): return self.post_processor(A ).cpu().detach()
55
from json import JSONDecodeError # Workaround for requests.exceptions.JSONDecodeError import requests def UpperCAmelCase ( a_ = "isbn/0140328726" ) -> dict: """simple docstring""" __A = olid.strip().strip("/" ) # Remove leading/trailing whitespace & slashes if new_olid.count("/" ) != 1: __A = F'''{olid} is not a valid Open Library olid''' raise ValueError(a_ ) return requests.get(F'''https://openlibrary.org/{new_olid}.json''' ).json() def UpperCAmelCase ( a_ ) -> dict: """simple docstring""" __A = { "title": "Title", "publish_date": "Publish date", "authors": "Authors", "number_of_pages": "Number of pages:", "first_sentence": "First sentence", "isbn_10": "ISBN (10)", "isbn_13": "ISBN (13)", } __A = {better_key: ol_book_data[key] for key, better_key in desired_keys.items()} __A = [ get_openlibrary_data(author["key"] )["name"] for author in data["Authors"] ] __A = data["First sentence"]["value"] for key, value in data.items(): if isinstance(a_ , a_ ): __A = ", ".join(a_ ) return data if __name__ == "__main__": import doctest doctest.testmod() while True: SCREAMING_SNAKE_CASE :int = input('\nEnter the ISBN code to search (or \'quit\' to stop): ').strip() if isbn.lower() in ("", "q", "quit", "exit", "stop"): break if len(isbn) not in (10, 13) or not isbn.isdigit(): print(f'''Sorry, {isbn} is not a valid ISBN. Please, input a valid ISBN.''') continue print(f'''\nSearching Open Library for ISBN: {isbn}...\n''') try: SCREAMING_SNAKE_CASE :Any = summarize_book(get_openlibrary_data(f'''isbn/{isbn}''')) print('\n'.join(f'''{key}: {value}''' for key, value in book_summary.items())) except JSONDecodeError: # Workaround for requests.exceptions.RequestException: print(f'''Sorry, there are no results for ISBN: {isbn}.''')
55
1
def UpperCAmelCase ( a_ ) -> int: """simple docstring""" __A = [] __A = set({"(", "[", "{"} ) __A = set({")", "]", "}"} ) __A = {"{": "}", "[": "]", "(": ")"} for i in range(len(a_ ) ): if s[i] in open_brackets: stack.append(s[i] ) elif s[i] in closed_brackets and ( len(a_ ) == 0 or (len(a_ ) > 0 and open_to_closed[stack.pop()] != s[i]) ): return False return len(a_ ) == 0 def UpperCAmelCase ( ) -> Optional[Any]: """simple docstring""" __A = input("Enter sequence of brackets: " ) if is_balanced(a_ ): print(a_ , "is balanced" ) else: print(a_ , "is not balanced" ) if __name__ == "__main__": main()
55
import requests SCREAMING_SNAKE_CASE :List[str] = 'YOUR API KEY' def UpperCAmelCase ( a_ , a_ = giphy_api_key ) -> list: """simple docstring""" __A = "+".join(query.split() ) __A = F'''https://api.giphy.com/v1/gifs/search?q={formatted_query}&api_key={api_key}''' __A = requests.get(a_ ).json()["data"] return [gif["url"] for gif in gifs] if __name__ == "__main__": print('\n'.join(get_gifs('space ship')))
55
1
import unittest import numpy as np from datasets import load_dataset 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 BeitImageProcessor class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self : Any ,A : List[str] ,A : str=7 ,A : Optional[Any]=3 ,A : Any=18 ,A : int=30 ,A : int=4_00 ,A : List[str]=True ,A : Union[str, Any]=None ,A : Union[str, Any]=True ,A : Tuple=None ,A : Tuple=True ,A : Union[str, Any]=[0.5, 0.5, 0.5] ,A : str=[0.5, 0.5, 0.5] ,A : List[Any]=False ,): __A = size if size is not None else {"height": 20, "width": 20} __A = crop_size if crop_size is not None else {"height": 18, "width": 18} __A = parent __A = batch_size __A = num_channels __A = image_size __A = min_resolution __A = max_resolution __A = do_resize __A = size __A = do_center_crop __A = crop_size __A = do_normalize __A = image_mean __A = image_std __A = do_reduce_labels def UpperCamelCase_ ( self : List[str] ): return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_reduce_labels": self.do_reduce_labels, } def UpperCAmelCase ( ) -> int: """simple docstring""" __A = load_dataset("hf-internal-testing/fixtures_ade20k" , split="test" ) __A = Image.open(dataset[0]["file"] ) __A = Image.open(dataset[1]["file"] ) return image, map def UpperCAmelCase ( ) -> Optional[int]: """simple docstring""" __A = load_dataset("hf-internal-testing/fixtures_ade20k" , split="test" ) __A = Image.open(ds[0]["file"] ) __A = Image.open(ds[1]["file"] ) __A = Image.open(ds[2]["file"] ) __A = Image.open(ds[3]["file"] ) return [imagea, imagea], [mapa, mapa] @require_torch @require_vision class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = BeitImageProcessor if is_vision_available() else None def UpperCamelCase_ ( self : List[Any] ): __A = BeitImageProcessingTester(self ) @property def UpperCamelCase_ ( self : List[Any] ): return self.image_processor_tester.prepare_image_processor_dict() def UpperCamelCase_ ( self : int ): __A = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(A ,"do_resize" ) ) self.assertTrue(hasattr(A ,"size" ) ) self.assertTrue(hasattr(A ,"do_center_crop" ) ) self.assertTrue(hasattr(A ,"center_crop" ) ) self.assertTrue(hasattr(A ,"do_normalize" ) ) self.assertTrue(hasattr(A ,"image_mean" ) ) self.assertTrue(hasattr(A ,"image_std" ) ) def UpperCamelCase_ ( self : List[str] ): __A = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size ,{"height": 20, "width": 20} ) self.assertEqual(image_processor.crop_size ,{"height": 18, "width": 18} ) self.assertEqual(image_processor.do_reduce_labels ,A ) __A = self.image_processing_class.from_dict( self.image_processor_dict ,size=42 ,crop_size=84 ,reduce_labels=A ) self.assertEqual(image_processor.size ,{"height": 42, "width": 42} ) self.assertEqual(image_processor.crop_size ,{"height": 84, "width": 84} ) self.assertEqual(image_processor.do_reduce_labels ,A ) def UpperCamelCase_ ( self : List[Any] ): pass def UpperCamelCase_ ( self : Optional[int] ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __A = prepare_image_inputs(self.image_processor_tester ,equal_resolution=A ) for image in image_inputs: self.assertIsInstance(A ,Image.Image ) # Test not batched input __A = 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 __A = image_processing(A ,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 UpperCamelCase_ ( self : List[str] ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __A = prepare_image_inputs(self.image_processor_tester ,equal_resolution=A ,numpify=A ) for image in image_inputs: self.assertIsInstance(A ,np.ndarray ) # Test not batched input __A = 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 __A = image_processing(A ,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 UpperCamelCase_ ( self : int ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A = prepare_image_inputs(self.image_processor_tester ,equal_resolution=A ,torchify=A ) for image in image_inputs: self.assertIsInstance(A ,torch.Tensor ) # Test not batched input __A = 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 __A = image_processing(A ,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 UpperCamelCase_ ( self : str ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A = prepare_image_inputs(self.image_processor_tester ,equal_resolution=A ,torchify=A ) __A = [] for image in image_inputs: self.assertIsInstance(A ,torch.Tensor ) maps.append(torch.zeros(image.shape[-2:] ).long() ) # Test not batched input __A = image_processing(image_inputs[0] ,maps[0] ,return_tensors="pt" ) self.assertEqual( encoding["pixel_values"].shape ,( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,) self.assertEqual( encoding["labels"].shape ,( 1, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,) self.assertEqual(encoding["labels"].dtype ,torch.long ) self.assertTrue(encoding["labels"].min().item() >= 0 ) self.assertTrue(encoding["labels"].max().item() <= 2_55 ) # Test batched __A = image_processing(A ,A ,return_tensors="pt" ) self.assertEqual( encoding["pixel_values"].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"], ) ,) self.assertEqual( encoding["labels"].shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,) self.assertEqual(encoding["labels"].dtype ,torch.long ) self.assertTrue(encoding["labels"].min().item() >= 0 ) self.assertTrue(encoding["labels"].max().item() <= 2_55 ) # Test not batched input (PIL images) __A , __A = prepare_semantic_single_inputs() __A = image_processing(A ,A ,return_tensors="pt" ) self.assertEqual( encoding["pixel_values"].shape ,( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,) self.assertEqual( encoding["labels"].shape ,( 1, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,) self.assertEqual(encoding["labels"].dtype ,torch.long ) self.assertTrue(encoding["labels"].min().item() >= 0 ) self.assertTrue(encoding["labels"].max().item() <= 2_55 ) # Test batched input (PIL images) __A , __A = prepare_semantic_batch_inputs() __A = image_processing(A ,A ,return_tensors="pt" ) self.assertEqual( encoding["pixel_values"].shape ,( 2, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,) self.assertEqual( encoding["labels"].shape ,( 2, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,) self.assertEqual(encoding["labels"].dtype ,torch.long ) self.assertTrue(encoding["labels"].min().item() >= 0 ) self.assertTrue(encoding["labels"].max().item() <= 2_55 ) def UpperCamelCase_ ( self : Dict ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # ADE20k has 150 classes, and the background is included, so labels should be between 0 and 150 __A , __A = prepare_semantic_single_inputs() __A = image_processing(A ,A ,return_tensors="pt" ) self.assertTrue(encoding["labels"].min().item() >= 0 ) self.assertTrue(encoding["labels"].max().item() <= 1_50 ) __A = True __A = image_processing(A ,A ,return_tensors="pt" ) self.assertTrue(encoding["labels"].min().item() >= 0 ) self.assertTrue(encoding["labels"].max().item() <= 2_55 )
55
import itertools import math def UpperCAmelCase ( a_ ) -> bool: """simple docstring""" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(a_ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def UpperCAmelCase ( ) -> Optional[Any]: """simple docstring""" __A = 2 while True: if is_prime(a_ ): yield num num += 1 def UpperCAmelCase ( a_ = 1_0_0_0_1 ) -> int: """simple docstring""" return next(itertools.islice(prime_generator() , nth - 1 , a_ ) ) if __name__ == "__main__": print(f'''{solution() = }''')
55
1
import fire from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoTokenizer from utils import SeqaSeqDataset, pickle_save def UpperCAmelCase ( a_ , a_ , a_=1_0_2_4 , a_=1_0_2_4 , a_=False , **a_ ) -> Union[str, Any]: """simple docstring""" __A = AutoTokenizer.from_pretrained(a_ ) __A = SeqaSeqDataset(a_ , a_ , a_ , a_ , type_path="train" , **a_ ) __A = tok.pad_token_id def get_lens(a_ ): __A = tqdm( DataLoader(a_ , batch_size=5_1_2 , num_workers=8 , shuffle=a_ , collate_fn=ds.collate_fn ) , desc=str(ds.len_file ) , ) __A = [] for batch in dl: __A = batch["input_ids"].ne(a_ ).sum(1 ).tolist() __A = batch["labels"].ne(a_ ).sum(1 ).tolist() if consider_target: for src, tgt in zip(a_ , a_ ): max_lens.append(max(a_ , a_ ) ) else: max_lens.extend(a_ ) return max_lens __A = get_lens(a_ ) __A = SeqaSeqDataset(a_ , a_ , a_ , a_ , type_path="val" , **a_ ) __A = get_lens(a_ ) pickle_save(a_ , train_ds.len_file ) pickle_save(a_ , val_ds.len_file ) if __name__ == "__main__": fire.Fire(save_len_file)
55
import argparse import os import numpy as np import tensorflow as tf import torch from transformers import BertModel def UpperCAmelCase ( a_ , a_ , a_ ) -> List[str]: """simple docstring""" __A = ("dense.weight", "attention.self.query", "attention.self.key", "attention.self.value") __A = ( ("layer.", "layer_"), ("word_embeddings.weight", "word_embeddings"), ("position_embeddings.weight", "position_embeddings"), ("token_type_embeddings.weight", "token_type_embeddings"), (".", "/"), ("LayerNorm/weight", "LayerNorm/gamma"), ("LayerNorm/bias", "LayerNorm/beta"), ("weight", "kernel"), ) if not os.path.isdir(a_ ): os.makedirs(a_ ) __A = model.state_dict() def to_tf_var_name(a_ ): for patt, repl in iter(a_ ): __A = name.replace(a_ , a_ ) return F'''bert/{name}''' def create_tf_var(a_ , a_ , a_ ): __A = tf.dtypes.as_dtype(tensor.dtype ) __A = tf.get_variable(dtype=a_ , shape=tensor.shape , name=a_ , initializer=tf.zeros_initializer() ) session.run(tf.variables_initializer([tf_var] ) ) session.run(a_ ) return tf_var tf.reset_default_graph() with tf.Session() as session: for var_name in state_dict: __A = to_tf_var_name(a_ ) __A = state_dict[var_name].numpy() if any(x in var_name for x in tensors_to_transpose ): __A = torch_tensor.T __A = create_tf_var(tensor=a_ , name=a_ , session=a_ ) tf.keras.backend.set_value(a_ , a_ ) __A = session.run(a_ ) print(F'''Successfully created {tf_name}: {np.allclose(a_ , a_ )}''' ) __A = tf.train.Saver(tf.trainable_variables() ) saver.save(a_ , os.path.join(a_ , model_name.replace("-" , "_" ) + ".ckpt" ) ) def UpperCAmelCase ( a_=None ) -> List[Any]: """simple docstring""" __A = argparse.ArgumentParser() parser.add_argument("--model_name" , type=a_ , required=a_ , help="model name e.g. bert-base-uncased" ) parser.add_argument( "--cache_dir" , type=a_ , default=a_ , required=a_ , help="Directory containing pytorch model" ) parser.add_argument("--pytorch_model_path" , type=a_ , required=a_ , help="/path/to/<pytorch-model-name>.bin" ) parser.add_argument("--tf_cache_dir" , type=a_ , required=a_ , help="Directory in which to save tensorflow model" ) __A = parser.parse_args(a_ ) __A = BertModel.from_pretrained( pretrained_model_name_or_path=args.model_name , state_dict=torch.load(args.pytorch_model_path ) , cache_dir=args.cache_dir , ) convert_pytorch_checkpoint_to_tf(model=a_ , ckpt_dir=args.tf_cache_dir , model_name=args.model_name ) if __name__ == "__main__": main()
55
1
import tempfile import numpy as np import torch from transformers import AutoTokenizer, TaEncoderModel from diffusers import DDPMScheduler, UNetaDConditionModel from diffusers.models.attention_processor import AttnAddedKVProcessor from diffusers.pipelines.deepfloyd_if import IFWatermarker from diffusers.utils.testing_utils import torch_device from ..test_pipelines_common import to_np class UpperCAmelCase : '''simple docstring''' def UpperCamelCase_ ( self : Any ): torch.manual_seed(0 ) __A = TaEncoderModel.from_pretrained("hf-internal-testing/tiny-random-t5" ) torch.manual_seed(0 ) __A = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5" ) torch.manual_seed(0 ) __A = UNetaDConditionModel( sample_size=32 ,layers_per_block=1 ,block_out_channels=[32, 64] ,down_block_types=[ "ResnetDownsampleBlock2D", "SimpleCrossAttnDownBlock2D", ] ,mid_block_type="UNetMidBlock2DSimpleCrossAttn" ,up_block_types=["SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"] ,in_channels=3 ,out_channels=6 ,cross_attention_dim=32 ,encoder_hid_dim=32 ,attention_head_dim=8 ,addition_embed_type="text" ,addition_embed_type_num_heads=2 ,cross_attention_norm="group_norm" ,resnet_time_scale_shift="scale_shift" ,act_fn="gelu" ,) unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests torch.manual_seed(0 ) __A = DDPMScheduler( num_train_timesteps=10_00 ,beta_schedule="squaredcos_cap_v2" ,beta_start=0.00_01 ,beta_end=0.02 ,thresholding=A ,dynamic_thresholding_ratio=0.95 ,sample_max_value=1.0 ,prediction_type="epsilon" ,variance_type="learned_range" ,) torch.manual_seed(0 ) __A = IFWatermarker() return { "text_encoder": text_encoder, "tokenizer": tokenizer, "unet": unet, "scheduler": scheduler, "watermarker": watermarker, "safety_checker": None, "feature_extractor": None, } def UpperCamelCase_ ( self : int ): torch.manual_seed(0 ) __A = TaEncoderModel.from_pretrained("hf-internal-testing/tiny-random-t5" ) torch.manual_seed(0 ) __A = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5" ) torch.manual_seed(0 ) __A = UNetaDConditionModel( sample_size=32 ,layers_per_block=[1, 2] ,block_out_channels=[32, 64] ,down_block_types=[ "ResnetDownsampleBlock2D", "SimpleCrossAttnDownBlock2D", ] ,mid_block_type="UNetMidBlock2DSimpleCrossAttn" ,up_block_types=["SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"] ,in_channels=6 ,out_channels=6 ,cross_attention_dim=32 ,encoder_hid_dim=32 ,attention_head_dim=8 ,addition_embed_type="text" ,addition_embed_type_num_heads=2 ,cross_attention_norm="group_norm" ,resnet_time_scale_shift="scale_shift" ,act_fn="gelu" ,class_embed_type="timestep" ,mid_block_scale_factor=1.4_14 ,time_embedding_act_fn="gelu" ,time_embedding_dim=32 ,) unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests torch.manual_seed(0 ) __A = DDPMScheduler( num_train_timesteps=10_00 ,beta_schedule="squaredcos_cap_v2" ,beta_start=0.00_01 ,beta_end=0.02 ,thresholding=A ,dynamic_thresholding_ratio=0.95 ,sample_max_value=1.0 ,prediction_type="epsilon" ,variance_type="learned_range" ,) torch.manual_seed(0 ) __A = DDPMScheduler( num_train_timesteps=10_00 ,beta_schedule="squaredcos_cap_v2" ,beta_start=0.00_01 ,beta_end=0.02 ,) torch.manual_seed(0 ) __A = IFWatermarker() return { "text_encoder": text_encoder, "tokenizer": tokenizer, "unet": unet, "scheduler": scheduler, "image_noising_scheduler": image_noising_scheduler, "watermarker": watermarker, "safety_checker": None, "feature_extractor": None, } def UpperCamelCase_ ( self : List[str] ): __A = self.get_dummy_components() __A = self.pipeline_class(**A ) pipe.to(A ) pipe.set_progress_bar_config(disable=A ) __A = self.get_dummy_inputs(A ) __A = inputs["prompt"] __A = inputs["generator"] __A = inputs["num_inference_steps"] __A = inputs["output_type"] if "image" in inputs: __A = inputs["image"] else: __A = None if "mask_image" in inputs: __A = inputs["mask_image"] else: __A = None if "original_image" in inputs: __A = inputs["original_image"] else: __A = None __A , __A = pipe.encode_prompt(A ) # inputs with prompt converted to embeddings __A = { "prompt_embeds": prompt_embeds, "negative_prompt_embeds": negative_prompt_embeds, "generator": generator, "num_inference_steps": num_inference_steps, "output_type": output_type, } if image is not None: __A = image if mask_image is not None: __A = mask_image if original_image is not None: __A = original_image # set all optional components to None for optional_component in pipe._optional_components: setattr(A ,A ,A ) __A = pipe(**A )[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(A ) __A = self.pipeline_class.from_pretrained(A ) pipe_loaded.to(A ) pipe_loaded.set_progress_bar_config(disable=A ) pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests for optional_component in pipe._optional_components: self.assertTrue( getattr(A ,A ) is None ,f'''`{optional_component}` did not stay set to None after loading.''' ,) __A = self.get_dummy_inputs(A ) __A = inputs["generator"] __A = inputs["num_inference_steps"] __A = inputs["output_type"] # inputs with prompt converted to embeddings __A = { "prompt_embeds": prompt_embeds, "negative_prompt_embeds": negative_prompt_embeds, "generator": generator, "num_inference_steps": num_inference_steps, "output_type": output_type, } if image is not None: __A = image if mask_image is not None: __A = mask_image if original_image is not None: __A = original_image __A = pipe_loaded(**A )[0] __A = np.abs(to_np(A ) - to_np(A ) ).max() self.assertLess(A ,1E-4 ) def UpperCamelCase_ ( self : Any ): __A = self.get_dummy_components() __A = self.pipeline_class(**A ) pipe.to(A ) pipe.set_progress_bar_config(disable=A ) __A = self.get_dummy_inputs(A ) __A = pipe(**A )[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(A ) __A = self.pipeline_class.from_pretrained(A ) pipe_loaded.to(A ) pipe_loaded.set_progress_bar_config(disable=A ) pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests __A = self.get_dummy_inputs(A ) __A = pipe_loaded(**A )[0] __A = np.abs(to_np(A ) - to_np(A ) ).max() self.assertLess(A ,1E-4 )
55
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE :Any = { 'configuration_pegasus_x': ['PEGASUS_X_PRETRAINED_CONFIG_ARCHIVE_MAP', 'PegasusXConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE :Any = [ 'PEGASUS_X_PRETRAINED_MODEL_ARCHIVE_LIST', 'PegasusXForConditionalGeneration', 'PegasusXModel', 'PegasusXPreTrainedModel', ] if TYPE_CHECKING: from .configuration_pegasus_x import PEGASUS_X_PRETRAINED_CONFIG_ARCHIVE_MAP, PegasusXConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pegasus_x import ( PEGASUS_X_PRETRAINED_MODEL_ARCHIVE_LIST, PegasusXForConditionalGeneration, PegasusXModel, PegasusXPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE :Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
55
1
import inspect from typing import Callable, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import DiffusionPipeline from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import logging SCREAMING_SNAKE_CASE :Optional[int] = logging.get_logger(__name__) # pylint: disable=invalid-name class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self : Optional[Any] ,A : AutoencoderKL ,A : CLIPTextModel ,A : CLIPTokenizer ,A : UNetaDConditionModel ,A : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] ,A : StableDiffusionSafetyChecker ,A : CLIPImageProcessor ,): super().__init__() self.register_modules( vae=A ,text_encoder=A ,tokenizer=A ,unet=A ,scheduler=A ,safety_checker=A ,feature_extractor=A ,) def UpperCamelCase_ ( self : Tuple ,A : Optional[Union[str, int]] = "auto" ): if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory __A = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(A ) def UpperCamelCase_ ( self : Tuple ): self.enable_attention_slicing(A ) @torch.no_grad() def __call__( self : Dict ,A : Union[str, List[str]] ,A : int = 5_12 ,A : int = 5_12 ,A : int = 50 ,A : float = 7.5 ,A : Optional[Union[str, List[str]]] = None ,A : Optional[int] = 1 ,A : float = 0.0 ,A : Optional[torch.Generator] = None ,A : Optional[torch.FloatTensor] = None ,A : Optional[str] = "pil" ,A : bool = True ,A : Optional[Callable[[int, int, torch.FloatTensor], None]] = None ,A : int = 1 ,A : Optional[torch.FloatTensor] = None ,**A : Optional[Any] ,): if isinstance(A ,A ): __A = 1 elif isinstance(A ,A ): __A = len(A ) else: raise ValueError(f'''`prompt` has to be of type `str` or `list` but is {type(A )}''' ) 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(A ,A ) or callback_steps <= 0) ): raise ValueError( f'''`callback_steps` has to be a positive integer but is {callback_steps} of type''' f''' {type(A )}.''' ) # get prompt text embeddings __A = self.tokenizer( A ,padding="max_length" ,max_length=self.tokenizer.model_max_length ,return_tensors="pt" ,) __A = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: __A = 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}''' ) __A = text_input_ids[:, : self.tokenizer.model_max_length] if text_embeddings is None: __A = self.text_encoder(text_input_ids.to(self.device ) )[0] # duplicate text embeddings for each generation per prompt, using mps friendly method __A , __A , __A = text_embeddings.shape __A = text_embeddings.repeat(1 ,A ,1 ) __A = text_embeddings.view(bs_embed * num_images_per_prompt ,A ,-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. __A = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: __A = 42 if negative_prompt is None: __A = [""] elif type(A ) is not type(A ): raise TypeError( f'''`negative_prompt` should be the same type to `prompt`, but got {type(A )} !=''' f''' {type(A )}.''' ) elif isinstance(A ,A ): __A = [negative_prompt] elif batch_size != len(A ): raise ValueError( f'''`negative_prompt`: {negative_prompt} has batch size {len(A )}, but `prompt`:''' f''' {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches''' " the batch size of `prompt`." ) else: __A = negative_prompt __A = text_input_ids.shape[-1] __A = self.tokenizer( A ,padding="max_length" ,max_length=A ,truncation=A ,return_tensors="pt" ,) __A = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt, using mps friendly method __A = uncond_embeddings.shape[1] __A = uncond_embeddings.repeat(A ,A ,1 ) __A = uncond_embeddings.view(batch_size * num_images_per_prompt ,A ,-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 __A = torch.cat([uncond_embeddings, text_embeddings] ) # get the initial random noise unless the user supplied it # Unlike in other pipelines, latents need to be generated in the target device # for 1-to-1 results reproducibility with the CompVis implementation. # However this currently doesn't work in `mps`. __A = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8) __A = (batch_size * num_images_per_prompt, self.unet.config.in_channels, 64, 64) __A = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not exist on mps __A = torch.randn( A ,generator=A ,device="cpu" ,dtype=A ).to(self.device ) __A = torch.randn(A ,generator=A ,device="cpu" ,dtype=A ).to( self.device ) else: __A = torch.randn( A ,generator=A ,device=self.device ,dtype=A ) __A = torch.randn(A ,generator=A ,device=self.device ,dtype=A ) else: if latents_reference.shape != latents_shape: raise ValueError(f'''Unexpected latents shape, got {latents.shape}, expected {latents_shape}''' ) __A = latents_reference.to(self.device ) __A = latents.to(self.device ) # This is the key part of the pipeline where we # try to ensure that the generated images w/ the same seed # but different sizes actually result in similar images __A = (latents_shape[3] - latents_shape_reference[3]) // 2 __A = (latents_shape[2] - latents_shape_reference[2]) // 2 __A = latents_shape_reference[3] if dx >= 0 else latents_shape_reference[3] + 2 * dx __A = latents_shape_reference[2] if dy >= 0 else latents_shape_reference[2] + 2 * dy __A = 0 if dx < 0 else dx __A = 0 if dy < 0 else dy __A = max(-dx ,0 ) __A = max(-dy ,0 ) # import pdb # pdb.set_trace() __A = latents_reference[:, :, dy : dy + h, dx : dx + w] # set timesteps self.scheduler.set_timesteps(A ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand __A = self.scheduler.timesteps.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler __A = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] __A = "eta" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) __A = {} if accepts_eta: __A = eta for i, t in enumerate(self.progress_bar(A ) ): # expand the latents if we are doing classifier free guidance __A = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents __A = self.scheduler.scale_model_input(A ,A ) # predict the noise residual __A = self.unet(A ,A ,encoder_hidden_states=A ).sample # perform guidance if do_classifier_free_guidance: __A , __A = noise_pred.chunk(2 ) __A = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # compute the previous noisy sample x_t -> x_t-1 __A = self.scheduler.step(A ,A ,A ,**A ).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(A ,A ,A ) __A = 1 / 0.1_82_15 * latents __A = self.vae.decode(A ).sample __A = (image / 2 + 0.5).clamp(0 ,1 ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 __A = image.cpu().permute(0 ,2 ,3 ,1 ).float().numpy() if self.safety_checker is not None: __A = self.feature_extractor(self.numpy_to_pil(A ) ,return_tensors="pt" ).to( self.device ) __A , __A = self.safety_checker( images=A ,clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype ) ) else: __A = None if output_type == "pil": __A = self.numpy_to_pil(A ) if not return_dict: return (image, has_nsfw_concept) return StableDiffusionPipelineOutput(images=A ,nsfw_content_detected=A )
55
from __future__ import annotations from collections.abc import Generator import requests from bsa import BeautifulSoup SCREAMING_SNAKE_CASE :int = 'https://www.indeed.co.in/jobs?q=mobile+app+development&l=' def UpperCAmelCase ( a_ = "mumbai" ) -> Generator[tuple[str, str], None, None]: """simple docstring""" __A = BeautifulSoup(requests.get(url + location ).content , "html.parser" ) # This attribute finds out all the specifics listed in a job for job in soup.find_all("div" , attrs={"data-tn-component": "organicJob"} ): __A = job.find("a" , attrs={"data-tn-element": "jobTitle"} ).text.strip() __A = job.find("span" , {"class": "company"} ).text.strip() yield job_title, company_name if __name__ == "__main__": for i, job in enumerate(fetch_jobs('Bangalore'), 1): print(f'''Job {i:>2} is {job[0]} at {job[1]}''')
55
1
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 how to properly calculate the metrics on the # validation dataset when in a distributed system, 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 :Tuple = 16 SCREAMING_SNAKE_CASE :List[str] = 32 def UpperCAmelCase ( a_ , a_ = 1_6 ) -> Union[str, Any]: """simple docstring""" __A = AutoTokenizer.from_pretrained("bert-base-cased" ) __A = load_dataset("glue" , "mrpc" ) def tokenize_function(a_ ): # max_length=None => use the model max length (it's actually the default) __A = tokenizer(examples["sentence1"] , examples["sentence2"] , truncation=a_ , max_length=a_ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): __A = datasets.map( a_ , batched=a_ , 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 __A = tokenized_datasets.rename_column("label" , "labels" ) def collate_fn(a_ ): # On TPU it's best to pad everything to the same length or training will be very slow. __A = 1_2_8 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": __A = 1_6 elif accelerator.mixed_precision != "no": __A = 8 else: __A = None return tokenizer.pad( a_ , padding="longest" , max_length=a_ , pad_to_multiple_of=a_ , return_tensors="pt" , ) # Instantiate dataloaders. __A = DataLoader( tokenized_datasets["train"] , shuffle=a_ , collate_fn=a_ , batch_size=a_ ) __A = DataLoader( tokenized_datasets["validation"] , shuffle=a_ , collate_fn=a_ , batch_size=a_ ) 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 :str = mocked_dataloaders # noqa: F811 def UpperCAmelCase ( a_ , a_ ) -> Optional[Any]: """simple docstring""" if os.environ.get("TESTING_MOCKED_DATALOADERS" , a_ ) == "1": __A = 2 # Initialize accelerator __A = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs __A = config["lr"] __A = int(config["num_epochs"] ) __A = int(config["seed"] ) __A = int(config["batch_size"] ) __A = evaluate.load("glue" , "mrpc" ) # If the batch size is too big we use gradient accumulation __A = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: __A = batch_size // MAX_GPU_BATCH_SIZE __A = MAX_GPU_BATCH_SIZE set_seed(a_ ) __A , __A = get_dataloaders(a_ , a_ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) __A = AutoModelForSequenceClassification.from_pretrained("bert-base-cased" , return_dict=a_ ) # 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). __A = model.to(accelerator.device ) # Instantiate optimizer __A = AdamW(params=model.parameters() , lr=a_ ) # Instantiate scheduler __A = get_linear_schedule_with_warmup( optimizer=a_ , num_warmup_steps=1_0_0 , num_training_steps=(len(a_ ) * 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. __A , __A , __A , __A , __A = accelerator.prepare( a_ , a_ , a_ , a_ , a_ ) # Now we train the model for epoch in range(a_ ): model.train() for step, batch in enumerate(a_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) __A = model(**a_ ) __A = outputs.loss __A = loss / gradient_accumulation_steps accelerator.backward(a_ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() __A = 0 for step, batch in enumerate(a_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): __A = model(**a_ ) __A = outputs.logits.argmax(dim=-1 ) __A , __A = accelerator.gather((predictions, batch["labels"]) ) # New Code # # First we check if it's a distributed system if accelerator.use_distributed: # Then see if we're on the last batch of our eval dataloader if step == len(a_ ) - 1: # Last batch needs to be truncated on distributed systems as it contains additional samples __A = predictions[: len(eval_dataloader.dataset ) - samples_seen] __A = references[: len(eval_dataloader.dataset ) - samples_seen] else: # Otherwise we add the number of samples seen samples_seen += references.shape[0] # All of this can be avoided if you use `Accelerator.gather_for_metrics` instead of `Accelerator.gather`: # accelerator.gather_for_metrics((predictions, batch["labels"])) metric.add_batch( predictions=a_ , references=a_ , ) __A = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'''epoch {epoch}:''' , a_ ) def UpperCAmelCase ( ) -> Tuple: """simple docstring""" __A = argparse.ArgumentParser(description="Simple example of training script." ) parser.add_argument( "--mixed_precision" , type=a_ , default=a_ , 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." ) __A = parser.parse_args() __A = {"lr": 2E-5, "num_epochs": 3, "seed": 4_2, "batch_size": 1_6} training_function(a_ , a_ ) if __name__ == "__main__": main()
55
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, BlipaProcessor, BlipImageProcessor, GPTaTokenizer, PreTrainedTokenizerFast @require_vision class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase_ ( self : List[str] ): __A = tempfile.mkdtemp() __A = BlipImageProcessor() __A = GPTaTokenizer.from_pretrained("hf-internal-testing/tiny-random-GPT2Model" ) __A = BlipaProcessor(A ,A ) processor.save_pretrained(self.tmpdirname ) def UpperCamelCase_ ( self : Dict ,**A : int ): return AutoProcessor.from_pretrained(self.tmpdirname ,**A ).tokenizer def UpperCamelCase_ ( self : Dict ,**A : Optional[int] ): return AutoProcessor.from_pretrained(self.tmpdirname ,**A ).image_processor def UpperCamelCase_ ( self : Dict ): shutil.rmtree(self.tmpdirname ) def UpperCamelCase_ ( self : Optional[int] ): __A = [np.random.randint(2_55 ,size=(3, 30, 4_00) ,dtype=np.uinta )] __A = [Image.fromarray(np.moveaxis(A ,0 ,-1 ) ) for x in image_inputs] return image_inputs def UpperCamelCase_ ( self : Any ): __A = BlipaProcessor(tokenizer=self.get_tokenizer() ,image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __A = self.get_tokenizer(bos_token="(BOS)" ,eos_token="(EOS)" ) __A = self.get_image_processor(do_normalize=A ,padding_value=1.0 ) __A = BlipaProcessor.from_pretrained( self.tmpdirname ,bos_token="(BOS)" ,eos_token="(EOS)" ,do_normalize=A ,padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() ,tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer ,A ) self.assertEqual(processor.image_processor.to_json_string() ,image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor ,A ) def UpperCamelCase_ ( self : List[Any] ): __A = self.get_image_processor() __A = self.get_tokenizer() __A = BlipaProcessor(tokenizer=A ,image_processor=A ) __A = self.prepare_image_inputs() __A = image_processor(A ,return_tensors="np" ) __A = processor(images=A ,return_tensors="np" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() ,input_processor[key].sum() ,delta=1E-2 ) def UpperCamelCase_ ( self : Tuple ): __A = self.get_image_processor() __A = self.get_tokenizer() __A = BlipaProcessor(tokenizer=A ,image_processor=A ) __A = "lower newer" __A = processor(text=A ) __A = tokenizer(A ,return_token_type_ids=A ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] ,encoded_processor[key] ) def UpperCamelCase_ ( self : int ): __A = self.get_image_processor() __A = self.get_tokenizer() __A = BlipaProcessor(tokenizer=A ,image_processor=A ) __A = "lower newer" __A = self.prepare_image_inputs() __A = processor(text=A ,images=A ) self.assertListEqual(list(inputs.keys() ) ,["pixel_values", "input_ids", "attention_mask"] ) # test if it raises when no input is passed with pytest.raises(A ): processor() def UpperCamelCase_ ( self : Optional[Any] ): __A = self.get_image_processor() __A = self.get_tokenizer() __A = BlipaProcessor(tokenizer=A ,image_processor=A ) __A = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __A = processor.batch_decode(A ) __A = tokenizer.batch_decode(A ) self.assertListEqual(A ,A ) def UpperCamelCase_ ( self : Optional[Any] ): __A = self.get_image_processor() __A = self.get_tokenizer() __A = BlipaProcessor(tokenizer=A ,image_processor=A ) __A = "lower newer" __A = self.prepare_image_inputs() __A = processor(text=A ,images=A ) # For now the processor supports only ['pixel_values', 'input_ids', 'attention_mask'] self.assertListEqual(list(inputs.keys() ) ,["pixel_values", "input_ids", "attention_mask"] )
55
1
from math import sqrt def UpperCAmelCase ( a_ ) -> bool: """simple docstring""" assert isinstance(a_ , a_ ) and ( number >= 0 ), "'number' must been an int and positive" __A = True # 0 and 1 are none primes. if number <= 1: __A = False for divisor in range(2 , int(round(sqrt(a_ ) ) ) + 1 ): # if 'number' divisible by 'divisor' then sets 'status' # of false and break up the loop. if number % divisor == 0: __A = False break # precondition assert isinstance(a_ , a_ ), "'status' must been from type bool" return status def UpperCAmelCase ( a_ ) -> Any: """simple docstring""" assert isinstance(a_ , a_ ) and (n > 2), "'N' must been an int and > 2" # beginList: contains all natural numbers from 2 up to N __A = list(range(2 , n + 1 ) ) __A = [] # this list will be returns. # actual sieve of erathostenes for i in range(len(a_ ) ): for j in range(i + 1 , len(a_ ) ): if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0): __A = 0 # filters actual prime numbers. __A = [x for x in begin_list if x != 0] # precondition assert isinstance(a_ , a_ ), "'ans' must been from type list" return ans def UpperCAmelCase ( a_ ) -> Optional[int]: """simple docstring""" assert isinstance(a_ , a_ ) and (n > 2), "'N' must been an int and > 2" __A = [] # iterates over all numbers between 2 up to N+1 # if a number is prime then appends to list 'ans' for number in range(2 , n + 1 ): if is_prime(a_ ): ans.append(a_ ) # precondition assert isinstance(a_ , a_ ), "'ans' must been from type list" return ans def UpperCAmelCase ( a_ ) -> Optional[int]: """simple docstring""" assert isinstance(a_ , a_ ) and number >= 0, "'number' must been an int and >= 0" __A = [] # this list will be returns of the function. # potential prime number factors. __A = 2 __A = number if number == 0 or number == 1: ans.append(a_ ) # if 'number' not prime then builds the prime factorization of 'number' elif not is_prime(a_ ): while quotient != 1: if is_prime(a_ ) and (quotient % factor == 0): ans.append(a_ ) quotient /= factor else: factor += 1 else: ans.append(a_ ) # precondition assert isinstance(a_ , a_ ), "'ans' must been from type list" return ans def UpperCAmelCase ( a_ ) -> Any: """simple docstring""" assert isinstance(a_ , a_ ) and ( number >= 0 ), "'number' bust been an int and >= 0" __A = 0 # prime factorization of 'number' __A = prime_factorization(a_ ) __A = max(a_ ) # precondition assert isinstance(a_ , a_ ), "'ans' must been from type int" return ans def UpperCAmelCase ( a_ ) -> Optional[Any]: """simple docstring""" assert isinstance(a_ , a_ ) and ( number >= 0 ), "'number' bust been an int and >= 0" __A = 0 # prime factorization of 'number' __A = prime_factorization(a_ ) __A = min(a_ ) # precondition assert isinstance(a_ , a_ ), "'ans' must been from type int" return ans def UpperCAmelCase ( a_ ) -> int: """simple docstring""" assert isinstance(a_ , a_ ), "'number' must been an int" assert isinstance(number % 2 == 0 , a_ ), "compare bust been from type bool" return number % 2 == 0 def UpperCAmelCase ( a_ ) -> List[Any]: """simple docstring""" assert isinstance(a_ , a_ ), "'number' must been an int" assert isinstance(number % 2 != 0 , a_ ), "compare bust been from type bool" return number % 2 != 0 def UpperCAmelCase ( a_ ) -> Optional[Any]: """simple docstring""" assert ( isinstance(a_ , a_ ) and (number > 2) and is_even(a_ ) ), "'number' must been an int, even and > 2" __A = [] # this list will returned # creates a list of prime numbers between 2 up to 'number' __A = get_prime_numbers(a_ ) __A = len(a_ ) # run variable for while-loops. __A = 0 __A = None # exit variable. for break up the loops __A = True while i < len_pn and loop: __A = i + 1 while j < len_pn and loop: if prime_numbers[i] + prime_numbers[j] == number: __A = False ans.append(prime_numbers[i] ) ans.append(prime_numbers[j] ) j += 1 i += 1 # precondition assert ( isinstance(a_ , a_ ) and (len(a_ ) == 2) and (ans[0] + ans[1] == number) and is_prime(ans[0] ) and is_prime(ans[1] ) ), "'ans' must contains two primes. And sum of elements must been eq 'number'" return ans def UpperCAmelCase ( a_ , a_ ) -> Optional[Any]: """simple docstring""" assert ( isinstance(a_ , a_ ) and isinstance(a_ , a_ ) and (numbera >= 0) and (numbera >= 0) ), "'number1' and 'number2' must been positive integer." __A = 0 while numbera != 0: __A = numbera % numbera __A = numbera __A = rest # precondition assert isinstance(a_ , a_ ) and ( numbera >= 0 ), "'number' must been from type int and positive" return numbera def UpperCAmelCase ( a_ , a_ ) -> List[str]: """simple docstring""" assert ( isinstance(a_ , a_ ) and isinstance(a_ , a_ ) and (numbera >= 1) and (numbera >= 1) ), "'number1' and 'number2' must been positive integer." __A = 1 # actual answer that will be return. # for kgV (x,1) if numbera > 1 and numbera > 1: # builds the prime factorization of 'number1' and 'number2' __A = prime_factorization(a_ ) __A = prime_factorization(a_ ) elif numbera == 1 or numbera == 1: __A = [] __A = [] __A = max(a_ , a_ ) __A = 0 __A = 0 __A = [] # captured numbers int both 'primeFac1' and 'primeFac2' # iterates through primeFac1 for n in prime_fac_a: if n not in done: if n in prime_fac_a: __A = prime_fac_a.count(a_ ) __A = prime_fac_a.count(a_ ) for _ in range(max(a_ , a_ ) ): ans *= n else: __A = prime_fac_a.count(a_ ) for _ in range(a_ ): ans *= n done.append(a_ ) # iterates through primeFac2 for n in prime_fac_a: if n not in done: __A = prime_fac_a.count(a_ ) for _ in range(a_ ): ans *= n done.append(a_ ) # precondition assert isinstance(a_ , a_ ) and ( ans >= 0 ), "'ans' must been from type int and positive" return ans def UpperCAmelCase ( a_ ) -> str: """simple docstring""" assert isinstance(a_ , a_ ) and (n >= 0), "'number' must been a positive int" __A = 0 __A = 2 # this variable holds the answer while index < n: index += 1 ans += 1 # counts to the next number # if ans not prime then # runs to the next prime number. while not is_prime(a_ ): ans += 1 # precondition assert isinstance(a_ , a_ ) and is_prime( a_ ), "'ans' must been a prime number and from type int" return ans def UpperCAmelCase ( a_ , a_ ) -> Tuple: """simple docstring""" assert ( is_prime(a_ ) and is_prime(a_ ) and (p_number_a < p_number_a) ), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'" __A = p_number_a + 1 # jump to the next number __A = [] # this list will be returns. # if number is not prime then # fetch the next prime number. while not is_prime(a_ ): number += 1 while number < p_number_a: ans.append(a_ ) number += 1 # fetch the next prime number. while not is_prime(a_ ): number += 1 # precondition assert ( isinstance(a_ , a_ ) and ans[0] != p_number_a and ans[len(a_ ) - 1] != p_number_a ), "'ans' must been a list without the arguments" # 'ans' contains not 'pNumber1' and 'pNumber2' ! return ans def UpperCAmelCase ( a_ ) -> str: """simple docstring""" assert isinstance(a_ , a_ ) and (n >= 1), "'n' must been int and >= 1" __A = [] # will be returned. for divisor in range(1 , n + 1 ): if n % divisor == 0: ans.append(a_ ) # precondition assert ans[0] == 1 and ans[len(a_ ) - 1] == n, "Error in function getDivisiors(...)" return ans def UpperCAmelCase ( a_ ) -> Dict: """simple docstring""" assert isinstance(a_ , a_ ) and ( number > 1 ), "'number' must been an int and >= 1" __A = get_divisors(a_ ) # precondition assert ( isinstance(a_ , a_ ) and (divisors[0] == 1) and (divisors[len(a_ ) - 1] == number) ), "Error in help-function getDivisiors(...)" # summed all divisors up to 'number' (exclusive), hence [:-1] return sum(divisors[:-1] ) == number def UpperCAmelCase ( a_ , a_ ) -> str: """simple docstring""" assert ( isinstance(a_ , a_ ) and isinstance(a_ , a_ ) and (denominator != 0) ), "The arguments must been from type int and 'denominator' != 0" # build the greatest common divisor of numerator and denominator. __A = gcd(abs(a_ ) , abs(a_ ) ) # precondition assert ( isinstance(a_ , a_ ) and (numerator % gcd_of_fraction == 0) and (denominator % gcd_of_fraction == 0) ), "Error in function gcd(...,...)" return (numerator // gcd_of_fraction, denominator // gcd_of_fraction) def UpperCAmelCase ( a_ ) -> Optional[int]: """simple docstring""" assert isinstance(a_ , a_ ) and (n >= 0), "'n' must been a int and >= 0" __A = 1 # this will be return. for factor in range(1 , n + 1 ): ans *= factor return ans def UpperCAmelCase ( a_ ) -> List[Any]: """simple docstring""" assert isinstance(a_ , a_ ) and (n >= 0), "'n' must been an int and >= 0" __A = 0 __A = 1 __A = 1 # this will be return for _ in range(n - 1 ): __A = ans ans += fiba __A = tmp return ans
55
import logging import torch from accelerate import Accelerator from arguments import EvaluationArguments from datasets import load_dataset from torch.utils.data import IterableDataset from torch.utils.data.dataloader import DataLoader from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, set_seed class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self : int ,A : Any ,A : List[str] ,A : Union[str, Any]=10_24 ,A : int=10_24 ,A : Optional[Any]=3.6 ): __A = tokenizer __A = tokenizer.bos_token_id __A = dataset __A = seq_length __A = seq_length * chars_per_token * num_of_sequences def __iter__( self : List[Any] ): __A = iter(self.dataset ) __A = True while more_examples: __A , __A = [], 0 while True: if buffer_len >= self.input_characters: break try: buffer.append(next(A )["content"] ) buffer_len += len(buffer[-1] ) except StopIteration: __A = False break __A = tokenizer(A ,truncation=A )["input_ids"] __A = [] for tokenized_input in tokenized_inputs: all_token_ids.extend(tokenized_input + [self.concat_token_id] ) for i in range(0 ,len(A ) ,self.seq_length ): __A = all_token_ids[i : i + self.seq_length] if len(A ) == self.seq_length: yield torch.tensor(A ) def UpperCAmelCase ( a_ ) -> Optional[int]: """simple docstring""" __A = {"streaming": True} __A = load_dataset(args.dataset_name , split="train" , **a_ ) __A = ConstantLengthDataset(a_ , a_ , seq_length=args.seq_length ) __A = DataLoader(a_ , batch_size=args.batch_size ) return eval_dataloader def UpperCAmelCase ( a_ ) -> Union[str, Any]: """simple docstring""" model.eval() __A = [] for step, batch in enumerate(a_ ): with torch.no_grad(): __A = model(a_ , labels=a_ ) __A = outputs.loss.repeat(args.batch_size ) losses.append(accelerator.gather(a_ ) ) if args.max_eval_steps > 0 and step >= args.max_eval_steps: break __A = torch.mean(torch.cat(a_ ) ) try: __A = torch.exp(a_ ) except OverflowError: __A = float("inf" ) return loss.item(), perplexity.item() # Setup Accelerator SCREAMING_SNAKE_CASE :Optional[int] = Accelerator() # Parse configuration SCREAMING_SNAKE_CASE :str = HfArgumentParser(EvaluationArguments) SCREAMING_SNAKE_CASE :int = parser.parse_args() set_seed(args.seed) # Logging SCREAMING_SNAKE_CASE :Dict = logging.getLogger(__name__) logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO ) # Load model and tokenizer SCREAMING_SNAKE_CASE :List[Any] = AutoModelForCausalLM.from_pretrained(args.model_ckpt) SCREAMING_SNAKE_CASE :int = AutoTokenizer.from_pretrained(args.model_ckpt) # Load dataset and dataloader SCREAMING_SNAKE_CASE :List[str] = create_dataloader(args) # Prepare everything with our `accelerator`. SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE :List[Any] = accelerator.prepare(model, eval_dataloader) # Evaluate and save the last checkpoint logger.info('Evaluating and saving model after training') SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE :List[Any] = evaluate(args) logger.info(f'''loss/eval: {eval_loss}, perplexity: {perplexity}''')
55
1
import warnings from typing import Dict import numpy as np from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING def UpperCAmelCase ( a_ ) -> str: """simple docstring""" return 1.0 / (1.0 + np.exp(-_outputs )) def UpperCAmelCase ( a_ ) -> Optional[Any]: """simple docstring""" __A = np.max(_outputs , axis=-1 , keepdims=a_ ) __A = np.exp(_outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=a_ ) class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = "sigmoid" snake_case_ = "softmax" snake_case_ = "none" @add_end_docstrings( __SCREAMING_SNAKE_CASE , R"\n return_all_scores (`bool`, *optional*, defaults to `False`):\n Whether to return all prediction scores or just the one of the predicted class.\n function_to_apply (`str`, *optional*, defaults to `\"default\"`):\n The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:\n\n - `\"default\"`: if the model has a single label, will apply the sigmoid function on the output. If the model\n has several labels, will apply the softmax function on the output.\n - `\"sigmoid\"`: Applies the sigmoid function on the output.\n - `\"softmax\"`: Applies the softmax function on the output.\n - `\"none\"`: Does not apply any function on the output.\n " , ) class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = False snake_case_ = ClassificationFunction.NONE def __init__( self : Dict ,**A : Optional[int] ): super().__init__(**A ) self.check_model_type( TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if self.framework == "tf" else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING ) def UpperCamelCase_ ( self : Any ,A : Optional[int]=None ,A : str=None ,A : Dict="" ,**A : str ): # Using "" as default argument because we're going to use `top_k=None` in user code to declare # "No top_k" __A = tokenizer_kwargs __A = {} if hasattr(self.model.config ,"return_all_scores" ) and return_all_scores is None: __A = self.model.config.return_all_scores if isinstance(A ,A ) or top_k is None: __A = top_k __A = False elif return_all_scores is not None: warnings.warn( "`return_all_scores` is now deprecated, if want a similar functionality use `top_k=None` instead of" " `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`." ,A ,) if return_all_scores: __A = None else: __A = 1 if isinstance(A ,A ): __A = ClassificationFunction[function_to_apply.upper()] if function_to_apply is not None: __A = function_to_apply return preprocess_params, {}, postprocess_params def __call__( self : List[str] ,*A : Optional[Any] ,**A : Tuple ): __A = super().__call__(*A ,**A ) # TODO try and retrieve it in a nicer way from _sanitize_parameters. __A = "top_k" not in kwargs if isinstance(args[0] ,A ) and _legacy: # This pipeline is odd, and return a list when single item is run return [result] else: return result def UpperCamelCase_ ( self : Tuple ,A : Any ,**A : List[str] ): __A = self.framework if isinstance(A ,A ): return self.tokenizer(**A ,return_tensors=A ,**A ) elif isinstance(A ,A ) and len(A ) == 1 and isinstance(inputs[0] ,A ) and len(inputs[0] ) == 2: # It used to be valid to use a list of list of list for text pairs, keeping this path for BC return self.tokenizer( text=inputs[0][0] ,text_pair=inputs[0][1] ,return_tensors=A ,**A ) elif isinstance(A ,A ): # This is likely an invalid usage of the pipeline attempting to pass text pairs. raise ValueError( "The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a" " dictionary `{\"text\": \"My text\", \"text_pair\": \"My pair\"}` in order to send a text pair." ) return self.tokenizer(A ,return_tensors=A ,**A ) def UpperCamelCase_ ( self : List[Any] ,A : str ): return self.model(**A ) def UpperCamelCase_ ( self : Optional[Any] ,A : Any ,A : Tuple=None ,A : List[Any]=1 ,A : List[str]=True ): # `_legacy` is used to determine if we're running the naked pipeline and in backward # compatibility mode, or if running the pipeline with `pipeline(..., top_k=1)` we're running # the more natural result containing the list. # Default value before `set_parameters` if function_to_apply is None: if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1: __A = ClassificationFunction.SIGMOID elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1: __A = ClassificationFunction.SOFTMAX elif hasattr(self.model.config ,"function_to_apply" ) and function_to_apply is None: __A = self.model.config.function_to_apply else: __A = ClassificationFunction.NONE __A = model_outputs["logits"][0] __A = outputs.numpy() if function_to_apply == ClassificationFunction.SIGMOID: __A = sigmoid(A ) elif function_to_apply == ClassificationFunction.SOFTMAX: __A = softmax(A ) elif function_to_apply == ClassificationFunction.NONE: __A = outputs else: raise ValueError(f'''Unrecognized `function_to_apply` argument: {function_to_apply}''' ) if top_k == 1 and _legacy: return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()} __A = [ {"label": self.model.config.idalabel[i], "score": score.item()} for i, score in enumerate(A ) ] if not _legacy: dict_scores.sort(key=lambda A : x["score"] ,reverse=A ) if top_k is not None: __A = dict_scores[:top_k] return dict_scores
55
import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = LayoutLMTokenizer snake_case_ = LayoutLMTokenizerFast snake_case_ = True snake_case_ = True def UpperCamelCase_ ( self : Any ): super().setUp() __A = [ "[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest", ] __A = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file ,"w" ,encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) def UpperCamelCase_ ( self : Tuple ,**A : int ): return LayoutLMTokenizer.from_pretrained(self.tmpdirname ,**A ) def UpperCamelCase_ ( self : Optional[Any] ,A : Any ): __A = "UNwant\u00E9d,running" __A = "unwanted, running" return input_text, output_text def UpperCamelCase_ ( self : str ): __A = self.tokenizer_class(self.vocab_file ) __A = tokenizer.tokenize("UNwant\u00E9d,running" ) self.assertListEqual(A ,["un", "##want", "##ed", ",", "runn", "##ing"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(A ) ,[7, 4, 5, 10, 8, 9] ) def UpperCamelCase_ ( self : int ): pass
55
1
from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE :Tuple = logging.get_logger(__name__) SCREAMING_SNAKE_CASE :Tuple = { 'facebook/nllb-moe-54B': 'https://huggingface.co/facebook/nllb-moe-54b/resolve/main/config.json', } class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = "nllb-moe" snake_case_ = ["past_key_values"] snake_case_ = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"} def __init__( self : Tuple ,A : Dict=12_81_12 ,A : Optional[Any]=10_24 ,A : List[Any]=12 ,A : Union[str, Any]=40_96 ,A : Dict=16 ,A : Optional[int]=12 ,A : Optional[int]=40_96 ,A : Optional[int]=16 ,A : List[Any]=0.05 ,A : List[Any]=0.05 ,A : Union[str, Any]=True ,A : Union[str, Any]=True ,A : Union[str, Any]="relu" ,A : Tuple=10_24 ,A : List[str]=0.1 ,A : Any=0.1 ,A : Tuple=0.0 ,A : Union[str, Any]=0.02 ,A : str=2 ,A : Any=True ,A : Dict=False ,A : int="float32" ,A : int=False ,A : Tuple=1_28 ,A : str=64 ,A : List[str]=4 ,A : Optional[Any]=4 ,A : Tuple=0.0_01 ,A : int=0.0_01 ,A : List[Any]="all" ,A : int=False ,A : str=False ,A : Optional[int]=1.0 ,A : str=0.2 ,A : Any=1 ,A : Optional[int]=0 ,A : List[str]=2 ,A : Union[str, Any]=False ,**A : Tuple ,): __A = vocab_size __A = max_position_embeddings __A = d_model __A = encoder_ffn_dim __A = encoder_layers __A = encoder_attention_heads __A = decoder_ffn_dim __A = decoder_layers __A = decoder_attention_heads __A = dropout __A = attention_dropout __A = activation_dropout __A = activation_function __A = init_std __A = encoder_layerdrop __A = decoder_layerdrop __A = use_cache __A = encoder_layers __A = scale_embedding # scale factor will be sqrt(d_model) if True __A = router_z_loss_coef __A = router_aux_loss_coef __A = decoder_sparse_step __A = encoder_sparse_step __A = num_experts __A = expert_capacity __A = router_bias if router_dtype not in ["float32", "float16", "bfloat16"]: raise ValueError(f'''`router_dtype` must be one of \'float32\', \'float16\' or \'bfloat16\', got {router_dtype}''' ) __A = router_dtype __A = router_ignore_padding_tokens __A = batch_prioritized_routing __A = second_expert_policy __A = normalize_router_prob_before_dropping __A = moe_eval_capacity_token_fraction __A = moe_token_dropout __A = output_router_logits super().__init__( pad_token_id=A ,bos_token_id=A ,eos_token_id=A ,is_encoder_decoder=A ,decoder_start_token_id=A ,**A ,)
55
SCREAMING_SNAKE_CASE :int = {str(digit): digit**5 for digit in range(10)} def UpperCAmelCase ( a_ ) -> int: """simple docstring""" return sum(DIGITS_FIFTH_POWER[digit] for digit in str(a_ ) ) def UpperCAmelCase ( ) -> int: """simple docstring""" return sum( number for number in range(1_0_0_0 , 1_0_0_0_0_0_0 ) if number == digits_fifth_powers_sum(a_ ) ) if __name__ == "__main__": print(solution())
55
1
import copy import re class UpperCAmelCase : '''simple docstring''' snake_case_ = "hp" snake_case_ = {} snake_case_ = None @classmethod def UpperCamelCase_ ( cls : Optional[Any] ,A : List[str] ,A : List[str] ): __A = prefix __A = defaults cls.build_naming_info() @staticmethod def UpperCamelCase_ ( A : str ,A : Optional[int] ): if len(A ) == 0: return "" __A = None if any(char.isdigit() for char in word ): raise Exception(f'''Parameters should not contain numbers: \'{word}\' contains a number''' ) if word in info["short_word"]: return info["short_word"][word] for prefix_len in range(1 ,len(A ) + 1 ): __A = word[:prefix_len] if prefix in info["reverse_short_word"]: continue else: __A = prefix break if short_word is None: # Paranoid fallback def int_to_alphabetic(A : Union[str, Any] ): __A = "" while integer != 0: __A = chr(ord("A" ) + integer % 10 ) + s integer //= 10 return s __A = 0 while True: __A = word + "#" + int_to_alphabetic(A ) if sword in info["reverse_short_word"]: continue else: __A = sword break __A = short_word __A = word return short_word @staticmethod def UpperCamelCase_ ( A : Tuple ,A : str ): __A = param_name.split("_" ) __A = [TrialShortNamer.shortname_for_word(A ,A ) for word in words] # We try to create a separatorless short name, but if there is a collision we have to fallback # to a separated short name __A = ["", "_"] for separator in separators: __A = separator.join(A ) if shortname not in info["reverse_short_param"]: __A = shortname __A = param_name return shortname return param_name @staticmethod def UpperCamelCase_ ( A : Union[str, Any] ,A : List[Any] ): __A = TrialShortNamer.shortname_for_key(A ,A ) __A = short_name __A = param_name @classmethod def UpperCamelCase_ ( cls : List[Any] ): if cls.NAMING_INFO is not None: return __A = { "short_word": {}, "reverse_short_word": {}, "short_param": {}, "reverse_short_param": {}, } __A = list(cls.DEFAULTS.keys() ) for k in field_keys: cls.add_new_param_name(A ,A ) __A = info @classmethod def UpperCamelCase_ ( cls : Union[str, Any] ,A : int ): cls.build_naming_info() assert cls.PREFIX is not None __A = [copy.copy(cls.PREFIX )] for k, v in params.items(): if k not in cls.DEFAULTS: raise Exception(f'''You should provide a default value for the param name {k} with value {v}''' ) if v == cls.DEFAULTS[k]: # The default value is not added to the name continue __A = cls.NAMING_INFO["short_param"][k] if isinstance(A ,A ): __A = 1 if v else 0 __A = "" if isinstance(A ,(int, float) ) else "-" __A = f'''{key}{sep}{v}''' name.append(A ) return "_".join(A ) @classmethod def UpperCamelCase_ ( cls : List[str] ,A : Tuple ): __A = repr[len(cls.PREFIX ) + 1 :] if repr == "": __A = [] else: __A = repr.split("_" ) __A = {} for value in values: if "-" in value: __A , __A = value.split("-" ) else: __A = re.sub("[0-9.]" ,"" ,A ) __A = float(re.sub("[^0-9.]" ,"" ,A ) ) __A = cls.NAMING_INFO["reverse_short_param"][p_k] __A = p_v for k in cls.DEFAULTS: if k not in parameters: __A = cls.DEFAULTS[k] return parameters
55
import inspect import unittest from transformers import MobileNetVaConfig 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 MobileNetVaForImageClassification, MobileNetVaModel from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileNetVaImageProcessor class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def UpperCamelCase_ ( self : Any ): __A = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(A ,"tf_padding" ) ) self.parent.assertTrue(hasattr(A ,"depth_multiplier" ) ) class UpperCAmelCase : '''simple docstring''' def __init__( self : Optional[Any] ,A : int ,A : List[Any]=13 ,A : int=3 ,A : Optional[Any]=32 ,A : Union[str, Any]=0.25 ,A : Tuple=8 ,A : Optional[int]=True ,A : Union[str, Any]=10_24 ,A : Any=32 ,A : Optional[int]="relu6" ,A : int=0.1 ,A : Optional[Any]=0.02 ,A : Optional[Any]=True ,A : List[str]=True ,A : str=10 ,A : str=None ,): __A = parent __A = batch_size __A = num_channels __A = image_size __A = depth_multiplier __A = min_depth __A = tf_padding __A = int(last_hidden_size * depth_multiplier ) __A = output_stride __A = hidden_act __A = classifier_dropout_prob __A = use_labels __A = is_training __A = num_labels __A = initializer_range __A = scope def UpperCamelCase_ ( self : Optional[int] ): __A = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __A = None __A = None if self.use_labels: __A = ids_tensor([self.batch_size] ,self.num_labels ) __A = ids_tensor([self.batch_size, self.image_size, self.image_size] ,self.num_labels ) __A = self.get_config() return config, pixel_values, labels, pixel_labels def UpperCamelCase_ ( self : Any ): return MobileNetVaConfig( num_channels=self.num_channels ,image_size=self.image_size ,depth_multiplier=self.depth_multiplier ,min_depth=self.min_depth ,tf_padding=self.tf_padding ,hidden_act=self.hidden_act ,classifier_dropout_prob=self.classifier_dropout_prob ,initializer_range=self.initializer_range ,) def UpperCamelCase_ ( self : Optional[int] ,A : str ,A : Tuple ,A : Optional[int] ,A : List[str] ): __A = MobileNetVaModel(config=A ) model.to(A ) model.eval() __A = model(A ) self.parent.assertEqual( result.last_hidden_state.shape ,( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) ,) def UpperCamelCase_ ( self : List[Any] ,A : Union[str, Any] ,A : List[Any] ,A : int ,A : Union[str, Any] ): __A = self.num_labels __A = MobileNetVaForImageClassification(A ) model.to(A ) model.eval() __A = model(A ,labels=A ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def UpperCamelCase_ ( self : Tuple ): __A = self.prepare_config_and_inputs() __A , __A , __A , __A = config_and_inputs __A = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = (MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else () snake_case_ = ( {"feature-extraction": MobileNetVaModel, "image-classification": MobileNetVaForImageClassification} if is_torch_available() else {} ) snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = False def UpperCamelCase_ ( self : Any ): __A = MobileNetVaModelTester(self ) __A = MobileNetVaConfigTester(self ,config_class=A ,has_text_modality=A ) def UpperCamelCase_ ( self : str ): self.config_tester.run_common_tests() @unittest.skip(reason="MobileNetV1 does not use inputs_embeds" ) def UpperCamelCase_ ( self : Union[str, Any] ): pass @unittest.skip(reason="MobileNetV1 does not support input and output embeddings" ) def UpperCamelCase_ ( self : Tuple ): pass @unittest.skip(reason="MobileNetV1 does not output attentions" ) def UpperCamelCase_ ( self : Any ): pass def UpperCamelCase_ ( self : Optional[int] ): __A , __A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __A = model_class(A ) __A = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __A = [*signature.parameters.keys()] __A = ["pixel_values"] self.assertListEqual(arg_names[:1] ,A ) def UpperCamelCase_ ( self : List[Any] ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A ) def UpperCamelCase_ ( self : Optional[int] ): def check_hidden_states_output(A : List[Any] ,A : List[Any] ,A : Optional[int] ): __A = model_class(A ) model.to(A ) model.eval() with torch.no_grad(): __A = model(**self._prepare_for_class(A ,A ) ) __A = outputs.hidden_states __A = 26 self.assertEqual(len(A ) ,A ) __A , __A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __A = True check_hidden_states_output(A ,A ,A ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __A = True check_hidden_states_output(A ,A ,A ) def UpperCamelCase_ ( self : Tuple ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*A ) @slow def UpperCamelCase_ ( self : Union[str, Any] ): for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __A = MobileNetVaModel.from_pretrained(A ) self.assertIsNotNone(A ) def UpperCAmelCase ( ) -> str: """simple docstring""" __A = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def UpperCamelCase_ ( self : List[str] ): return ( MobileNetVaImageProcessor.from_pretrained("google/mobilenet_v1_1.0_224" ) if is_vision_available() else None ) @slow def UpperCamelCase_ ( self : Optional[Any] ): __A = MobileNetVaForImageClassification.from_pretrained("google/mobilenet_v1_1.0_224" ).to(A ) __A = self.default_image_processor __A = prepare_img() __A = image_processor(images=A ,return_tensors="pt" ).to(A ) # forward pass with torch.no_grad(): __A = model(**A ) # verify the logits __A = torch.Size((1, 10_01) ) self.assertEqual(outputs.logits.shape ,A ) __A = torch.tensor([-4.17_39, -1.12_33, 3.12_05] ).to(A ) self.assertTrue(torch.allclose(outputs.logits[0, :3] ,A ,atol=1E-4 ) )
55
1
import argparse import os from pathlib import Path import torch from bark.generation import _load_model as _bark_load_model from huggingface_hub import hf_hub_download from transformers import EncodecConfig, EncodecModel, set_seed from transformers.models.bark.configuration_bark import ( BarkCoarseConfig, BarkConfig, BarkFineConfig, BarkSemanticConfig, ) from transformers.models.bark.generation_configuration_bark import ( BarkCoarseGenerationConfig, BarkFineGenerationConfig, BarkGenerationConfig, BarkSemanticGenerationConfig, ) from transformers.models.bark.modeling_bark import BarkCoarseModel, BarkFineModel, BarkModel, BarkSemanticModel from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE :Any = logging.get_logger(__name__) set_seed(770) SCREAMING_SNAKE_CASE :Any = { 'c_attn': 'att_proj', 'c_proj': 'out_proj', 'c_fc': 'in_proj', 'transformer.': '', 'h.': 'layers.', 'ln_1': 'layernorm_1', 'ln_2': 'layernorm_2', 'ln_f': 'layernorm_final', 'wpe': 'position_embeds_layer', 'wte': 'input_embeds_layer', } SCREAMING_SNAKE_CASE :Union[str, Any] = { 'text_small': { 'repo_id': 'suno/bark', 'file_name': 'text.pt', }, 'coarse_small': { 'repo_id': 'suno/bark', 'file_name': 'coarse.pt', }, 'fine_small': { 'repo_id': 'suno/bark', 'file_name': 'fine.pt', }, 'text': { 'repo_id': 'suno/bark', 'file_name': 'text_2.pt', }, 'coarse': { 'repo_id': 'suno/bark', 'file_name': 'coarse_2.pt', }, 'fine': { 'repo_id': 'suno/bark', 'file_name': 'fine_2.pt', }, } SCREAMING_SNAKE_CASE :List[str] = os.path.dirname(os.path.abspath(__file__)) SCREAMING_SNAKE_CASE :Optional[int] = os.path.join(os.path.expanduser('~'), '.cache') SCREAMING_SNAKE_CASE :Any = os.path.join(os.getenv('XDG_CACHE_HOME', default_cache_dir), 'suno', 'bark_v0') def UpperCAmelCase ( a_ , a_=False ) -> Optional[Any]: """simple docstring""" __A = model_type if use_small: key += "_small" return os.path.join(a_ , REMOTE_MODEL_PATHS[key]["file_name"] ) def UpperCAmelCase ( a_ , a_ ) -> List[str]: """simple docstring""" os.makedirs(a_ , exist_ok=a_ ) hf_hub_download(repo_id=a_ , filename=a_ , local_dir=a_ ) def UpperCAmelCase ( a_ , a_ , a_=False , a_="text" ) -> List[Any]: """simple docstring""" if model_type == "text": __A = BarkSemanticModel __A = BarkSemanticConfig __A = BarkSemanticGenerationConfig elif model_type == "coarse": __A = BarkCoarseModel __A = BarkCoarseConfig __A = BarkCoarseGenerationConfig elif model_type == "fine": __A = BarkFineModel __A = BarkFineConfig __A = BarkFineGenerationConfig else: raise NotImplementedError() __A = F'''{model_type}_small''' if use_small else model_type __A = REMOTE_MODEL_PATHS[model_key] if not os.path.exists(a_ ): logger.info(F'''{model_type} model not found, downloading into `{CACHE_DIR}`.''' ) _download(model_info["repo_id"] , model_info["file_name"] ) __A = torch.load(a_ , map_location=a_ ) # this is a hack __A = checkpoint["model_args"] if "input_vocab_size" not in model_args: __A = model_args["vocab_size"] __A = model_args["vocab_size"] del model_args["vocab_size"] # convert Bark model arguments to HF Bark model arguments __A = model_args.pop("n_head" ) __A = model_args.pop("n_embd" ) __A = model_args.pop("n_layer" ) __A = ConfigClass(**checkpoint["model_args"] ) __A = ModelClass(config=a_ ) __A = GenerationConfigClass() __A = model_generation_config __A = checkpoint["model"] # fixup checkpoint __A = "_orig_mod." for k, v in list(state_dict.items() ): if k.startswith(a_ ): # replace part of the key with corresponding layer name in HF implementation __A = k[len(a_ ) :] for old_layer_name in new_layer_name_dict: __A = new_k.replace(a_ , new_layer_name_dict[old_layer_name] ) __A = state_dict.pop(a_ ) __A = set(state_dict.keys() ) - set(model.state_dict().keys() ) __A = {k for k in extra_keys if not k.endswith(".attn.bias" )} __A = set(model.state_dict().keys() ) - set(state_dict.keys() ) __A = {k for k in missing_keys if not k.endswith(".attn.bias" )} if len(a_ ) != 0: raise ValueError(F'''extra keys found: {extra_keys}''' ) if len(a_ ) != 0: raise ValueError(F'''missing keys: {missing_keys}''' ) model.load_state_dict(a_ , strict=a_ ) __A = model.num_parameters(exclude_embeddings=a_ ) __A = checkpoint["best_val_loss"].item() logger.info(F'''model loaded: {round(n_params/1E6 , 1 )}M params, {round(a_ , 3 )} loss''' ) model.eval() model.to(a_ ) del checkpoint, state_dict return model def UpperCAmelCase ( a_ , a_=False , a_="text" ) -> List[Any]: """simple docstring""" if model_type not in ("text", "coarse", "fine"): raise NotImplementedError() __A = "cpu" # do conversion on cpu __A = _get_ckpt_path(a_ , use_small=a_ ) __A = _load_model(a_ , a_ , model_type=a_ , use_small=a_ ) # load bark initial model __A = _bark_load_model(a_ , "cpu" , model_type=a_ , use_small=a_ ) if model_type == "text": __A = bark_model["model"] if model.num_parameters(exclude_embeddings=a_ ) != bark_model.get_num_params(): raise ValueError("initial and new models don't have the same number of parameters" ) # check if same output as the bark model __A = 5 __A = 1_0 if model_type in ["text", "coarse"]: __A = torch.randint(2_5_6 , (batch_size, sequence_length) , dtype=torch.int ) __A = bark_model(a_ )[0] __A = model(a_ ) # take last logits __A = output_new_model_total.logits[:, [-1], :] else: __A = 3 __A = 8 __A = torch.randint(2_5_6 , (batch_size, sequence_length, n_codes_total) , dtype=torch.int ) __A = model(a_ , a_ ) __A = bark_model(a_ , a_ ) __A = output_new_model_total.logits # output difference should come from the difference of self-attention implementation design if output_new_model.shape != output_old_model.shape: raise ValueError("initial and new outputs don't have the same shape" ) if (output_new_model - output_old_model).abs().max().item() > 1E-3: raise ValueError("initial and new outputs are not equal" ) Path(a_ ).mkdir(exist_ok=a_ ) model.save_pretrained(a_ ) def UpperCAmelCase ( a_ , a_ , a_ , a_ , a_ , a_ , ) -> Union[str, Any]: """simple docstring""" __A = os.path.join(a_ , a_ ) __A = BarkSemanticConfig.from_pretrained(os.path.join(a_ , "config.json" ) ) __A = BarkCoarseConfig.from_pretrained(os.path.join(a_ , "config.json" ) ) __A = BarkFineConfig.from_pretrained(os.path.join(a_ , "config.json" ) ) __A = EncodecConfig.from_pretrained("facebook/encodec_24khz" ) __A = BarkSemanticModel.from_pretrained(a_ ) __A = BarkCoarseModel.from_pretrained(a_ ) __A = BarkFineModel.from_pretrained(a_ ) __A = EncodecModel.from_pretrained("facebook/encodec_24khz" ) __A = BarkConfig.from_sub_model_configs( a_ , a_ , a_ , a_ ) __A = BarkGenerationConfig.from_sub_model_configs( semantic.generation_config , coarseAcoustic.generation_config , fineAcoustic.generation_config ) __A = BarkModel(a_ ) __A = semantic __A = coarseAcoustic __A = fineAcoustic __A = codec __A = bark_generation_config Path(a_ ).mkdir(exist_ok=a_ ) bark.save_pretrained(a_ , repo_id=a_ , push_to_hub=a_ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE :Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument('model_type', type=str, help='text, coarse or fine.') parser.add_argument('pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--is_small', action='store_true', help='convert the small version instead of the large.') SCREAMING_SNAKE_CASE :Union[str, Any] = parser.parse_args() load_model(args.pytorch_dump_folder_path, model_type=args.model_type, use_small=args.is_small)
55
import copy import unittest from transformers.models.auto import get_values from transformers.testing_utils import require_torch, 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, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_MULTIPLE_CHOICE_MAPPING, MODEL_FOR_QUESTION_ANSWERING_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaModel, ) from transformers.models.layoutlmva.modeling_layoutlmva import LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class UpperCAmelCase : '''simple docstring''' def __init__( self : str ,A : int ,A : int=2 ,A : Optional[Any]=3 ,A : Dict=4 ,A : Optional[int]=2 ,A : Union[str, Any]=7 ,A : List[str]=True ,A : Union[str, Any]=True ,A : Optional[int]=True ,A : Optional[int]=True ,A : Tuple=99 ,A : Optional[int]=36 ,A : Dict=3 ,A : str=4 ,A : Optional[Any]=37 ,A : Dict="gelu" ,A : Dict=0.1 ,A : Union[str, Any]=0.1 ,A : Union[str, Any]=5_12 ,A : Any=16 ,A : Union[str, Any]=2 ,A : List[Any]=0.02 ,A : List[Any]=6 ,A : Optional[int]=6 ,A : List[Any]=3 ,A : Union[str, Any]=4 ,A : Tuple=None ,A : List[str]=10_00 ,): __A = parent __A = batch_size __A = num_channels __A = image_size __A = patch_size __A = text_seq_length __A = is_training __A = use_input_mask __A = use_token_type_ids __A = use_labels __A = vocab_size __A = hidden_size __A = num_hidden_layers __A = num_attention_heads __A = intermediate_size __A = hidden_act __A = hidden_dropout_prob __A = attention_probs_dropout_prob __A = max_position_embeddings __A = type_vocab_size __A = type_sequence_label_size __A = initializer_range __A = coordinate_size __A = shape_size __A = num_labels __A = num_choices __A = scope __A = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) __A = text_seq_length __A = (image_size // patch_size) ** 2 + 1 __A = self.text_seq_length + self.image_seq_length def UpperCamelCase_ ( self : int ): __A = ids_tensor([self.batch_size, self.text_seq_length] ,self.vocab_size ) __A = ids_tensor([self.batch_size, self.text_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]: __A = bbox[i, j, 3] __A = bbox[i, j, 1] __A = t if bbox[i, j, 2] < bbox[i, j, 0]: __A = bbox[i, j, 2] __A = bbox[i, j, 0] __A = t __A = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __A = None if self.use_input_mask: __A = random_attention_mask([self.batch_size, self.text_seq_length] ) __A = None if self.use_token_type_ids: __A = ids_tensor([self.batch_size, self.text_seq_length] ,self.type_vocab_size ) __A = None __A = None if self.use_labels: __A = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) __A = ids_tensor([self.batch_size, self.text_seq_length] ,self.num_labels ) __A = LayoutLMvaConfig( 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 ,coordinate_size=self.coordinate_size ,shape_size=self.shape_size ,input_size=self.image_size ,patch_size=self.patch_size ,) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def UpperCamelCase_ ( self : Optional[int] ,A : List[str] ,A : Any ,A : Dict ,A : List[Any] ,A : Optional[int] ,A : Any ,A : Dict ,A : List[Any] ): __A = LayoutLMvaModel(config=A ) model.to(A ) model.eval() # text + image __A = model(A ,pixel_values=A ) __A = model( A ,bbox=A ,pixel_values=A ,attention_mask=A ,token_type_ids=A ) __A = model(A ,bbox=A ,pixel_values=A ,token_type_ids=A ) __A = model(A ,bbox=A ,pixel_values=A ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) # text only __A = model(A ) self.parent.assertEqual( result.last_hidden_state.shape ,(self.batch_size, self.text_seq_length, self.hidden_size) ) # image only __A = model(pixel_values=A ) self.parent.assertEqual( result.last_hidden_state.shape ,(self.batch_size, self.image_seq_length, self.hidden_size) ) def UpperCamelCase_ ( self : Optional[int] ,A : Dict ,A : List[str] ,A : Any ,A : List[Any] ,A : Any ,A : Any ,A : Dict ,A : Optional[Any] ): __A = self.num_labels __A = LayoutLMvaForSequenceClassification(A ) model.to(A ) model.eval() __A = model( A ,bbox=A ,pixel_values=A ,attention_mask=A ,token_type_ids=A ,labels=A ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def UpperCamelCase_ ( self : str ,A : Optional[Any] ,A : Dict ,A : str ,A : Tuple ,A : Union[str, Any] ,A : List[Any] ,A : Any ,A : Union[str, Any] ): __A = self.num_labels __A = LayoutLMvaForTokenClassification(config=A ) model.to(A ) model.eval() __A = model( A ,bbox=A ,pixel_values=A ,attention_mask=A ,token_type_ids=A ,labels=A ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.text_seq_length, self.num_labels) ) def UpperCamelCase_ ( self : Optional[int] ,A : Optional[Any] ,A : int ,A : str ,A : List[str] ,A : int ,A : List[str] ,A : List[str] ,A : Dict ): __A = LayoutLMvaForQuestionAnswering(config=A ) model.to(A ) model.eval() __A = model( A ,bbox=A ,pixel_values=A ,attention_mask=A ,token_type_ids=A ,start_positions=A ,end_positions=A ,) self.parent.assertEqual(result.start_logits.shape ,(self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape ,(self.batch_size, self.seq_length) ) def UpperCamelCase_ ( self : str ): __A = self.prepare_config_and_inputs() ( ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ) = config_and_inputs __A = { "input_ids": input_ids, "bbox": bbox, "pixel_values": pixel_values, "token_type_ids": token_type_ids, "attention_mask": input_mask, } return config, inputs_dict @require_torch class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = ( ( LayoutLMvaModel, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaForQuestionAnswering, ) if is_torch_available() else () ) snake_case_ = ( {"document-question-answering": LayoutLMvaForQuestionAnswering, "feature-extraction": LayoutLMvaModel} if is_torch_available() else {} ) def UpperCamelCase_ ( self : str ,A : Any ,A : Any ,A : Tuple ,A : List[Any] ,A : Optional[Any] ): # `DocumentQuestionAnsweringPipeline` is expected to work with this model, but it combines the text and visual # embedding along the sequence dimension (dim 1), which causes an error during post-processing as `p_mask` has # the sequence dimension of the text embedding only. # (see the line `embedding_output = torch.cat([embedding_output, visual_embeddings], dim=1)`) return True def UpperCamelCase_ ( self : Union[str, Any] ): __A = LayoutLMvaModelTester(self ) __A = ConfigTester(self ,config_class=A ,hidden_size=37 ) def UpperCamelCase_ ( self : List[Any] ,A : int ,A : List[str] ,A : Dict=False ): __A = copy.deepcopy(A ) if model_class in get_values(A ): __A = { k: v.unsqueeze(1 ).expand(-1 ,self.model_tester.num_choices ,-1 ).contiguous() if isinstance(A ,torch.Tensor ) and v.ndim > 1 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(A ): __A = torch.ones(self.model_tester.batch_size ,dtype=torch.long ,device=A ) elif model_class in get_values(A ): __A = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=A ) __A = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=A ) elif model_class in [ *get_values(A ), ]: __A = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=A ) elif model_class in [ *get_values(A ), ]: __A = torch.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) ,dtype=torch.long ,device=A ,) return inputs_dict def UpperCamelCase_ ( self : List[Any] ): self.config_tester.run_common_tests() def UpperCamelCase_ ( self : Union[str, Any] ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A ) def UpperCamelCase_ ( self : str ): __A = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __A = type self.model_tester.create_and_check_model(*A ) def UpperCamelCase_ ( self : Optional[Any] ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*A ) def UpperCamelCase_ ( self : Optional[Any] ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*A ) def UpperCamelCase_ ( self : str ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*A ) @slow def UpperCamelCase_ ( self : Optional[int] ): for model_name in LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __A = LayoutLMvaModel.from_pretrained(A ) self.assertIsNotNone(A ) def UpperCAmelCase ( ) -> Dict: """simple docstring""" __A = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def UpperCamelCase_ ( self : Any ): return LayoutLMvaImageProcessor(apply_ocr=A ) if is_vision_available() else None @slow def UpperCamelCase_ ( self : Dict ): __A = LayoutLMvaModel.from_pretrained("microsoft/layoutlmv3-base" ).to(A ) __A = self.default_image_processor __A = prepare_img() __A = image_processor(images=A ,return_tensors="pt" ).pixel_values.to(A ) __A = torch.tensor([[1, 2]] ) __A = torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]] ).unsqueeze(0 ) # forward pass __A = model( input_ids=input_ids.to(A ) ,bbox=bbox.to(A ) ,pixel_values=pixel_values.to(A ) ,) # verify the logits __A = torch.Size((1, 1_99, 7_68) ) self.assertEqual(outputs.last_hidden_state.shape ,A ) __A = torch.tensor( [[-0.05_29, 0.36_18, 0.16_32], [-0.15_87, -0.16_67, -0.04_00], [-0.15_57, -0.16_71, -0.05_05]] ).to(A ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] ,A ,atol=1E-4 ) )
55
1
import argparse import tensorflow as tf import torch from transformers import BertConfig, BertForMaskedLM from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertPooler, BertSelfAttention, BertSelfOutput, ) from transformers.utils import logging logging.set_verbosity_info() def UpperCAmelCase ( a_ , a_ , a_ ) -> Any: """simple docstring""" def get_masked_lm_array(a_ ): __A = F'''masked_lm/{name}/.ATTRIBUTES/VARIABLE_VALUE''' __A = tf.train.load_variable(a_ , a_ ) if "kernel" in name: __A = array.transpose() return torch.from_numpy(a_ ) def get_encoder_array(a_ ): __A = F'''encoder/{name}/.ATTRIBUTES/VARIABLE_VALUE''' __A = tf.train.load_variable(a_ , a_ ) if "kernel" in name: __A = array.transpose() return torch.from_numpy(a_ ) def get_encoder_layer_array(a_ , a_ ): __A = F'''encoder/_transformer_layers/{layer_index}/{name}/.ATTRIBUTES/VARIABLE_VALUE''' __A = tf.train.load_variable(a_ , a_ ) if "kernel" in name: __A = array.transpose() return torch.from_numpy(a_ ) def get_encoder_attention_layer_array(a_ , a_ , a_ ): __A = F'''encoder/_transformer_layers/{layer_index}/_attention_layer/{name}/.ATTRIBUTES/VARIABLE_VALUE''' __A = tf.train.load_variable(a_ , a_ ) __A = array.reshape(a_ ) if "kernel" in name: __A = array.transpose() return torch.from_numpy(a_ ) print(F'''Loading model based on config from {config_path}...''' ) __A = BertConfig.from_json_file(a_ ) __A = BertForMaskedLM(a_ ) # Layers for layer_index in range(0 , config.num_hidden_layers ): __A = model.bert.encoder.layer[layer_index] # Self-attention __A = layer.attention.self __A = get_encoder_attention_layer_array( a_ , "_query_dense/kernel" , self_attn.query.weight.data.shape ) __A = get_encoder_attention_layer_array( a_ , "_query_dense/bias" , self_attn.query.bias.data.shape ) __A = get_encoder_attention_layer_array( a_ , "_key_dense/kernel" , self_attn.key.weight.data.shape ) __A = get_encoder_attention_layer_array( a_ , "_key_dense/bias" , self_attn.key.bias.data.shape ) __A = get_encoder_attention_layer_array( a_ , "_value_dense/kernel" , self_attn.value.weight.data.shape ) __A = get_encoder_attention_layer_array( a_ , "_value_dense/bias" , self_attn.value.bias.data.shape ) # Self-attention Output __A = layer.attention.output __A = get_encoder_attention_layer_array( a_ , "_output_dense/kernel" , self_output.dense.weight.data.shape ) __A = get_encoder_attention_layer_array( a_ , "_output_dense/bias" , self_output.dense.bias.data.shape ) __A = get_encoder_layer_array(a_ , "_attention_layer_norm/gamma" ) __A = get_encoder_layer_array(a_ , "_attention_layer_norm/beta" ) # Intermediate __A = layer.intermediate __A = get_encoder_layer_array(a_ , "_intermediate_dense/kernel" ) __A = get_encoder_layer_array(a_ , "_intermediate_dense/bias" ) # Output __A = layer.output __A = get_encoder_layer_array(a_ , "_output_dense/kernel" ) __A = get_encoder_layer_array(a_ , "_output_dense/bias" ) __A = get_encoder_layer_array(a_ , "_output_layer_norm/gamma" ) __A = get_encoder_layer_array(a_ , "_output_layer_norm/beta" ) # Embeddings __A = get_encoder_array("_position_embedding_layer/embeddings" ) __A = get_encoder_array("_type_embedding_layer/embeddings" ) __A = get_encoder_array("_embedding_norm_layer/gamma" ) __A = get_encoder_array("_embedding_norm_layer/beta" ) # LM Head __A = model.cls.predictions.transform __A = get_masked_lm_array("dense/kernel" ) __A = get_masked_lm_array("dense/bias" ) __A = get_masked_lm_array("layer_norm/gamma" ) __A = get_masked_lm_array("layer_norm/beta" ) __A = get_masked_lm_array("embedding_table" ) # Pooling __A = BertPooler(config=a_ ) __A = get_encoder_array("_pooler_layer/kernel" ) __A = get_encoder_array("_pooler_layer/bias" ) # Export final model model.save_pretrained(a_ ) # Integration test - should load without any errors ;) __A = BertForMaskedLM.from_pretrained(a_ ) print(new_model.eval() ) print("Model conversion was done sucessfully!" ) if __name__ == "__main__": SCREAMING_SNAKE_CASE :int = argparse.ArgumentParser() parser.add_argument( '--tf_checkpoint_path', type=str, required=True, help='Path to the TensorFlow Token Dropping checkpoint path.' ) parser.add_argument( '--bert_config_file', type=str, required=True, help='The config json file corresponding to the BERT model. This specifies the model architecture.', ) parser.add_argument( '--pytorch_dump_path', type=str, required=True, help='Path to the output PyTorch model.', ) SCREAMING_SNAKE_CASE :Tuple = parser.parse_args() convert_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
55
import unittest import numpy as np from datasets import load_dataset 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 BeitImageProcessor class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self : Any ,A : List[str] ,A : str=7 ,A : Optional[Any]=3 ,A : Any=18 ,A : int=30 ,A : int=4_00 ,A : List[str]=True ,A : Union[str, Any]=None ,A : Union[str, Any]=True ,A : Tuple=None ,A : Tuple=True ,A : Union[str, Any]=[0.5, 0.5, 0.5] ,A : str=[0.5, 0.5, 0.5] ,A : List[Any]=False ,): __A = size if size is not None else {"height": 20, "width": 20} __A = crop_size if crop_size is not None else {"height": 18, "width": 18} __A = parent __A = batch_size __A = num_channels __A = image_size __A = min_resolution __A = max_resolution __A = do_resize __A = size __A = do_center_crop __A = crop_size __A = do_normalize __A = image_mean __A = image_std __A = do_reduce_labels def UpperCamelCase_ ( self : List[str] ): return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_reduce_labels": self.do_reduce_labels, } def UpperCAmelCase ( ) -> int: """simple docstring""" __A = load_dataset("hf-internal-testing/fixtures_ade20k" , split="test" ) __A = Image.open(dataset[0]["file"] ) __A = Image.open(dataset[1]["file"] ) return image, map def UpperCAmelCase ( ) -> Optional[int]: """simple docstring""" __A = load_dataset("hf-internal-testing/fixtures_ade20k" , split="test" ) __A = Image.open(ds[0]["file"] ) __A = Image.open(ds[1]["file"] ) __A = Image.open(ds[2]["file"] ) __A = Image.open(ds[3]["file"] ) return [imagea, imagea], [mapa, mapa] @require_torch @require_vision class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = BeitImageProcessor if is_vision_available() else None def UpperCamelCase_ ( self : List[Any] ): __A = BeitImageProcessingTester(self ) @property def UpperCamelCase_ ( self : List[Any] ): return self.image_processor_tester.prepare_image_processor_dict() def UpperCamelCase_ ( self : int ): __A = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(A ,"do_resize" ) ) self.assertTrue(hasattr(A ,"size" ) ) self.assertTrue(hasattr(A ,"do_center_crop" ) ) self.assertTrue(hasattr(A ,"center_crop" ) ) self.assertTrue(hasattr(A ,"do_normalize" ) ) self.assertTrue(hasattr(A ,"image_mean" ) ) self.assertTrue(hasattr(A ,"image_std" ) ) def UpperCamelCase_ ( self : List[str] ): __A = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size ,{"height": 20, "width": 20} ) self.assertEqual(image_processor.crop_size ,{"height": 18, "width": 18} ) self.assertEqual(image_processor.do_reduce_labels ,A ) __A = self.image_processing_class.from_dict( self.image_processor_dict ,size=42 ,crop_size=84 ,reduce_labels=A ) self.assertEqual(image_processor.size ,{"height": 42, "width": 42} ) self.assertEqual(image_processor.crop_size ,{"height": 84, "width": 84} ) self.assertEqual(image_processor.do_reduce_labels ,A ) def UpperCamelCase_ ( self : List[Any] ): pass def UpperCamelCase_ ( self : Optional[int] ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __A = prepare_image_inputs(self.image_processor_tester ,equal_resolution=A ) for image in image_inputs: self.assertIsInstance(A ,Image.Image ) # Test not batched input __A = 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 __A = image_processing(A ,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 UpperCamelCase_ ( self : List[str] ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __A = prepare_image_inputs(self.image_processor_tester ,equal_resolution=A ,numpify=A ) for image in image_inputs: self.assertIsInstance(A ,np.ndarray ) # Test not batched input __A = 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 __A = image_processing(A ,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 UpperCamelCase_ ( self : int ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A = prepare_image_inputs(self.image_processor_tester ,equal_resolution=A ,torchify=A ) for image in image_inputs: self.assertIsInstance(A ,torch.Tensor ) # Test not batched input __A = 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 __A = image_processing(A ,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 UpperCamelCase_ ( self : str ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A = prepare_image_inputs(self.image_processor_tester ,equal_resolution=A ,torchify=A ) __A = [] for image in image_inputs: self.assertIsInstance(A ,torch.Tensor ) maps.append(torch.zeros(image.shape[-2:] ).long() ) # Test not batched input __A = image_processing(image_inputs[0] ,maps[0] ,return_tensors="pt" ) self.assertEqual( encoding["pixel_values"].shape ,( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,) self.assertEqual( encoding["labels"].shape ,( 1, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,) self.assertEqual(encoding["labels"].dtype ,torch.long ) self.assertTrue(encoding["labels"].min().item() >= 0 ) self.assertTrue(encoding["labels"].max().item() <= 2_55 ) # Test batched __A = image_processing(A ,A ,return_tensors="pt" ) self.assertEqual( encoding["pixel_values"].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"], ) ,) self.assertEqual( encoding["labels"].shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,) self.assertEqual(encoding["labels"].dtype ,torch.long ) self.assertTrue(encoding["labels"].min().item() >= 0 ) self.assertTrue(encoding["labels"].max().item() <= 2_55 ) # Test not batched input (PIL images) __A , __A = prepare_semantic_single_inputs() __A = image_processing(A ,A ,return_tensors="pt" ) self.assertEqual( encoding["pixel_values"].shape ,( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,) self.assertEqual( encoding["labels"].shape ,( 1, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,) self.assertEqual(encoding["labels"].dtype ,torch.long ) self.assertTrue(encoding["labels"].min().item() >= 0 ) self.assertTrue(encoding["labels"].max().item() <= 2_55 ) # Test batched input (PIL images) __A , __A = prepare_semantic_batch_inputs() __A = image_processing(A ,A ,return_tensors="pt" ) self.assertEqual( encoding["pixel_values"].shape ,( 2, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,) self.assertEqual( encoding["labels"].shape ,( 2, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,) self.assertEqual(encoding["labels"].dtype ,torch.long ) self.assertTrue(encoding["labels"].min().item() >= 0 ) self.assertTrue(encoding["labels"].max().item() <= 2_55 ) def UpperCamelCase_ ( self : Dict ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # ADE20k has 150 classes, and the background is included, so labels should be between 0 and 150 __A , __A = prepare_semantic_single_inputs() __A = image_processing(A ,A ,return_tensors="pt" ) self.assertTrue(encoding["labels"].min().item() >= 0 ) self.assertTrue(encoding["labels"].max().item() <= 1_50 ) __A = True __A = image_processing(A ,A ,return_tensors="pt" ) self.assertTrue(encoding["labels"].min().item() >= 0 ) self.assertTrue(encoding["labels"].max().item() <= 2_55 )
55
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) SCREAMING_SNAKE_CASE :int = { 'configuration_mobilebert': [ 'MOBILEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MobileBertConfig', 'MobileBertOnnxConfig', ], 'tokenization_mobilebert': ['MobileBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE :Dict = ['MobileBertTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE :Union[str, Any] = [ 'MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'MobileBertForMaskedLM', 'MobileBertForMultipleChoice', 'MobileBertForNextSentencePrediction', 'MobileBertForPreTraining', 'MobileBertForQuestionAnswering', 'MobileBertForSequenceClassification', 'MobileBertForTokenClassification', 'MobileBertLayer', 'MobileBertModel', 'MobileBertPreTrainedModel', 'load_tf_weights_in_mobilebert', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE :List[str] = [ 'TF_MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFMobileBertForMaskedLM', 'TFMobileBertForMultipleChoice', 'TFMobileBertForNextSentencePrediction', 'TFMobileBertForPreTraining', 'TFMobileBertForQuestionAnswering', 'TFMobileBertForSequenceClassification', 'TFMobileBertForTokenClassification', 'TFMobileBertMainLayer', 'TFMobileBertModel', 'TFMobileBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_mobilebert import ( MOBILEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileBertConfig, MobileBertOnnxConfig, ) from .tokenization_mobilebert import MobileBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mobilebert_fast import MobileBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mobilebert import ( MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, MobileBertForMaskedLM, MobileBertForMultipleChoice, MobileBertForNextSentencePrediction, MobileBertForPreTraining, MobileBertForQuestionAnswering, MobileBertForSequenceClassification, MobileBertForTokenClassification, MobileBertLayer, MobileBertModel, MobileBertPreTrainedModel, load_tf_weights_in_mobilebert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mobilebert import ( TF_MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFMobileBertForMaskedLM, TFMobileBertForMultipleChoice, TFMobileBertForNextSentencePrediction, TFMobileBertForPreTraining, TFMobileBertForQuestionAnswering, TFMobileBertForSequenceClassification, TFMobileBertForTokenClassification, TFMobileBertMainLayer, TFMobileBertModel, TFMobileBertPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE :Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
55
from numpy import exp, pi, sqrt def UpperCAmelCase ( a_ , a_ = 0.0 , a_ = 1.0 ) -> int: """simple docstring""" return 1 / sqrt(2 * pi * sigma**2 ) * exp(-((x - mu) ** 2) / (2 * sigma**2) ) if __name__ == "__main__": import doctest doctest.testmod()
55
1
def UpperCAmelCase ( a_ = 6_0_0_8_5_1_4_7_5_1_4_3 ) -> int: """simple docstring""" try: __A = int(a_ ) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int." ) if n <= 0: raise ValueError("Parameter n must be greater than or equal to one." ) __A = 2 __A = 0 if n == 2: return 2 while n > 2: while n % i != 0: i += 1 __A = i while n % i == 0: __A = n // i i += 1 return int(a_ ) if __name__ == "__main__": print(f'''{solution() = }''')
55
import gc import unittest from diffusers import FlaxStableDiffusionInpaintPipeline from diffusers.utils import is_flax_available, load_image, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard @slow @require_flax class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase_ ( self : Tuple ): # clean up the VRAM after each test super().tearDown() gc.collect() def UpperCamelCase_ ( self : Optional[int] ): __A = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/sd2-inpaint/init_image.png" ) __A = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png" ) __A = "xvjiarui/stable-diffusion-2-inpainting" __A , __A = FlaxStableDiffusionInpaintPipeline.from_pretrained(A ,safety_checker=A ) __A = "Face of a yellow cat, high resolution, sitting on a park bench" __A = jax.random.PRNGKey(0 ) __A = 50 __A = jax.device_count() __A = num_samples * [prompt] __A = num_samples * [init_image] __A = num_samples * [mask_image] __A , __A , __A = pipeline.prepare_inputs(A ,A ,A ) # shard inputs and rng __A = replicate(A ) __A = jax.random.split(A ,jax.device_count() ) __A = shard(A ) __A = shard(A ) __A = shard(A ) __A = pipeline( A ,A ,A ,A ,A ,A ,jit=A ) __A = output.images.reshape(A ,5_12 ,5_12 ,3 ) __A = images[0, 2_53:2_56, 2_53:2_56, -1] __A = jnp.asarray(jax.device_get(image_slice.flatten() ) ) __A = jnp.array( [0.3_61_13_07, 0.37_64_97_36, 0.3_75_74_08, 0.38_21_39_53, 0.39_29_51_67, 0.3_84_16_31, 0.41_55_49_78, 0.4_13_74_75, 0.4_21_70_84] ) print(f'''output_slice: {output_slice}''' ) assert jnp.abs(output_slice - expected_slice ).max() < 1E-2
55
1
import requests SCREAMING_SNAKE_CASE :List[str] = 'YOUR API KEY' def UpperCAmelCase ( a_ , a_ = giphy_api_key ) -> list: """simple docstring""" __A = "+".join(query.split() ) __A = F'''https://api.giphy.com/v1/gifs/search?q={formatted_query}&api_key={api_key}''' __A = requests.get(a_ ).json()["data"] return [gif["url"] for gif in gifs] if __name__ == "__main__": print('\n'.join(get_gifs('space ship')))
55
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 GLPNImageProcessor class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self : Any ,A : Optional[int] ,A : Optional[int]=7 ,A : Optional[Any]=3 ,A : List[str]=18 ,A : Any=30 ,A : Tuple=4_00 ,A : Union[str, Any]=True ,A : Optional[Any]=32 ,A : Union[str, Any]=True ,): __A = parent __A = batch_size __A = num_channels __A = image_size __A = min_resolution __A = max_resolution __A = do_resize __A = size_divisor __A = do_rescale def UpperCamelCase_ ( self : Union[str, Any] ): return { "do_resize": self.do_resize, "size_divisor": self.size_divisor, "do_rescale": self.do_rescale, } @require_torch @require_vision class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = GLPNImageProcessor if is_vision_available() else None def UpperCamelCase_ ( self : int ): __A = GLPNImageProcessingTester(self ) @property def UpperCamelCase_ ( self : Optional[Any] ): return self.image_processor_tester.prepare_image_processor_dict() def UpperCamelCase_ ( self : Any ): __A = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(A ,"do_resize" ) ) self.assertTrue(hasattr(A ,"size_divisor" ) ) self.assertTrue(hasattr(A ,"resample" ) ) self.assertTrue(hasattr(A ,"do_rescale" ) ) def UpperCamelCase_ ( self : str ): pass def UpperCamelCase_ ( self : Dict ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __A = prepare_image_inputs(self.image_processor_tester ,equal_resolution=A ) for image in image_inputs: self.assertIsInstance(A ,Image.Image ) # Test not batched input (GLPNImageProcessor doesn't support batching) __A = image_processing(image_inputs[0] ,return_tensors="pt" ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 ) def UpperCamelCase_ ( self : Optional[Any] ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __A = prepare_image_inputs(self.image_processor_tester ,equal_resolution=A ,numpify=A ) for image in image_inputs: self.assertIsInstance(A ,np.ndarray ) # Test not batched input (GLPNImageProcessor doesn't support batching) __A = image_processing(image_inputs[0] ,return_tensors="pt" ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 ) def UpperCamelCase_ ( self : int ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A = prepare_image_inputs(self.image_processor_tester ,equal_resolution=A ,torchify=A ) for image in image_inputs: self.assertIsInstance(A ,torch.Tensor ) # Test not batched input (GLPNImageProcessor doesn't support batching) __A = image_processing(image_inputs[0] ,return_tensors="pt" ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 )
55
1
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 UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase_ ( self : Optional[Any] ): __A = tempfile.mkdtemp() __A = SamImageProcessor() __A = SamProcessor(A ) processor.save_pretrained(self.tmpdirname ) def UpperCamelCase_ ( self : Any ,**A : Optional[int] ): return AutoProcessor.from_pretrained(self.tmpdirname ,**A ).image_processor def UpperCamelCase_ ( self : Dict ): shutil.rmtree(self.tmpdirname ) def UpperCamelCase_ ( self : Any ): __A = [np.random.randint(2_55 ,size=(3, 30, 4_00) ,dtype=np.uinta )] __A = [Image.fromarray(np.moveaxis(A ,0 ,-1 ) ) for x in image_inputs] return image_inputs def UpperCamelCase_ ( self : Any ): __A = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __A = self.get_image_processor(do_normalize=A ,padding_value=1.0 ) __A = SamProcessor.from_pretrained(self.tmpdirname ,do_normalize=A ,padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() ,image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor ,A ) def UpperCamelCase_ ( self : Tuple ): __A = self.get_image_processor() __A = SamProcessor(image_processor=A ) __A = self.prepare_image_inputs() __A = image_processor(A ,return_tensors="np" ) __A = processor(images=A ,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 UpperCamelCase_ ( self : Tuple ): __A = self.get_image_processor() __A = SamProcessor(image_processor=A ) __A = [torch.ones((1, 3, 5, 5) )] __A = [[17_64, 26_46]] __A = [[6_83, 10_24]] __A = processor.post_process_masks(A ,A ,A ) self.assertEqual(masks[0].shape ,(1, 3, 17_64, 26_46) ) __A = processor.post_process_masks( A ,torch.tensor(A ) ,torch.tensor(A ) ) self.assertEqual(masks[0].shape ,(1, 3, 17_64, 26_46) ) # should also work with np __A = [np.ones((1, 3, 5, 5) )] __A = processor.post_process_masks(A ,np.array(A ) ,np.array(A ) ) self.assertEqual(masks[0].shape ,(1, 3, 17_64, 26_46) ) __A = [[1, 0], [0, 1]] with self.assertRaises(A ): __A = processor.post_process_masks(A ,np.array(A ) ,np.array(A ) ) @require_vision @require_tf class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase_ ( self : List[str] ): __A = tempfile.mkdtemp() __A = SamImageProcessor() __A = SamProcessor(A ) processor.save_pretrained(self.tmpdirname ) def UpperCamelCase_ ( self : Tuple ,**A : int ): return AutoProcessor.from_pretrained(self.tmpdirname ,**A ).image_processor def UpperCamelCase_ ( self : Tuple ): shutil.rmtree(self.tmpdirname ) def UpperCamelCase_ ( self : Union[str, Any] ): __A = [np.random.randint(2_55 ,size=(3, 30, 4_00) ,dtype=np.uinta )] __A = [Image.fromarray(np.moveaxis(A ,0 ,-1 ) ) for x in image_inputs] return image_inputs def UpperCamelCase_ ( self : int ): __A = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __A = self.get_image_processor(do_normalize=A ,padding_value=1.0 ) __A = SamProcessor.from_pretrained(self.tmpdirname ,do_normalize=A ,padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() ,image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor ,A ) def UpperCamelCase_ ( self : Tuple ): __A = self.get_image_processor() __A = SamProcessor(image_processor=A ) __A = self.prepare_image_inputs() __A = image_processor(A ,return_tensors="np" ) __A = processor(images=A ,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 UpperCamelCase_ ( self : Dict ): __A = self.get_image_processor() __A = SamProcessor(image_processor=A ) __A = [tf.ones((1, 3, 5, 5) )] __A = [[17_64, 26_46]] __A = [[6_83, 10_24]] __A = processor.post_process_masks(A ,A ,A ,return_tensors="tf" ) self.assertEqual(masks[0].shape ,(1, 3, 17_64, 26_46) ) __A = processor.post_process_masks( A ,tf.convert_to_tensor(A ) ,tf.convert_to_tensor(A ) ,return_tensors="tf" ,) self.assertEqual(masks[0].shape ,(1, 3, 17_64, 26_46) ) # should also work with np __A = [np.ones((1, 3, 5, 5) )] __A = processor.post_process_masks( A ,np.array(A ) ,np.array(A ) ,return_tensors="tf" ) self.assertEqual(masks[0].shape ,(1, 3, 17_64, 26_46) ) __A = [[1, 0], [0, 1]] with self.assertRaises(tf.errors.InvalidArgumentError ): __A = processor.post_process_masks( A ,np.array(A ) ,np.array(A ) ,return_tensors="tf" ) @require_vision @require_torchvision class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase_ ( self : Optional[int] ): __A = tempfile.mkdtemp() __A = SamImageProcessor() __A = SamProcessor(A ) processor.save_pretrained(self.tmpdirname ) def UpperCamelCase_ ( self : str ,**A : str ): return AutoProcessor.from_pretrained(self.tmpdirname ,**A ).image_processor def UpperCamelCase_ ( self : Optional[Any] ): shutil.rmtree(self.tmpdirname ) def UpperCamelCase_ ( self : Union[str, Any] ): __A = [np.random.randint(2_55 ,size=(3, 30, 4_00) ,dtype=np.uinta )] __A = [Image.fromarray(np.moveaxis(A ,0 ,-1 ) ) for x in image_inputs] return image_inputs @is_pt_tf_cross_test def UpperCamelCase_ ( self : Tuple ): __A = self.get_image_processor() __A = SamProcessor(image_processor=A ) __A = np.random.randint(0 ,2 ,size=(1, 3, 5, 5) ).astype(np.floataa ) __A = [tf.convert_to_tensor(A )] __A = [torch.tensor(A )] __A = [[17_64, 26_46]] __A = [[6_83, 10_24]] __A = processor.post_process_masks( A ,A ,A ,return_tensors="tf" ) __A = processor.post_process_masks( A ,A ,A ,return_tensors="pt" ) self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy() ) ) @is_pt_tf_cross_test def UpperCamelCase_ ( self : List[str] ): __A = self.get_image_processor() __A = SamProcessor(image_processor=A ) __A = self.prepare_image_inputs() __A = image_processor(A ,return_tensors="pt" )["pixel_values"].numpy() __A = processor(images=A ,return_tensors="pt" )["pixel_values"].numpy() __A = image_processor(A ,return_tensors="tf" )["pixel_values"].numpy() __A = processor(images=A ,return_tensors="tf" )["pixel_values"].numpy() self.assertTrue(np.allclose(A ,A ) ) self.assertTrue(np.allclose(A ,A ) ) self.assertTrue(np.allclose(A ,A ) )
55
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Image from .base import TaskTemplate @dataclass(frozen=__SCREAMING_SNAKE_CASE ) class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = field(default="image-classification" , metadata={"include_in_asdict_even_if_is_default": True} ) snake_case_ = Features({"image": Image()} ) snake_case_ = Features({"labels": ClassLabel} ) snake_case_ = "image" snake_case_ = "labels" def UpperCamelCase_ ( self : Optional[Any] ,A : Tuple ): if self.label_column not in features: raise ValueError(f'''Column {self.label_column} is not present in features.''' ) if not isinstance(features[self.label_column] ,A ): raise ValueError(f'''Column {self.label_column} is not a ClassLabel.''' ) __A = copy.deepcopy(self ) __A = self.label_schema.copy() __A = features[self.label_column] __A = label_schema return task_template @property def UpperCamelCase_ ( self : Any ): return { self.image_column: "image", self.label_column: "labels", }
55
1
import numpy as np SCREAMING_SNAKE_CASE :Union[str, Any] = [ ['a', 'b', 'c', 'd', 'e'], ['f', 'g', 'h', 'i', 'k'], ['l', 'm', 'n', 'o', 'p'], ['q', 'r', 's', 't', 'u'], ['v', 'w', 'x', 'y', 'z'], ] class UpperCAmelCase : '''simple docstring''' def __init__( self : Optional[Any] ): __A = np.array(A ) def UpperCamelCase_ ( self : str ,A : str ): __A , __A = np.where(letter == self.SQUARE ) __A = np.concatenate([indexa + 1, indexa + 1] ) return indexes def UpperCamelCase_ ( self : Optional[Any] ,A : int ,A : int ): __A = self.SQUARE[indexa - 1, indexa - 1] return letter def UpperCamelCase_ ( self : str ,A : str ): __A = message.lower() __A = message.replace(" " ,"" ) __A = message.replace("j" ,"i" ) __A = np.empty((2, len(A )) ) for letter_index in range(len(A ) ): __A = self.letter_to_numbers(message[letter_index] ) __A = numbers[0] __A = numbers[1] __A = first_step.reshape(2 * len(A ) ) __A = "" for numbers_index in range(len(A ) ): __A = int(second_step[numbers_index * 2] ) __A = int(second_step[(numbers_index * 2) + 1] ) __A = self.numbers_to_letter(A ,A ) __A = encoded_message + letter return encoded_message def UpperCamelCase_ ( self : List[str] ,A : str ): __A = message.lower() message.replace(" " ,"" ) __A = np.empty(2 * len(A ) ) for letter_index in range(len(A ) ): __A = self.letter_to_numbers(message[letter_index] ) __A = numbers[0] __A = numbers[1] __A = first_step.reshape((2, len(A )) ) __A = "" for numbers_index in range(len(A ) ): __A = int(second_step[0, numbers_index] ) __A = int(second_step[1, numbers_index] ) __A = self.numbers_to_letter(A ,A ) __A = decoded_message + letter return decoded_message
55
from math import sqrt def UpperCAmelCase ( a_ ) -> bool: """simple docstring""" assert isinstance(a_ , a_ ) and ( number >= 0 ), "'number' must been an int and positive" __A = True # 0 and 1 are none primes. if number <= 1: __A = False for divisor in range(2 , int(round(sqrt(a_ ) ) ) + 1 ): # if 'number' divisible by 'divisor' then sets 'status' # of false and break up the loop. if number % divisor == 0: __A = False break # precondition assert isinstance(a_ , a_ ), "'status' must been from type bool" return status def UpperCAmelCase ( a_ ) -> Any: """simple docstring""" assert isinstance(a_ , a_ ) and (n > 2), "'N' must been an int and > 2" # beginList: contains all natural numbers from 2 up to N __A = list(range(2 , n + 1 ) ) __A = [] # this list will be returns. # actual sieve of erathostenes for i in range(len(a_ ) ): for j in range(i + 1 , len(a_ ) ): if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0): __A = 0 # filters actual prime numbers. __A = [x for x in begin_list if x != 0] # precondition assert isinstance(a_ , a_ ), "'ans' must been from type list" return ans def UpperCAmelCase ( a_ ) -> Optional[int]: """simple docstring""" assert isinstance(a_ , a_ ) and (n > 2), "'N' must been an int and > 2" __A = [] # iterates over all numbers between 2 up to N+1 # if a number is prime then appends to list 'ans' for number in range(2 , n + 1 ): if is_prime(a_ ): ans.append(a_ ) # precondition assert isinstance(a_ , a_ ), "'ans' must been from type list" return ans def UpperCAmelCase ( a_ ) -> Optional[int]: """simple docstring""" assert isinstance(a_ , a_ ) and number >= 0, "'number' must been an int and >= 0" __A = [] # this list will be returns of the function. # potential prime number factors. __A = 2 __A = number if number == 0 or number == 1: ans.append(a_ ) # if 'number' not prime then builds the prime factorization of 'number' elif not is_prime(a_ ): while quotient != 1: if is_prime(a_ ) and (quotient % factor == 0): ans.append(a_ ) quotient /= factor else: factor += 1 else: ans.append(a_ ) # precondition assert isinstance(a_ , a_ ), "'ans' must been from type list" return ans def UpperCAmelCase ( a_ ) -> Any: """simple docstring""" assert isinstance(a_ , a_ ) and ( number >= 0 ), "'number' bust been an int and >= 0" __A = 0 # prime factorization of 'number' __A = prime_factorization(a_ ) __A = max(a_ ) # precondition assert isinstance(a_ , a_ ), "'ans' must been from type int" return ans def UpperCAmelCase ( a_ ) -> Optional[Any]: """simple docstring""" assert isinstance(a_ , a_ ) and ( number >= 0 ), "'number' bust been an int and >= 0" __A = 0 # prime factorization of 'number' __A = prime_factorization(a_ ) __A = min(a_ ) # precondition assert isinstance(a_ , a_ ), "'ans' must been from type int" return ans def UpperCAmelCase ( a_ ) -> int: """simple docstring""" assert isinstance(a_ , a_ ), "'number' must been an int" assert isinstance(number % 2 == 0 , a_ ), "compare bust been from type bool" return number % 2 == 0 def UpperCAmelCase ( a_ ) -> List[Any]: """simple docstring""" assert isinstance(a_ , a_ ), "'number' must been an int" assert isinstance(number % 2 != 0 , a_ ), "compare bust been from type bool" return number % 2 != 0 def UpperCAmelCase ( a_ ) -> Optional[Any]: """simple docstring""" assert ( isinstance(a_ , a_ ) and (number > 2) and is_even(a_ ) ), "'number' must been an int, even and > 2" __A = [] # this list will returned # creates a list of prime numbers between 2 up to 'number' __A = get_prime_numbers(a_ ) __A = len(a_ ) # run variable for while-loops. __A = 0 __A = None # exit variable. for break up the loops __A = True while i < len_pn and loop: __A = i + 1 while j < len_pn and loop: if prime_numbers[i] + prime_numbers[j] == number: __A = False ans.append(prime_numbers[i] ) ans.append(prime_numbers[j] ) j += 1 i += 1 # precondition assert ( isinstance(a_ , a_ ) and (len(a_ ) == 2) and (ans[0] + ans[1] == number) and is_prime(ans[0] ) and is_prime(ans[1] ) ), "'ans' must contains two primes. And sum of elements must been eq 'number'" return ans def UpperCAmelCase ( a_ , a_ ) -> Optional[Any]: """simple docstring""" assert ( isinstance(a_ , a_ ) and isinstance(a_ , a_ ) and (numbera >= 0) and (numbera >= 0) ), "'number1' and 'number2' must been positive integer." __A = 0 while numbera != 0: __A = numbera % numbera __A = numbera __A = rest # precondition assert isinstance(a_ , a_ ) and ( numbera >= 0 ), "'number' must been from type int and positive" return numbera def UpperCAmelCase ( a_ , a_ ) -> List[str]: """simple docstring""" assert ( isinstance(a_ , a_ ) and isinstance(a_ , a_ ) and (numbera >= 1) and (numbera >= 1) ), "'number1' and 'number2' must been positive integer." __A = 1 # actual answer that will be return. # for kgV (x,1) if numbera > 1 and numbera > 1: # builds the prime factorization of 'number1' and 'number2' __A = prime_factorization(a_ ) __A = prime_factorization(a_ ) elif numbera == 1 or numbera == 1: __A = [] __A = [] __A = max(a_ , a_ ) __A = 0 __A = 0 __A = [] # captured numbers int both 'primeFac1' and 'primeFac2' # iterates through primeFac1 for n in prime_fac_a: if n not in done: if n in prime_fac_a: __A = prime_fac_a.count(a_ ) __A = prime_fac_a.count(a_ ) for _ in range(max(a_ , a_ ) ): ans *= n else: __A = prime_fac_a.count(a_ ) for _ in range(a_ ): ans *= n done.append(a_ ) # iterates through primeFac2 for n in prime_fac_a: if n not in done: __A = prime_fac_a.count(a_ ) for _ in range(a_ ): ans *= n done.append(a_ ) # precondition assert isinstance(a_ , a_ ) and ( ans >= 0 ), "'ans' must been from type int and positive" return ans def UpperCAmelCase ( a_ ) -> str: """simple docstring""" assert isinstance(a_ , a_ ) and (n >= 0), "'number' must been a positive int" __A = 0 __A = 2 # this variable holds the answer while index < n: index += 1 ans += 1 # counts to the next number # if ans not prime then # runs to the next prime number. while not is_prime(a_ ): ans += 1 # precondition assert isinstance(a_ , a_ ) and is_prime( a_ ), "'ans' must been a prime number and from type int" return ans def UpperCAmelCase ( a_ , a_ ) -> Tuple: """simple docstring""" assert ( is_prime(a_ ) and is_prime(a_ ) and (p_number_a < p_number_a) ), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'" __A = p_number_a + 1 # jump to the next number __A = [] # this list will be returns. # if number is not prime then # fetch the next prime number. while not is_prime(a_ ): number += 1 while number < p_number_a: ans.append(a_ ) number += 1 # fetch the next prime number. while not is_prime(a_ ): number += 1 # precondition assert ( isinstance(a_ , a_ ) and ans[0] != p_number_a and ans[len(a_ ) - 1] != p_number_a ), "'ans' must been a list without the arguments" # 'ans' contains not 'pNumber1' and 'pNumber2' ! return ans def UpperCAmelCase ( a_ ) -> str: """simple docstring""" assert isinstance(a_ , a_ ) and (n >= 1), "'n' must been int and >= 1" __A = [] # will be returned. for divisor in range(1 , n + 1 ): if n % divisor == 0: ans.append(a_ ) # precondition assert ans[0] == 1 and ans[len(a_ ) - 1] == n, "Error in function getDivisiors(...)" return ans def UpperCAmelCase ( a_ ) -> Dict: """simple docstring""" assert isinstance(a_ , a_ ) and ( number > 1 ), "'number' must been an int and >= 1" __A = get_divisors(a_ ) # precondition assert ( isinstance(a_ , a_ ) and (divisors[0] == 1) and (divisors[len(a_ ) - 1] == number) ), "Error in help-function getDivisiors(...)" # summed all divisors up to 'number' (exclusive), hence [:-1] return sum(divisors[:-1] ) == number def UpperCAmelCase ( a_ , a_ ) -> str: """simple docstring""" assert ( isinstance(a_ , a_ ) and isinstance(a_ , a_ ) and (denominator != 0) ), "The arguments must been from type int and 'denominator' != 0" # build the greatest common divisor of numerator and denominator. __A = gcd(abs(a_ ) , abs(a_ ) ) # precondition assert ( isinstance(a_ , a_ ) and (numerator % gcd_of_fraction == 0) and (denominator % gcd_of_fraction == 0) ), "Error in function gcd(...,...)" return (numerator // gcd_of_fraction, denominator // gcd_of_fraction) def UpperCAmelCase ( a_ ) -> Optional[int]: """simple docstring""" assert isinstance(a_ , a_ ) and (n >= 0), "'n' must been a int and >= 0" __A = 1 # this will be return. for factor in range(1 , n + 1 ): ans *= factor return ans def UpperCAmelCase ( a_ ) -> List[Any]: """simple docstring""" assert isinstance(a_ , a_ ) and (n >= 0), "'n' must been an int and >= 0" __A = 0 __A = 1 __A = 1 # this will be return for _ in range(n - 1 ): __A = ans ans += fiba __A = tmp return ans
55
1
import csv import tweepy # Twitter API credentials SCREAMING_SNAKE_CASE :List[str] = '' SCREAMING_SNAKE_CASE :List[str] = '' SCREAMING_SNAKE_CASE :Tuple = '' SCREAMING_SNAKE_CASE :List[str] = '' def UpperCAmelCase ( a_ ) -> None: """simple docstring""" __A = tweepy.OAuthHandler(a_ , a_ ) auth.set_access_token(a_ , a_ ) __A = tweepy.API(a_ ) # initialize a list to hold all the tweepy Tweets __A = [] # make initial request for most recent tweets (200 is the maximum allowed count) __A = api.user_timeline(screen_name=a_ , count=2_0_0 ) # save most recent tweets alltweets.extend(a_ ) # save the id of the oldest tweet less one __A = alltweets[-1].id - 1 # keep grabbing tweets until there are no tweets left to grab while len(a_ ) > 0: print(F'''getting tweets before {oldest}''' ) # all subsequent requests use the max_id param to prevent duplicates __A = api.user_timeline( screen_name=a_ , count=2_0_0 , max_id=a_ ) # save most recent tweets alltweets.extend(a_ ) # update the id of the oldest tweet less one __A = alltweets[-1].id - 1 print(F'''...{len(a_ )} tweets downloaded so far''' ) # transform the tweepy tweets into a 2D array that will populate the csv __A = [[tweet.id_str, tweet.created_at, tweet.text] for tweet in alltweets] # write the csv with open(F'''new_{screen_name}_tweets.csv''' , "w" ) as f: __A = csv.writer(a_ ) writer.writerow(["id", "created_at", "text"] ) writer.writerows(a_ ) if __name__ == "__main__": # pass in the username of the account you want to download get_all_tweets('FirePing32')
55
import os def UpperCAmelCase ( ) -> Any: """simple docstring""" __A = os.path.dirname(os.path.realpath(a_ ) ) __A = os.path.join(a_ , "triangle.txt" ) with open(a_ ) as f: __A = f.readlines() __A = [] for line in triangle: __A = [] for number in line.strip().split(" " ): numbers_from_line.append(int(a_ ) ) a.append(a_ ) for i in range(1 , len(a_ ) ): for j in range(len(a[i] ) ): __A = a[i - 1][j] if j != len(a[i - 1] ) else 0 __A = a[i - 1][j - 1] if j > 0 else 0 a[i][j] += max(a_ , a_ ) return max(a[-1] ) if __name__ == "__main__": print(solution())
55
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) SCREAMING_SNAKE_CASE :List[Any] = {'configuration_xglm': ['XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP', 'XGLMConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE :Any = ['XGLMTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE :Optional[int] = ['XGLMTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE :Tuple = [ 'XGLM_PRETRAINED_MODEL_ARCHIVE_LIST', 'XGLMForCausalLM', 'XGLMModel', 'XGLMPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE :Dict = [ 'FlaxXGLMForCausalLM', 'FlaxXGLMModel', 'FlaxXGLMPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE :Any = [ 'TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFXGLMForCausalLM', 'TFXGLMModel', 'TFXGLMPreTrainedModel', ] if TYPE_CHECKING: from .configuration_xglm import XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XGLMConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm import XGLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm_fast import XGLMTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xglm import XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, XGLMForCausalLM, XGLMModel, XGLMPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_xglm import FlaxXGLMForCausalLM, FlaxXGLMModel, FlaxXGLMPreTrainedModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, TFXGLMPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE :str = _LazyModule(__name__, globals()['__file__'], _import_structure)
55
import re from flax.core.frozen_dict import freeze from flax.traverse_util import flatten_dict, unflatten_dict from jax.experimental import PartitionSpec as P # Sentinels SCREAMING_SNAKE_CASE :Union[str, Any] = object() # For specifying empty leaf dict `{}` SCREAMING_SNAKE_CASE :List[str] = object() def UpperCAmelCase ( a_ , a_ ) -> Tuple: """simple docstring""" __A = tuple((re.compile(x + "$" ) for x in qs) ) for i in range(len(a_ ) - len(a_ ) + 1 ): __A = [x.match(a_ ) for x, y in zip(a_ , ks[i:] )] if matches and all(a_ ): return True return False def UpperCAmelCase ( a_ ) -> Optional[int]: """simple docstring""" def replace(a_ , a_ ): for rule, replacement in rules: if _match(a_ , a_ ): return replacement return val return replace def UpperCAmelCase ( ) -> int: """simple docstring""" return [ # embeddings (("transformer", "wpe", "embedding"), P("mp" , a_ )), (("transformer", "wte", "embedding"), P("mp" , a_ )), # atention (("attention", "(q_proj|k_proj|v_proj)", "kernel"), P(a_ , "mp" )), (("attention", "out_proj", "kernel"), P("mp" , a_ )), (("attention", "out_proj", "bias"), None), # mlp (("mlp", "c_fc", "kernel"), P(a_ , "mp" )), (("mlp", "c_fc", "bias"), P("mp" )), (("mlp", "c_proj", "kernel"), P("mp" , a_ )), (("mlp", "c_proj", "bias"), None), # layer norms ((r"ln_\d+", "bias"), None), ((r"\d+", r"ln_\d+", "scale"), None), (("ln_f", "bias"), None), (("ln_f", "scale"), None), ] def UpperCAmelCase ( a_ ) -> List[Any]: """simple docstring""" __A = _get_partition_rules() __A = _replacement_rules(a_ ) __A = {k: _unmatched for k in flatten_dict(a_ )} __A = {k: replace(a_ , a_ ) for k, v in initd.items()} assert _unmatched not in result.values(), "Incomplete partition spec." return freeze(unflatten_dict(a_ ) )
55
1
import importlib import os from dataclasses import dataclass from enum import Enum from typing import Any, Dict, Optional, Union import torch from ..utils import BaseOutput SCREAMING_SNAKE_CASE :Optional[Any] = 'scheduler_config.json' class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = 1 snake_case_ = 2 snake_case_ = 3 snake_case_ = 4 snake_case_ = 5 snake_case_ = 6 snake_case_ = 7 snake_case_ = 8 snake_case_ = 9 snake_case_ = 10 snake_case_ = 11 snake_case_ = 12 snake_case_ = 13 snake_case_ = 14 @dataclass class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = 42 class UpperCAmelCase : '''simple docstring''' snake_case_ = SCHEDULER_CONFIG_NAME snake_case_ = [] snake_case_ = True @classmethod def UpperCamelCase_ ( cls : Union[str, Any] ,A : Dict[str, Any] = None ,A : Optional[str] = None ,A : str=False ,**A : List[Any] ,): __A , __A , __A = cls.load_config( pretrained_model_name_or_path=A ,subfolder=A ,return_unused_kwargs=A ,return_commit_hash=A ,**A ,) return cls.from_config(A ,return_unused_kwargs=A ,**A ) def UpperCamelCase_ ( self : Any ,A : Union[str, os.PathLike] ,A : bool = False ,**A : Dict ): self.save_config(save_directory=A ,push_to_hub=A ,**A ) @property def UpperCamelCase_ ( self : Optional[Any] ): return self._get_compatibles() @classmethod def UpperCamelCase_ ( cls : List[str] ): __A = list(set([cls.__name__] + cls._compatibles ) ) __A = importlib.import_module(__name__.split("." )[0] ) __A = [ getattr(A ,A ) for c in compatible_classes_str if hasattr(A ,A ) ] return compatible_classes
55
from __future__ import annotations import inspect import unittest import numpy as np from transformers import DeiTConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, TFDeiTModel, ) from transformers.models.deit.modeling_tf_deit import TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class UpperCAmelCase : '''simple docstring''' def __init__( self : List[Any] ,A : Union[str, Any] ,A : List[Any]=13 ,A : Optional[Any]=30 ,A : Union[str, Any]=2 ,A : Union[str, Any]=3 ,A : Any=True ,A : Dict=True ,A : str=32 ,A : Tuple=2 ,A : Optional[int]=4 ,A : Tuple=37 ,A : List[Any]="gelu" ,A : Dict=0.1 ,A : Optional[int]=0.1 ,A : List[Any]=10 ,A : Optional[Any]=0.02 ,A : Dict=3 ,A : Dict=None ,A : List[Any]=2 ,): __A = parent __A = batch_size __A = image_size __A = patch_size __A = num_channels __A = is_training __A = use_labels __A = hidden_size __A = num_hidden_layers __A = num_attention_heads __A = intermediate_size __A = hidden_act __A = hidden_dropout_prob __A = attention_probs_dropout_prob __A = type_sequence_label_size __A = initializer_range __A = scope __A = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) __A = (image_size // patch_size) ** 2 __A = num_patches + 2 def UpperCamelCase_ ( self : List[Any] ): __A = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __A = None if self.use_labels: __A = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) __A = self.get_config() return config, pixel_values, labels def UpperCamelCase_ ( self : Optional[int] ): return DeiTConfig( image_size=self.image_size ,patch_size=self.patch_size ,num_channels=self.num_channels ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,hidden_act=self.hidden_act ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,is_decoder=A ,initializer_range=self.initializer_range ,encoder_stride=self.encoder_stride ,) def UpperCamelCase_ ( self : List[str] ,A : List[Any] ,A : Optional[int] ,A : Union[str, Any] ): __A = TFDeiTModel(config=A ) __A = model(A ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase_ ( self : List[Any] ,A : List[Any] ,A : Optional[Any] ,A : Dict ): __A = TFDeiTForMaskedImageModeling(config=A ) __A = model(A ) self.parent.assertEqual( result.reconstruction.shape ,(self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images __A = 1 __A = TFDeiTForMaskedImageModeling(A ) __A = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __A = model(A ) self.parent.assertEqual(result.reconstruction.shape ,(self.batch_size, 1, self.image_size, self.image_size) ) def UpperCamelCase_ ( self : Optional[Any] ,A : Union[str, Any] ,A : Dict ,A : Union[str, Any] ): __A = self.type_sequence_label_size __A = TFDeiTForImageClassification(A ) __A = model(A ,labels=A ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) # test greyscale images __A = 1 __A = TFDeiTForImageClassification(A ) __A = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __A = model(A ,labels=A ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) def UpperCamelCase_ ( self : str ): __A = self.prepare_config_and_inputs() __A , __A , __A = config_and_inputs __A = {"pixel_values": pixel_values} return config, inputs_dict @require_tf class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = ( ( TFDeiTModel, TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, ) if is_tf_available() else () ) snake_case_ = ( { "feature-extraction": TFDeiTModel, "image-classification": (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher), } if is_tf_available() else {} ) snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = False def UpperCamelCase_ ( self : str ): __A = TFDeiTModelTester(self ) __A = ConfigTester(self ,config_class=A ,has_text_modality=A ,hidden_size=37 ) def UpperCamelCase_ ( self : Any ): self.config_tester.run_common_tests() @unittest.skip(reason="DeiT does not use inputs_embeds" ) def UpperCamelCase_ ( self : Union[str, Any] ): pass def UpperCamelCase_ ( self : List[Any] ): __A , __A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __A = model_class(A ) self.assertIsInstance(model.get_input_embeddings() ,(tf.keras.layers.Layer) ) __A = model.get_output_embeddings() self.assertTrue(x is None or isinstance(A ,tf.keras.layers.Dense ) ) def UpperCamelCase_ ( self : Union[str, Any] ): __A , __A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __A = model_class(A ) __A = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __A = [*signature.parameters.keys()] __A = ["pixel_values"] self.assertListEqual(arg_names[:1] ,A ) def UpperCamelCase_ ( self : Union[str, Any] ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A ) def UpperCamelCase_ ( self : Union[str, Any] ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*A ) def UpperCamelCase_ ( self : Optional[Any] ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*A ) def UpperCamelCase_ ( self : Optional[int] ,A : Union[str, Any] ,A : List[str] ,A : Optional[Any]=False ): __A = super()._prepare_for_class(A ,A ,return_labels=A ) if return_labels: if "labels" in inputs_dict and "labels" not in inspect.signature(model_class.call ).parameters: del inputs_dict["labels"] return inputs_dict @slow def UpperCamelCase_ ( self : Any ): for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __A = TFDeiTModel.from_pretrained(A ) self.assertIsNotNone(A ) def UpperCAmelCase ( ) -> str: """simple docstring""" __A = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_tf @require_vision class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def UpperCamelCase_ ( self : int ): return ( DeiTImageProcessor.from_pretrained("facebook/deit-base-distilled-patch16-224" ) if is_vision_available() else None ) @slow def UpperCamelCase_ ( self : Optional[int] ): __A = TFDeiTForImageClassificationWithTeacher.from_pretrained("facebook/deit-base-distilled-patch16-224" ) __A = self.default_image_processor __A = prepare_img() __A = image_processor(images=A ,return_tensors="tf" ) # forward pass __A = model(**A ) # verify the logits __A = tf.TensorShape((1, 10_00) ) self.assertEqual(outputs.logits.shape ,A ) __A = tf.constant([-1.02_66, 0.19_12, -1.28_61] ) self.assertTrue(np.allclose(outputs.logits[0, :3] ,A ,atol=1E-4 ) )
55
1
from scipy.stats import pearsonr, spearmanr from sklearn.metrics import fa_score, matthews_corrcoef import datasets SCREAMING_SNAKE_CASE :Optional[Any] = '\\n@inproceedings{wang2019glue,\n title={{GLUE}: A Multi-Task Benchmark and Analysis Platform for Natural Language Understanding},\n author={Wang, Alex and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R.},\n note={In the Proceedings of ICLR.},\n year={2019}\n}\n' SCREAMING_SNAKE_CASE :Tuple = '\\nGLUE, the General Language Understanding Evaluation benchmark\n(https://gluebenchmark.com/) is a collection of resources for training,\nevaluating, and analyzing natural language understanding systems.\n' SCREAMING_SNAKE_CASE :Tuple = '\nCompute GLUE evaluation metric associated to each GLUE dataset.\nArgs:\n predictions: list of predictions to score.\n Each translation should be tokenized into a list of tokens.\n references: list of lists of references for each translation.\n Each reference should be tokenized into a list of tokens.\nReturns: depending on the GLUE subset, one or several of:\n "accuracy": Accuracy\n "f1": F1 score\n "pearson": Pearson Correlation\n "spearmanr": Spearman Correlation\n "matthews_correlation": Matthew Correlation\nExamples:\n\n >>> glue_metric = datasets.load_metric(\'glue\', \'sst2\') # \'sst2\' or any of ["mnli", "mnli_mismatched", "mnli_matched", "qnli", "rte", "wnli", "hans"]\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0}\n\n >>> glue_metric = datasets.load_metric(\'glue\', \'mrpc\') # \'mrpc\' or \'qqp\'\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0, \'f1\': 1.0}\n\n >>> glue_metric = datasets.load_metric(\'glue\', \'stsb\')\n >>> references = [0., 1., 2., 3., 4., 5.]\n >>> predictions = [0., 1., 2., 3., 4., 5.]\n >>> results = glue_metric.compute(predictions=predictions, references=references)\n >>> print({"pearson": round(results["pearson"], 2), "spearmanr": round(results["spearmanr"], 2)})\n {\'pearson\': 1.0, \'spearmanr\': 1.0}\n\n >>> glue_metric = datasets.load_metric(\'glue\', \'cola\')\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'matthews_correlation\': 1.0}\n' def UpperCAmelCase ( a_ , a_ ) -> str: """simple docstring""" return float((preds == labels).mean() ) def UpperCAmelCase ( a_ , a_ ) -> str: """simple docstring""" __A = simple_accuracy(a_ , a_ ) __A = float(fa_score(y_true=a_ , y_pred=a_ ) ) return { "accuracy": acc, "f1": fa, } def UpperCAmelCase ( a_ , a_ ) -> List[Any]: """simple docstring""" __A = float(pearsonr(a_ , a_ )[0] ) __A = float(spearmanr(a_ , a_ )[0] ) return { "pearson": pearson_corr, "spearmanr": spearman_corr, } @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCAmelCase ( datasets.Metric ): '''simple docstring''' def UpperCamelCase_ ( self : str ): if self.config_name not in [ "sst2", "mnli", "mnli_mismatched", "mnli_matched", "cola", "stsb", "mrpc", "qqp", "qnli", "rte", "wnli", "hans", ]: raise KeyError( "You should supply a configuration name selected in " "[\"sst2\", \"mnli\", \"mnli_mismatched\", \"mnli_matched\", " "\"cola\", \"stsb\", \"mrpc\", \"qqp\", \"qnli\", \"rte\", \"wnli\", \"hans\"]" ) return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { "predictions": datasets.Value("int64" if self.config_name != "stsb" else "float32" ), "references": datasets.Value("int64" if self.config_name != "stsb" else "float32" ), } ) ,codebase_urls=[] ,reference_urls=[] ,format="numpy" ,) def UpperCamelCase_ ( self : List[str] ,A : List[str] ,A : Dict ): if self.config_name == "cola": return {"matthews_correlation": matthews_corrcoef(A ,A )} elif self.config_name == "stsb": return pearson_and_spearman(A ,A ) elif self.config_name in ["mrpc", "qqp"]: return acc_and_fa(A ,A ) elif self.config_name in ["sst2", "mnli", "mnli_mismatched", "mnli_matched", "qnli", "rte", "wnli", "hans"]: return {"accuracy": simple_accuracy(A ,A )} else: raise KeyError( "You should supply a configuration name selected in " "[\"sst2\", \"mnli\", \"mnli_mismatched\", \"mnli_matched\", " "\"cola\", \"stsb\", \"mrpc\", \"qqp\", \"qnli\", \"rte\", \"wnli\", \"hans\"]" )
55
SCREAMING_SNAKE_CASE :List[Any] = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] SCREAMING_SNAKE_CASE :Union[str, Any] = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] SCREAMING_SNAKE_CASE :int = { 0: 'Sunday', 1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday', 5: 'Friday', 6: 'Saturday', } def UpperCAmelCase ( a_ , a_ , a_ ) -> str: """simple docstring""" assert len(str(a_ ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 1_2, "month should be between 1 to 12" assert 1 <= day <= 3_1, "day should be between 1 to 31" # Doomsday algorithm: __A = year // 1_0_0 __A = (5 * (century % 4) + 2) % 7 __A = year % 1_0_0 __A = centurian % 1_2 __A = ( (centurian // 1_2) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 __A = ( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 4_0_0) == 0) else DOOMSDAY_LEAP[month - 1] ) __A = (dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
55
1
import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartTokenizer, MBartTokenizerFast, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin SCREAMING_SNAKE_CASE :List[str] = get_tests_dir('fixtures/test_sentencepiece.model') if is_torch_available(): from transformers.models.mbart.modeling_mbart import shift_tokens_right SCREAMING_SNAKE_CASE :Any = 25_0004 SCREAMING_SNAKE_CASE :Tuple = 25_0020 @require_sentencepiece @require_tokenizers class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = MBartTokenizer snake_case_ = MBartTokenizerFast snake_case_ = True snake_case_ = True def UpperCamelCase_ ( self : Dict ): super().setUp() # We have a SentencePiece fixture for testing __A = MBartTokenizer(A ,keep_accents=A ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCamelCase_ ( self : int ): __A = MBartTokenizer(A ,keep_accents=A ) __A = tokenizer.tokenize("This is a test" ) self.assertListEqual(A ,["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(A ) ,[value + tokenizer.fairseq_offset for value in [2_85, 46, 10, 1_70, 3_82]] ,) __A = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( A ,[ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", ".", ] ,) __A = tokenizer.convert_tokens_to_ids(A ) self.assertListEqual( A ,[ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, 2, 4] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] ,) __A = tokenizer.convert_ids_to_tokens(A ) self.assertListEqual( A ,[ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "<unk>", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "<unk>", ".", ] ,) def UpperCamelCase_ ( self : List[str] ): if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return __A = (self.rust_tokenizer_class, "hf-internal-testing/tiny-random-mbart", {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): __A = self.rust_tokenizer_class.from_pretrained(A ,**A ) __A = self.tokenizer_class.from_pretrained(A ,**A ) __A = tempfile.mkdtemp() __A = tokenizer_r.save_pretrained(A ) __A = tokenizer_p.save_pretrained(A ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any("tokenizer.json" in f for f in tokenizer_r_files ) ) __A = tuple(f for f in tokenizer_r_files if "tokenizer.json" not in f ) self.assertSequenceEqual(A ,A ) # Checks everything loads correctly in the same way __A = tokenizer_r.from_pretrained(A ) __A = tokenizer_p.from_pretrained(A ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(A ,A ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(A ) # Save tokenizer rust, legacy_format=True __A = tempfile.mkdtemp() __A = tokenizer_r.save_pretrained(A ,legacy_format=A ) __A = tokenizer_p.save_pretrained(A ) # Checks it save with the same files self.assertSequenceEqual(A ,A ) # Checks everything loads correctly in the same way __A = tokenizer_r.from_pretrained(A ) __A = tokenizer_p.from_pretrained(A ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(A ,A ) ) shutil.rmtree(A ) # Save tokenizer rust, legacy_format=False __A = tempfile.mkdtemp() __A = tokenizer_r.save_pretrained(A ,legacy_format=A ) __A = tokenizer_p.save_pretrained(A ) # Checks it saved the tokenizer.json file self.assertTrue(any("tokenizer.json" in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way __A = tokenizer_r.from_pretrained(A ) __A = tokenizer_p.from_pretrained(A ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(A ,A ) ) shutil.rmtree(A ) @require_torch @require_sentencepiece @require_tokenizers class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' snake_case_ = "facebook/mbart-large-en-ro" snake_case_ = [ " UN Chief Says There Is No Military Solution in Syria", " Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for Syria is that \"there is no military solution\" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.", ] snake_case_ = [ "Şeful ONU declară că nu există o soluţie militară în Siria", "Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei" " pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi că noi arme nu vor" " face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.", ] snake_case_ = [8274, 127873, 25916, 7, 8622, 2071, 438, 67485, 53, 187895, 23, 51712, 2, EN_CODE] @classmethod def UpperCamelCase_ ( cls : Optional[int] ): __A = MBartTokenizer.from_pretrained( cls.checkpoint_name ,src_lang="en_XX" ,tgt_lang="ro_RO" ) __A = 1 return cls def UpperCamelCase_ ( self : Any ): self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["ar_AR"] ,25_00_01 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["en_EN"] ,25_00_04 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["ro_RO"] ,25_00_20 ) def UpperCamelCase_ ( self : Optional[int] ): __A = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens ,A ) def UpperCamelCase_ ( self : Union[str, Any] ): self.assertIn(A ,self.tokenizer.all_special_ids ) __A = [RO_CODE, 8_84, 90_19, 96, 9, 9_16, 8_67_92, 36, 1_87_43, 1_55_96, 5, 2] __A = self.tokenizer.decode(A ,skip_special_tokens=A ) __A = self.tokenizer.decode(generated_ids[1:] ,skip_special_tokens=A ) self.assertEqual(A ,A ) self.assertNotIn(self.tokenizer.eos_token ,A ) def UpperCamelCase_ ( self : int ): __A = ["this is gunna be a long sentence " * 20] assert isinstance(src_text[0] ,A ) __A = 10 __A = self.tokenizer(A ,max_length=A ,truncation=A ).input_ids[0] self.assertEqual(ids[-2] ,2 ) self.assertEqual(ids[-1] ,A ) self.assertEqual(len(A ) ,A ) def UpperCamelCase_ ( self : Any ): self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["<mask>", "ar_AR"] ) ,[25_00_26, 25_00_01] ) def UpperCamelCase_ ( self : Union[str, Any] ): __A = tempfile.mkdtemp() __A = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(A ) __A = MBartTokenizer.from_pretrained(A ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids ,A ) @require_torch def UpperCamelCase_ ( self : Tuple ): __A = self.tokenizer(self.src_text ,text_target=self.tgt_text ,padding=A ,return_tensors="pt" ) __A = shift_tokens_right(batch["labels"] ,self.tokenizer.pad_token_id ) # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 assert batch.input_ids[1][-2:].tolist() == [2, EN_CODE] assert batch.decoder_input_ids[1][0].tolist() == RO_CODE assert batch.decoder_input_ids[1][-1] == 2 assert batch.labels[1][-2:].tolist() == [2, RO_CODE] @require_torch def UpperCamelCase_ ( self : Any ): __A = self.tokenizer( self.src_text ,text_target=self.tgt_text ,padding=A ,truncation=A ,max_length=len(self.expected_src_tokens ) ,return_tensors="pt" ,) __A = shift_tokens_right(batch["labels"] ,self.tokenizer.pad_token_id ) self.assertIsInstance(A ,A ) self.assertEqual((2, 14) ,batch.input_ids.shape ) self.assertEqual((2, 14) ,batch.attention_mask.shape ) __A = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens ,A ) self.assertEqual(2 ,batch.decoder_input_ids[0, -1] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens ,[] ) self.assertEqual(self.tokenizer.suffix_tokens ,[self.tokenizer.eos_token_id, EN_CODE] ) def UpperCamelCase_ ( self : Optional[int] ): __A = self.tokenizer(self.src_text ,padding=A ,truncation=A ,max_length=3 ,return_tensors="pt" ) __A = self.tokenizer( text_target=self.tgt_text ,padding=A ,truncation=A ,max_length=10 ,return_tensors="pt" ) __A = targets["input_ids"] __A = shift_tokens_right(A ,self.tokenizer.pad_token_id ) self.assertEqual(batch.input_ids.shape[1] ,3 ) self.assertEqual(batch.decoder_input_ids.shape[1] ,10 ) @require_torch def UpperCamelCase_ ( self : str ): __A = self.tokenizer._build_translation_inputs( "A test" ,return_tensors="pt" ,src_lang="en_XX" ,tgt_lang="ar_AR" ) self.assertEqual( nested_simplify(A ) ,{ # A, test, EOS, en_XX "input_ids": [[62, 30_34, 2, 25_00_04]], "attention_mask": [[1, 1, 1, 1]], # ar_AR "forced_bos_token_id": 25_00_01, } ,)
55
from json import JSONDecodeError # Workaround for requests.exceptions.JSONDecodeError import requests def UpperCAmelCase ( a_ = "isbn/0140328726" ) -> dict: """simple docstring""" __A = olid.strip().strip("/" ) # Remove leading/trailing whitespace & slashes if new_olid.count("/" ) != 1: __A = F'''{olid} is not a valid Open Library olid''' raise ValueError(a_ ) return requests.get(F'''https://openlibrary.org/{new_olid}.json''' ).json() def UpperCAmelCase ( a_ ) -> dict: """simple docstring""" __A = { "title": "Title", "publish_date": "Publish date", "authors": "Authors", "number_of_pages": "Number of pages:", "first_sentence": "First sentence", "isbn_10": "ISBN (10)", "isbn_13": "ISBN (13)", } __A = {better_key: ol_book_data[key] for key, better_key in desired_keys.items()} __A = [ get_openlibrary_data(author["key"] )["name"] for author in data["Authors"] ] __A = data["First sentence"]["value"] for key, value in data.items(): if isinstance(a_ , a_ ): __A = ", ".join(a_ ) return data if __name__ == "__main__": import doctest doctest.testmod() while True: SCREAMING_SNAKE_CASE :int = input('\nEnter the ISBN code to search (or \'quit\' to stop): ').strip() if isbn.lower() in ("", "q", "quit", "exit", "stop"): break if len(isbn) not in (10, 13) or not isbn.isdigit(): print(f'''Sorry, {isbn} is not a valid ISBN. Please, input a valid ISBN.''') continue print(f'''\nSearching Open Library for ISBN: {isbn}...\n''') try: SCREAMING_SNAKE_CASE :Any = summarize_book(get_openlibrary_data(f'''isbn/{isbn}''')) print('\n'.join(f'''{key}: {value}''' for key, value in book_summary.items())) except JSONDecodeError: # Workaround for requests.exceptions.RequestException: print(f'''Sorry, there are no results for ISBN: {isbn}.''')
55
1
import inspect import unittest from transformers import MobileNetVaConfig 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 MobileNetVaForImageClassification, MobileNetVaModel from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileNetVaImageProcessor class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def UpperCamelCase_ ( self : Any ): __A = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(A ,"tf_padding" ) ) self.parent.assertTrue(hasattr(A ,"depth_multiplier" ) ) class UpperCAmelCase : '''simple docstring''' def __init__( self : Optional[Any] ,A : int ,A : List[Any]=13 ,A : int=3 ,A : Optional[Any]=32 ,A : Union[str, Any]=0.25 ,A : Tuple=8 ,A : Optional[int]=True ,A : Union[str, Any]=10_24 ,A : Any=32 ,A : Optional[int]="relu6" ,A : int=0.1 ,A : Optional[Any]=0.02 ,A : Optional[Any]=True ,A : List[str]=True ,A : str=10 ,A : str=None ,): __A = parent __A = batch_size __A = num_channels __A = image_size __A = depth_multiplier __A = min_depth __A = tf_padding __A = int(last_hidden_size * depth_multiplier ) __A = output_stride __A = hidden_act __A = classifier_dropout_prob __A = use_labels __A = is_training __A = num_labels __A = initializer_range __A = scope def UpperCamelCase_ ( self : Optional[int] ): __A = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __A = None __A = None if self.use_labels: __A = ids_tensor([self.batch_size] ,self.num_labels ) __A = ids_tensor([self.batch_size, self.image_size, self.image_size] ,self.num_labels ) __A = self.get_config() return config, pixel_values, labels, pixel_labels def UpperCamelCase_ ( self : Any ): return MobileNetVaConfig( num_channels=self.num_channels ,image_size=self.image_size ,depth_multiplier=self.depth_multiplier ,min_depth=self.min_depth ,tf_padding=self.tf_padding ,hidden_act=self.hidden_act ,classifier_dropout_prob=self.classifier_dropout_prob ,initializer_range=self.initializer_range ,) def UpperCamelCase_ ( self : Optional[int] ,A : str ,A : Tuple ,A : Optional[int] ,A : List[str] ): __A = MobileNetVaModel(config=A ) model.to(A ) model.eval() __A = model(A ) self.parent.assertEqual( result.last_hidden_state.shape ,( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) ,) def UpperCamelCase_ ( self : List[Any] ,A : Union[str, Any] ,A : List[Any] ,A : int ,A : Union[str, Any] ): __A = self.num_labels __A = MobileNetVaForImageClassification(A ) model.to(A ) model.eval() __A = model(A ,labels=A ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def UpperCamelCase_ ( self : Tuple ): __A = self.prepare_config_and_inputs() __A , __A , __A , __A = config_and_inputs __A = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = (MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else () snake_case_ = ( {"feature-extraction": MobileNetVaModel, "image-classification": MobileNetVaForImageClassification} if is_torch_available() else {} ) snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = False def UpperCamelCase_ ( self : Any ): __A = MobileNetVaModelTester(self ) __A = MobileNetVaConfigTester(self ,config_class=A ,has_text_modality=A ) def UpperCamelCase_ ( self : str ): self.config_tester.run_common_tests() @unittest.skip(reason="MobileNetV1 does not use inputs_embeds" ) def UpperCamelCase_ ( self : Union[str, Any] ): pass @unittest.skip(reason="MobileNetV1 does not support input and output embeddings" ) def UpperCamelCase_ ( self : Tuple ): pass @unittest.skip(reason="MobileNetV1 does not output attentions" ) def UpperCamelCase_ ( self : Any ): pass def UpperCamelCase_ ( self : Optional[int] ): __A , __A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __A = model_class(A ) __A = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __A = [*signature.parameters.keys()] __A = ["pixel_values"] self.assertListEqual(arg_names[:1] ,A ) def UpperCamelCase_ ( self : List[Any] ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A ) def UpperCamelCase_ ( self : Optional[int] ): def check_hidden_states_output(A : List[Any] ,A : List[Any] ,A : Optional[int] ): __A = model_class(A ) model.to(A ) model.eval() with torch.no_grad(): __A = model(**self._prepare_for_class(A ,A ) ) __A = outputs.hidden_states __A = 26 self.assertEqual(len(A ) ,A ) __A , __A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __A = True check_hidden_states_output(A ,A ,A ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __A = True check_hidden_states_output(A ,A ,A ) def UpperCamelCase_ ( self : Tuple ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*A ) @slow def UpperCamelCase_ ( self : Union[str, Any] ): for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __A = MobileNetVaModel.from_pretrained(A ) self.assertIsNotNone(A ) def UpperCAmelCase ( ) -> str: """simple docstring""" __A = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def UpperCamelCase_ ( self : List[str] ): return ( MobileNetVaImageProcessor.from_pretrained("google/mobilenet_v1_1.0_224" ) if is_vision_available() else None ) @slow def UpperCamelCase_ ( self : Optional[Any] ): __A = MobileNetVaForImageClassification.from_pretrained("google/mobilenet_v1_1.0_224" ).to(A ) __A = self.default_image_processor __A = prepare_img() __A = image_processor(images=A ,return_tensors="pt" ).to(A ) # forward pass with torch.no_grad(): __A = model(**A ) # verify the logits __A = torch.Size((1, 10_01) ) self.assertEqual(outputs.logits.shape ,A ) __A = torch.tensor([-4.17_39, -1.12_33, 3.12_05] ).to(A ) self.assertTrue(torch.allclose(outputs.logits[0, :3] ,A ,atol=1E-4 ) )
55
import requests SCREAMING_SNAKE_CASE :List[str] = 'YOUR API KEY' def UpperCAmelCase ( a_ , a_ = giphy_api_key ) -> list: """simple docstring""" __A = "+".join(query.split() ) __A = F'''https://api.giphy.com/v1/gifs/search?q={formatted_query}&api_key={api_key}''' __A = requests.get(a_ ).json()["data"] return [gif["url"] for gif in gifs] if __name__ == "__main__": print('\n'.join(get_gifs('space ship')))
55
1
def UpperCAmelCase ( a_ ) -> bool: """simple docstring""" if not isinstance(a_ , a_ ): __A = F'''Input value of [number={number}] must be an integer''' raise TypeError(a_ ) if number < 0: return False __A = number * number while number > 0: if number % 1_0 != number_square % 1_0: return False number //= 1_0 number_square //= 1_0 return True if __name__ == "__main__": import doctest doctest.testmod()
55
import itertools import math def UpperCAmelCase ( a_ ) -> bool: """simple docstring""" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(a_ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def UpperCAmelCase ( ) -> Optional[Any]: """simple docstring""" __A = 2 while True: if is_prime(a_ ): yield num num += 1 def UpperCAmelCase ( a_ = 1_0_0_0_1 ) -> int: """simple docstring""" return next(itertools.islice(prime_generator() , nth - 1 , a_ ) ) if __name__ == "__main__": print(f'''{solution() = }''')
55
1
from dataclasses import asdict, dataclass from typing import Optional from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE :Dict = logging.get_logger(__name__) # TODO Update this SCREAMING_SNAKE_CASE :Dict = { 'facebook/esm-1b': 'https://huggingface.co/facebook/esm-1b/resolve/main/config.json', # See all ESM models at https://huggingface.co/models?filter=esm } class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = "esm" def __init__( self : List[str] ,A : Dict=None ,A : Tuple=None ,A : Any=None ,A : Optional[Any]=7_68 ,A : Tuple=12 ,A : List[str]=12 ,A : Tuple=30_72 ,A : List[str]=0.1 ,A : List[Any]=0.1 ,A : int=10_26 ,A : List[str]=0.02 ,A : Union[str, Any]=1E-12 ,A : List[Any]="absolute" ,A : List[Any]=True ,A : Union[str, Any]=None ,A : Optional[int]=False ,A : Dict=False ,A : Tuple=None ,A : Optional[int]=None ,**A : List[Any] ,): super().__init__(pad_token_id=A ,mask_token_id=A ,**A ) __A = vocab_size __A = hidden_size __A = num_hidden_layers __A = num_attention_heads __A = intermediate_size __A = hidden_dropout_prob __A = attention_probs_dropout_prob __A = max_position_embeddings __A = initializer_range __A = layer_norm_eps __A = position_embedding_type __A = use_cache __A = emb_layer_norm_before __A = token_dropout __A = is_folding_model if is_folding_model: if esmfold_config is None: logger.info("No esmfold_config supplied for folding model, using default values." ) __A = EsmFoldConfig() elif isinstance(A ,A ): __A = EsmFoldConfig(**A ) __A = esmfold_config if vocab_list is None: logger.warning("No vocab_list supplied for folding model, assuming the ESM-2 vocabulary!" ) __A = get_default_vocab_list() else: __A = vocab_list else: __A = None __A = None if self.esmfold_config is not None and getattr(self.esmfold_config ,"use_esm_attn_map" ,A ): raise ValueError("The HuggingFace port of ESMFold does not support use_esm_attn_map at this time!" ) def UpperCamelCase_ ( self : Optional[int] ): __A = super().to_dict() if isinstance(self.esmfold_config ,A ): __A = self.esmfold_config.to_dict() return output @dataclass class UpperCAmelCase : '''simple docstring''' snake_case_ = None snake_case_ = True snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = 0 snake_case_ = True snake_case_ = False snake_case_ = 128 snake_case_ = None def UpperCamelCase_ ( self : List[Any] ): if self.trunk is None: __A = TrunkConfig() elif isinstance(self.trunk ,A ): __A = TrunkConfig(**self.trunk ) def UpperCamelCase_ ( self : Optional[Any] ): __A = asdict(self ) __A = self.trunk.to_dict() return output @dataclass class UpperCAmelCase : '''simple docstring''' snake_case_ = 48 snake_case_ = 1024 snake_case_ = 128 snake_case_ = 32 snake_case_ = 32 snake_case_ = 32 snake_case_ = 0 snake_case_ = 0 snake_case_ = False snake_case_ = 4 snake_case_ = 128 snake_case_ = None def UpperCamelCase_ ( self : List[Any] ): if self.structure_module is None: __A = StructureModuleConfig() elif isinstance(self.structure_module ,A ): __A = StructureModuleConfig(**self.structure_module ) if self.max_recycles <= 0: raise ValueError(f'''`max_recycles` should be positive, got {self.max_recycles}.''' ) if self.sequence_state_dim % self.sequence_state_dim != 0: raise ValueError( "`sequence_state_dim` should be a round multiple of `sequence_state_dim`, got" f''' {self.sequence_state_dim} and {self.sequence_state_dim}.''' ) if self.pairwise_state_dim % self.pairwise_state_dim != 0: raise ValueError( "`pairwise_state_dim` should be a round multiple of `pairwise_state_dim`, got" f''' {self.pairwise_state_dim} and {self.pairwise_state_dim}.''' ) __A = self.sequence_state_dim // self.sequence_head_width __A = self.pairwise_state_dim // self.pairwise_head_width if self.sequence_state_dim != sequence_num_heads * self.sequence_head_width: raise ValueError( "`sequence_state_dim` should be equal to `sequence_num_heads * sequence_head_width, got" f''' {self.sequence_state_dim} != {sequence_num_heads} * {self.sequence_head_width}.''' ) if self.pairwise_state_dim != pairwise_num_heads * self.pairwise_head_width: raise ValueError( "`pairwise_state_dim` should be equal to `pairwise_num_heads * pairwise_head_width, got" f''' {self.pairwise_state_dim} != {pairwise_num_heads} * {self.pairwise_head_width}.''' ) if self.pairwise_state_dim % 2 != 0: raise ValueError(f'''`pairwise_state_dim` should be even, got {self.pairwise_state_dim}.''' ) if self.dropout >= 0.4: raise ValueError(f'''`dropout` should not be greater than 0.4, got {self.dropout}.''' ) def UpperCamelCase_ ( self : Tuple ): __A = asdict(self ) __A = self.structure_module.to_dict() return output @dataclass class UpperCAmelCase : '''simple docstring''' snake_case_ = 384 snake_case_ = 128 snake_case_ = 16 snake_case_ = 128 snake_case_ = 12 snake_case_ = 4 snake_case_ = 8 snake_case_ = 0.1 snake_case_ = 8 snake_case_ = 1 snake_case_ = 2 snake_case_ = 7 snake_case_ = 10 snake_case_ = 1E-8 snake_case_ = 1E5 def UpperCamelCase_ ( self : Union[str, Any] ): return asdict(self ) def UpperCAmelCase ( ) -> int: """simple docstring""" return ( "<cls>", "<pad>", "<eos>", "<unk>", "L", "A", "G", "V", "S", "E", "R", "T", "I", "D", "P", "K", "Q", "N", "F", "Y", "M", "H", "W", "C", "X", "B", "U", "Z", "O", ".", "-", "<null_1>", "<mask>", )
55
import argparse import os import numpy as np import tensorflow as tf import torch from transformers import BertModel def UpperCAmelCase ( a_ , a_ , a_ ) -> List[str]: """simple docstring""" __A = ("dense.weight", "attention.self.query", "attention.self.key", "attention.self.value") __A = ( ("layer.", "layer_"), ("word_embeddings.weight", "word_embeddings"), ("position_embeddings.weight", "position_embeddings"), ("token_type_embeddings.weight", "token_type_embeddings"), (".", "/"), ("LayerNorm/weight", "LayerNorm/gamma"), ("LayerNorm/bias", "LayerNorm/beta"), ("weight", "kernel"), ) if not os.path.isdir(a_ ): os.makedirs(a_ ) __A = model.state_dict() def to_tf_var_name(a_ ): for patt, repl in iter(a_ ): __A = name.replace(a_ , a_ ) return F'''bert/{name}''' def create_tf_var(a_ , a_ , a_ ): __A = tf.dtypes.as_dtype(tensor.dtype ) __A = tf.get_variable(dtype=a_ , shape=tensor.shape , name=a_ , initializer=tf.zeros_initializer() ) session.run(tf.variables_initializer([tf_var] ) ) session.run(a_ ) return tf_var tf.reset_default_graph() with tf.Session() as session: for var_name in state_dict: __A = to_tf_var_name(a_ ) __A = state_dict[var_name].numpy() if any(x in var_name for x in tensors_to_transpose ): __A = torch_tensor.T __A = create_tf_var(tensor=a_ , name=a_ , session=a_ ) tf.keras.backend.set_value(a_ , a_ ) __A = session.run(a_ ) print(F'''Successfully created {tf_name}: {np.allclose(a_ , a_ )}''' ) __A = tf.train.Saver(tf.trainable_variables() ) saver.save(a_ , os.path.join(a_ , model_name.replace("-" , "_" ) + ".ckpt" ) ) def UpperCAmelCase ( a_=None ) -> List[Any]: """simple docstring""" __A = argparse.ArgumentParser() parser.add_argument("--model_name" , type=a_ , required=a_ , help="model name e.g. bert-base-uncased" ) parser.add_argument( "--cache_dir" , type=a_ , default=a_ , required=a_ , help="Directory containing pytorch model" ) parser.add_argument("--pytorch_model_path" , type=a_ , required=a_ , help="/path/to/<pytorch-model-name>.bin" ) parser.add_argument("--tf_cache_dir" , type=a_ , required=a_ , help="Directory in which to save tensorflow model" ) __A = parser.parse_args(a_ ) __A = BertModel.from_pretrained( pretrained_model_name_or_path=args.model_name , state_dict=torch.load(args.pytorch_model_path ) , cache_dir=args.cache_dir , ) convert_pytorch_checkpoint_to_tf(model=a_ , ckpt_dir=args.tf_cache_dir , model_name=args.model_name ) if __name__ == "__main__": main()
55
1
from timeit import timeit def UpperCAmelCase ( a_ ) -> int: """simple docstring""" if number < 0: raise ValueError("the value of input must not be negative" ) __A = 0 while number: number &= number - 1 result += 1 return result def UpperCAmelCase ( a_ ) -> int: """simple docstring""" if number < 0: raise ValueError("the value of input must not be negative" ) __A = 0 while number: if number % 2 == 1: result += 1 number >>= 1 return result def UpperCAmelCase ( ) -> None: """simple docstring""" def do_benchmark(a_ ) -> None: __A = "import __main__ as z" print(F'''Benchmark when {number = }:''' ) print(F'''{get_set_bits_count_using_modulo_operator(a_ ) = }''' ) __A = timeit("z.get_set_bits_count_using_modulo_operator(25)" , setup=a_ ) print(F'''timeit() runs in {timing} seconds''' ) print(F'''{get_set_bits_count_using_brian_kernighans_algorithm(a_ ) = }''' ) __A = timeit( "z.get_set_bits_count_using_brian_kernighans_algorithm(25)" , setup=a_ , ) print(F'''timeit() runs in {timing} seconds''' ) for number in (2_5, 3_7, 5_8, 0): do_benchmark(a_ ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
55
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE :Any = { 'configuration_pegasus_x': ['PEGASUS_X_PRETRAINED_CONFIG_ARCHIVE_MAP', 'PegasusXConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE :Any = [ 'PEGASUS_X_PRETRAINED_MODEL_ARCHIVE_LIST', 'PegasusXForConditionalGeneration', 'PegasusXModel', 'PegasusXPreTrainedModel', ] if TYPE_CHECKING: from .configuration_pegasus_x import PEGASUS_X_PRETRAINED_CONFIG_ARCHIVE_MAP, PegasusXConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pegasus_x import ( PEGASUS_X_PRETRAINED_MODEL_ARCHIVE_LIST, PegasusXForConditionalGeneration, PegasusXModel, PegasusXPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE :Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
55
1
from collections import OrderedDict from typing import List, Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging SCREAMING_SNAKE_CASE :Union[str, Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE :str = { 'google/efficientnet-b7': 'https://huggingface.co/google/efficientnet-b7/resolve/main/config.json', } class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = "efficientnet" def __init__( self : Optional[int] ,A : int = 3 ,A : int = 6_00 ,A : float = 2.0 ,A : float = 3.1 ,A : int = 8 ,A : List[int] = [3, 3, 5, 3, 5, 5, 3] ,A : List[int] = [32, 16, 24, 40, 80, 1_12, 1_92] ,A : List[int] = [16, 24, 40, 80, 1_12, 1_92, 3_20] ,A : List[int] = [] ,A : List[int] = [1, 2, 2, 2, 1, 2, 1] ,A : List[int] = [1, 2, 2, 3, 3, 4, 1] ,A : List[int] = [1, 6, 6, 6, 6, 6, 6] ,A : float = 0.25 ,A : str = "swish" ,A : int = 25_60 ,A : str = "mean" ,A : float = 0.02 ,A : float = 0.0_01 ,A : float = 0.99 ,A : float = 0.5 ,A : float = 0.2 ,**A : Any ,): super().__init__(**A ) __A = num_channels __A = image_size __A = width_coefficient __A = depth_coefficient __A = depth_divisor __A = kernel_sizes __A = in_channels __A = out_channels __A = depthwise_padding __A = strides __A = num_block_repeats __A = expand_ratios __A = squeeze_expansion_ratio __A = hidden_act __A = hidden_dim __A = pooling_type __A = initializer_range __A = batch_norm_eps __A = batch_norm_momentum __A = dropout_rate __A = drop_connect_rate __A = sum(A ) * 4 class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = version.parse("1.11" ) @property def UpperCamelCase_ ( self : Any ): return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ] ) @property def UpperCamelCase_ ( self : Optional[Any] ): return 1E-5
55
from __future__ import annotations from collections.abc import Generator import requests from bsa import BeautifulSoup SCREAMING_SNAKE_CASE :int = 'https://www.indeed.co.in/jobs?q=mobile+app+development&l=' def UpperCAmelCase ( a_ = "mumbai" ) -> Generator[tuple[str, str], None, None]: """simple docstring""" __A = BeautifulSoup(requests.get(url + location ).content , "html.parser" ) # This attribute finds out all the specifics listed in a job for job in soup.find_all("div" , attrs={"data-tn-component": "organicJob"} ): __A = job.find("a" , attrs={"data-tn-element": "jobTitle"} ).text.strip() __A = job.find("span" , {"class": "company"} ).text.strip() yield job_title, company_name if __name__ == "__main__": for i, job in enumerate(fetch_jobs('Bangalore'), 1): print(f'''Job {i:>2} is {job[0]} at {job[1]}''')
55
1
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import os from ...utils.constants import SAGEMAKER_PARALLEL_EC2_INSTANCES, TORCH_DYNAMO_MODES from ...utils.dataclasses import ComputeEnvironment, SageMakerDistributedType from ...utils.imports import is_botoa_available from .config_args import SageMakerConfig from .config_utils import ( DYNAMO_BACKENDS, _ask_field, _ask_options, _convert_dynamo_backend, _convert_mixed_precision, _convert_sagemaker_distributed_mode, _convert_yes_no_to_bool, ) if is_botoa_available(): import botoa # noqa: F401 def UpperCAmelCase ( a_ ) -> Optional[int]: """simple docstring""" __A = botoa.client("iam" ) __A = { "Version": "2012-10-17", "Statement": [ {"Effect": "Allow", "Principal": {"Service": "sagemaker.amazonaws.com"}, "Action": "sts:AssumeRole"} ], } try: # create the role, associated with the chosen trust policy iam_client.create_role( RoleName=a_ , AssumeRolePolicyDocument=json.dumps(a_ , indent=2 ) ) __A = { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "sagemaker:*", "ecr:GetDownloadUrlForLayer", "ecr:BatchGetImage", "ecr:BatchCheckLayerAvailability", "ecr:GetAuthorizationToken", "cloudwatch:PutMetricData", "cloudwatch:GetMetricData", "cloudwatch:GetMetricStatistics", "cloudwatch:ListMetrics", "logs:CreateLogGroup", "logs:CreateLogStream", "logs:DescribeLogStreams", "logs:PutLogEvents", "logs:GetLogEvents", "s3:CreateBucket", "s3:ListBucket", "s3:GetBucketLocation", "s3:GetObject", "s3:PutObject", ], "Resource": "*", } ], } # attach policy to role iam_client.put_role_policy( RoleName=a_ , PolicyName=F'''{role_name}_policy_permission''' , PolicyDocument=json.dumps(a_ , indent=2 ) , ) except iam_client.exceptions.EntityAlreadyExistsException: print(F'''role {role_name} already exists. Using existing one''' ) def UpperCAmelCase ( a_ ) -> Optional[int]: """simple docstring""" __A = botoa.client("iam" ) return iam_client.get_role(RoleName=a_ )["Role"]["Arn"] def UpperCAmelCase ( ) -> Optional[int]: """simple docstring""" __A = _ask_options( "How do you want to authorize?" , ["AWS Profile", "Credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) "] , a_ , ) __A = None if credentials_configuration == 0: __A = _ask_field("Enter your AWS Profile name: [default] " , default="default" ) __A = aws_profile else: print( "Note you will need to provide AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY when you launch you training script with," "`accelerate launch --aws_access_key_id XXX --aws_secret_access_key YYY`" ) __A = _ask_field("AWS Access Key ID: " ) __A = aws_access_key_id __A = _ask_field("AWS Secret Access Key: " ) __A = aws_secret_access_key __A = _ask_field("Enter your AWS Region: [us-east-1]" , default="us-east-1" ) __A = aws_region __A = _ask_options( "Do you already have an IAM Role for executing Amazon SageMaker Training Jobs?" , ["Provide IAM Role name", "Create new IAM role using credentials"] , a_ , ) if role_management == 0: __A = _ask_field("Enter your IAM role name: " ) else: __A = "accelerate_sagemaker_execution_role" print(F'''Accelerate will create an iam role "{iam_role_name}" using the provided credentials''' ) _create_iam_role_for_sagemaker(a_ ) __A = _ask_field( "Do you want to use custom Docker image? [yes/NO]: " , _convert_yes_no_to_bool , default=a_ , error_message="Please enter yes or no." , ) __A = None if is_custom_docker_image: __A = _ask_field("Enter your Docker image: " , lambda a_ : str(a_ ).lower() ) __A = _ask_field( "Do you want to provide SageMaker input channels with data locations? [yes/NO]: " , _convert_yes_no_to_bool , default=a_ , error_message="Please enter yes or no." , ) __A = None if is_sagemaker_inputs_enabled: __A = _ask_field( "Enter the path to the SageMaker inputs TSV file with columns (channel_name, data_location): " , lambda a_ : str(a_ ).lower() , ) __A = _ask_field( "Do you want to enable SageMaker metrics? [yes/NO]: " , _convert_yes_no_to_bool , default=a_ , error_message="Please enter yes or no." , ) __A = None if is_sagemaker_metrics_enabled: __A = _ask_field( "Enter the path to the SageMaker metrics TSV file with columns (metric_name, metric_regex): " , lambda a_ : str(a_ ).lower() , ) __A = _ask_options( "What is the distributed mode?" , ["No distributed training", "Data parallelism"] , _convert_sagemaker_distributed_mode , ) __A = {} __A = _ask_field( "Do you wish to optimize your script with torch dynamo?[yes/NO]:" , _convert_yes_no_to_bool , default=a_ , error_message="Please enter yes or no." , ) if use_dynamo: __A = "dynamo_" __A = _ask_options( "Which dynamo backend would you like to use?" , [x.lower() for x in DYNAMO_BACKENDS] , _convert_dynamo_backend , default=2 , ) __A = _ask_field( "Do you want to customize the defaults sent to torch.compile? [yes/NO]: " , _convert_yes_no_to_bool , default=a_ , error_message="Please enter yes or no." , ) if use_custom_options: __A = _ask_options( "Which mode do you want to use?" , a_ , lambda a_ : TORCH_DYNAMO_MODES[int(a_ )] , default="default" , ) __A = _ask_field( "Do you want the fullgraph mode or it is ok to break model into several subgraphs? [yes/NO]: " , _convert_yes_no_to_bool , default=a_ , error_message="Please enter yes or no." , ) __A = _ask_field( "Do you want to enable dynamic shape tracing? [yes/NO]: " , _convert_yes_no_to_bool , default=a_ , error_message="Please enter yes or no." , ) __A = "Which EC2 instance type you want to use for your training?" if distributed_type != SageMakerDistributedType.NO: __A = _ask_options( a_ , a_ , lambda a_ : SAGEMAKER_PARALLEL_EC2_INSTANCES[int(a_ )] ) else: eca_instance_query += "? [ml.p3.2xlarge]:" __A = _ask_field(a_ , lambda a_ : str(a_ ).lower() , default="ml.p3.2xlarge" ) __A = 1 if distributed_type in (SageMakerDistributedType.DATA_PARALLEL, SageMakerDistributedType.MODEL_PARALLEL): __A = _ask_field( "How many machines do you want use? [1]: " , a_ , default=1 , ) __A = _ask_options( "Do you wish to use FP16 or BF16 (mixed precision)?" , ["no", "fp16", "bf16", "fp8"] , _convert_mixed_precision , ) if use_dynamo and mixed_precision == "no": print( "Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts." ) return SageMakerConfig( image_uri=a_ , compute_environment=ComputeEnvironment.AMAZON_SAGEMAKER , distributed_type=a_ , use_cpu=a_ , dynamo_config=a_ , eca_instance_type=a_ , profile=a_ , region=a_ , iam_role_name=a_ , mixed_precision=a_ , num_machines=a_ , sagemaker_inputs_file=a_ , sagemaker_metrics_file=a_ , )
55
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, BlipaProcessor, BlipImageProcessor, GPTaTokenizer, PreTrainedTokenizerFast @require_vision class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase_ ( self : List[str] ): __A = tempfile.mkdtemp() __A = BlipImageProcessor() __A = GPTaTokenizer.from_pretrained("hf-internal-testing/tiny-random-GPT2Model" ) __A = BlipaProcessor(A ,A ) processor.save_pretrained(self.tmpdirname ) def UpperCamelCase_ ( self : Dict ,**A : int ): return AutoProcessor.from_pretrained(self.tmpdirname ,**A ).tokenizer def UpperCamelCase_ ( self : Dict ,**A : Optional[int] ): return AutoProcessor.from_pretrained(self.tmpdirname ,**A ).image_processor def UpperCamelCase_ ( self : Dict ): shutil.rmtree(self.tmpdirname ) def UpperCamelCase_ ( self : Optional[int] ): __A = [np.random.randint(2_55 ,size=(3, 30, 4_00) ,dtype=np.uinta )] __A = [Image.fromarray(np.moveaxis(A ,0 ,-1 ) ) for x in image_inputs] return image_inputs def UpperCamelCase_ ( self : Any ): __A = BlipaProcessor(tokenizer=self.get_tokenizer() ,image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __A = self.get_tokenizer(bos_token="(BOS)" ,eos_token="(EOS)" ) __A = self.get_image_processor(do_normalize=A ,padding_value=1.0 ) __A = BlipaProcessor.from_pretrained( self.tmpdirname ,bos_token="(BOS)" ,eos_token="(EOS)" ,do_normalize=A ,padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() ,tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer ,A ) self.assertEqual(processor.image_processor.to_json_string() ,image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor ,A ) def UpperCamelCase_ ( self : List[Any] ): __A = self.get_image_processor() __A = self.get_tokenizer() __A = BlipaProcessor(tokenizer=A ,image_processor=A ) __A = self.prepare_image_inputs() __A = image_processor(A ,return_tensors="np" ) __A = processor(images=A ,return_tensors="np" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() ,input_processor[key].sum() ,delta=1E-2 ) def UpperCamelCase_ ( self : Tuple ): __A = self.get_image_processor() __A = self.get_tokenizer() __A = BlipaProcessor(tokenizer=A ,image_processor=A ) __A = "lower newer" __A = processor(text=A ) __A = tokenizer(A ,return_token_type_ids=A ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] ,encoded_processor[key] ) def UpperCamelCase_ ( self : int ): __A = self.get_image_processor() __A = self.get_tokenizer() __A = BlipaProcessor(tokenizer=A ,image_processor=A ) __A = "lower newer" __A = self.prepare_image_inputs() __A = processor(text=A ,images=A ) self.assertListEqual(list(inputs.keys() ) ,["pixel_values", "input_ids", "attention_mask"] ) # test if it raises when no input is passed with pytest.raises(A ): processor() def UpperCamelCase_ ( self : Optional[Any] ): __A = self.get_image_processor() __A = self.get_tokenizer() __A = BlipaProcessor(tokenizer=A ,image_processor=A ) __A = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __A = processor.batch_decode(A ) __A = tokenizer.batch_decode(A ) self.assertListEqual(A ,A ) def UpperCamelCase_ ( self : Optional[Any] ): __A = self.get_image_processor() __A = self.get_tokenizer() __A = BlipaProcessor(tokenizer=A ,image_processor=A ) __A = "lower newer" __A = self.prepare_image_inputs() __A = processor(text=A ,images=A ) # For now the processor supports only ['pixel_values', 'input_ids', 'attention_mask'] self.assertListEqual(list(inputs.keys() ) ,["pixel_values", "input_ids", "attention_mask"] )
55
1
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto.configuration_auto import CONFIG_MAPPING SCREAMING_SNAKE_CASE :int = logging.get_logger(__name__) class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = "upernet" def __init__( self : List[Any] ,A : List[Any]=None ,A : Optional[Any]=5_12 ,A : Union[str, Any]=0.02 ,A : Any=[1, 2, 3, 6] ,A : Dict=True ,A : List[Any]=0.4 ,A : Dict=3_84 ,A : List[str]=2_56 ,A : List[str]=1 ,A : Optional[Any]=False ,A : List[Any]=2_55 ,**A : str ,): super().__init__(**A ) if backbone_config is None: logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone." ) __A = CONFIG_MAPPING["resnet"](out_features=["stage1", "stage2", "stage3", "stage4"] ) elif isinstance(A ,A ): __A = backbone_config.get("model_type" ) __A = CONFIG_MAPPING[backbone_model_type] __A = config_class.from_dict(A ) __A = backbone_config __A = hidden_size __A = initializer_range __A = pool_scales __A = use_auxiliary_head __A = auxiliary_loss_weight __A = auxiliary_in_channels __A = auxiliary_channels __A = auxiliary_num_convs __A = auxiliary_concat_input __A = loss_ignore_index def UpperCamelCase_ ( self : Union[str, Any] ): __A = copy.deepcopy(self.__dict__ ) __A = self.backbone_config.to_dict() __A = self.__class__.model_type return output
55
import logging import torch from accelerate import Accelerator from arguments import EvaluationArguments from datasets import load_dataset from torch.utils.data import IterableDataset from torch.utils.data.dataloader import DataLoader from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, set_seed class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self : int ,A : Any ,A : List[str] ,A : Union[str, Any]=10_24 ,A : int=10_24 ,A : Optional[Any]=3.6 ): __A = tokenizer __A = tokenizer.bos_token_id __A = dataset __A = seq_length __A = seq_length * chars_per_token * num_of_sequences def __iter__( self : List[Any] ): __A = iter(self.dataset ) __A = True while more_examples: __A , __A = [], 0 while True: if buffer_len >= self.input_characters: break try: buffer.append(next(A )["content"] ) buffer_len += len(buffer[-1] ) except StopIteration: __A = False break __A = tokenizer(A ,truncation=A )["input_ids"] __A = [] for tokenized_input in tokenized_inputs: all_token_ids.extend(tokenized_input + [self.concat_token_id] ) for i in range(0 ,len(A ) ,self.seq_length ): __A = all_token_ids[i : i + self.seq_length] if len(A ) == self.seq_length: yield torch.tensor(A ) def UpperCAmelCase ( a_ ) -> Optional[int]: """simple docstring""" __A = {"streaming": True} __A = load_dataset(args.dataset_name , split="train" , **a_ ) __A = ConstantLengthDataset(a_ , a_ , seq_length=args.seq_length ) __A = DataLoader(a_ , batch_size=args.batch_size ) return eval_dataloader def UpperCAmelCase ( a_ ) -> Union[str, Any]: """simple docstring""" model.eval() __A = [] for step, batch in enumerate(a_ ): with torch.no_grad(): __A = model(a_ , labels=a_ ) __A = outputs.loss.repeat(args.batch_size ) losses.append(accelerator.gather(a_ ) ) if args.max_eval_steps > 0 and step >= args.max_eval_steps: break __A = torch.mean(torch.cat(a_ ) ) try: __A = torch.exp(a_ ) except OverflowError: __A = float("inf" ) return loss.item(), perplexity.item() # Setup Accelerator SCREAMING_SNAKE_CASE :Optional[int] = Accelerator() # Parse configuration SCREAMING_SNAKE_CASE :str = HfArgumentParser(EvaluationArguments) SCREAMING_SNAKE_CASE :int = parser.parse_args() set_seed(args.seed) # Logging SCREAMING_SNAKE_CASE :Dict = logging.getLogger(__name__) logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO ) # Load model and tokenizer SCREAMING_SNAKE_CASE :List[Any] = AutoModelForCausalLM.from_pretrained(args.model_ckpt) SCREAMING_SNAKE_CASE :int = AutoTokenizer.from_pretrained(args.model_ckpt) # Load dataset and dataloader SCREAMING_SNAKE_CASE :List[str] = create_dataloader(args) # Prepare everything with our `accelerator`. SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE :List[Any] = accelerator.prepare(model, eval_dataloader) # Evaluate and save the last checkpoint logger.info('Evaluating and saving model after training') SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE :List[Any] = evaluate(args) logger.info(f'''loss/eval: {eval_loss}, perplexity: {perplexity}''')
55
1
import unittest import numpy as np from transformers import AlbertConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.albert.modeling_flax_albert import ( FlaxAlbertForMaskedLM, FlaxAlbertForMultipleChoice, FlaxAlbertForPreTraining, FlaxAlbertForQuestionAnswering, FlaxAlbertForSequenceClassification, FlaxAlbertForTokenClassification, FlaxAlbertModel, ) class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self : str ,A : List[str] ,A : List[Any]=13 ,A : Optional[int]=7 ,A : Tuple=True ,A : Tuple=True ,A : Tuple=True ,A : Optional[Any]=True ,A : Optional[int]=99 ,A : Optional[Any]=32 ,A : int=5 ,A : List[Any]=4 ,A : Union[str, Any]=37 ,A : int="gelu" ,A : int=0.1 ,A : List[Any]=0.1 ,A : List[str]=5_12 ,A : int=16 ,A : str=2 ,A : int=0.02 ,A : Optional[Any]=4 ,): __A = parent __A = batch_size __A = seq_length __A = is_training __A = use_attention_mask __A = use_token_type_ids __A = use_labels __A = vocab_size __A = hidden_size __A = num_hidden_layers __A = num_attention_heads __A = intermediate_size __A = hidden_act __A = hidden_dropout_prob __A = attention_probs_dropout_prob __A = max_position_embeddings __A = type_vocab_size __A = type_sequence_label_size __A = initializer_range __A = num_choices def UpperCamelCase_ ( self : Dict ): __A = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) __A = None if self.use_attention_mask: __A = random_attention_mask([self.batch_size, self.seq_length] ) __A = None if self.use_token_type_ids: __A = ids_tensor([self.batch_size, self.seq_length] ,self.type_vocab_size ) __A = AlbertConfig( vocab_size=self.vocab_size ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,hidden_act=self.hidden_act ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,type_vocab_size=self.type_vocab_size ,is_decoder=A ,initializer_range=self.initializer_range ,) return config, input_ids, token_type_ids, attention_mask def UpperCamelCase_ ( self : Dict ): __A = self.prepare_config_and_inputs() __A , __A , __A , __A = config_and_inputs __A = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask} return config, inputs_dict @require_flax class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = ( ( FlaxAlbertModel, FlaxAlbertForPreTraining, FlaxAlbertForMaskedLM, FlaxAlbertForMultipleChoice, FlaxAlbertForQuestionAnswering, FlaxAlbertForSequenceClassification, FlaxAlbertForTokenClassification, FlaxAlbertForQuestionAnswering, ) if is_flax_available() else () ) def UpperCamelCase_ ( self : List[Any] ): __A = FlaxAlbertModelTester(self ) @slow def UpperCamelCase_ ( self : List[Any] ): for model_class_name in self.all_model_classes: __A = model_class_name.from_pretrained("albert-base-v2" ) __A = model(np.ones((1, 1) ) ) self.assertIsNotNone(A ) @require_flax class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @slow def UpperCamelCase_ ( self : Optional[Any] ): __A = FlaxAlbertModel.from_pretrained("albert-base-v2" ) __A = np.array([[0, 3_45, 2_32, 3_28, 7_40, 1_40, 16_95, 69, 60_78, 15_88, 2]] ) __A = np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) __A = model(A ,attention_mask=A )[0] __A = (1, 11, 7_68) self.assertEqual(output.shape ,A ) __A = np.array( [[[-0.65_13, 1.50_35, -0.27_66], [-0.65_15, 1.50_46, -0.27_80], [-0.65_12, 1.50_49, -0.27_84]]] ) self.assertTrue(jnp.allclose(output[:, 1:4, 1:4] ,A ,atol=1E-4 ) )
55
import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = LayoutLMTokenizer snake_case_ = LayoutLMTokenizerFast snake_case_ = True snake_case_ = True def UpperCamelCase_ ( self : Any ): super().setUp() __A = [ "[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest", ] __A = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file ,"w" ,encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) def UpperCamelCase_ ( self : Tuple ,**A : int ): return LayoutLMTokenizer.from_pretrained(self.tmpdirname ,**A ) def UpperCamelCase_ ( self : Optional[Any] ,A : Any ): __A = "UNwant\u00E9d,running" __A = "unwanted, running" return input_text, output_text def UpperCamelCase_ ( self : str ): __A = self.tokenizer_class(self.vocab_file ) __A = tokenizer.tokenize("UNwant\u00E9d,running" ) self.assertListEqual(A ,["un", "##want", "##ed", ",", "runn", "##ing"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(A ) ,[7, 4, 5, 10, 8, 9] ) def UpperCamelCase_ ( self : int ): pass
55
1
import argparse import os import transformers from .convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS from .utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE :Optional[int] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE :Tuple = {name: getattr(transformers, name + 'Fast') for name in SLOW_TO_FAST_CONVERTERS} def UpperCAmelCase ( a_ , a_ , a_ , a_ ) -> List[str]: """simple docstring""" if tokenizer_name is not None and tokenizer_name not in TOKENIZER_CLASSES: raise ValueError(F'''Unrecognized tokenizer name, should be one of {list(TOKENIZER_CLASSES.keys() )}.''' ) if tokenizer_name is None: __A = TOKENIZER_CLASSES else: __A = {tokenizer_name: getattr(a_ , tokenizer_name + "Fast" )} logger.info(F'''Loading tokenizer classes: {tokenizer_names}''' ) for tokenizer_name in tokenizer_names: __A = TOKENIZER_CLASSES[tokenizer_name] __A = True if checkpoint_name is None: __A = list(tokenizer_class.max_model_input_sizes.keys() ) else: __A = [checkpoint_name] logger.info(F'''For tokenizer {tokenizer_class.__class__.__name__} loading checkpoints: {checkpoint_names}''' ) for checkpoint in checkpoint_names: logger.info(F'''Loading {tokenizer_class.__class__.__name__} {checkpoint}''' ) # Load tokenizer __A = tokenizer_class.from_pretrained(a_ , force_download=a_ ) # Save fast tokenizer logger.info(F'''Save fast tokenizer to {dump_path} with prefix {checkpoint} add_prefix {add_prefix}''' ) # For organization names we create sub-directories if "/" in checkpoint: __A , __A = checkpoint.split("/" ) __A = os.path.join(a_ , a_ ) elif add_prefix: __A = checkpoint __A = dump_path else: __A = None __A = dump_path logger.info(F'''=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}''' ) if checkpoint in list(tokenizer.pretrained_vocab_files_map.values() )[0]: __A = list(tokenizer.pretrained_vocab_files_map.values() )[0][checkpoint] __A = file_path.split(a_ )[-1][0] if next_char == "/": __A = os.path.join(a_ , a_ ) __A = None logger.info(F'''=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}''' ) __A = tokenizer.save_pretrained( a_ , legacy_format=a_ , filename_prefix=a_ ) logger.info(F'''=> File names {file_names}''' ) for file_name in file_names: if not file_name.endswith("tokenizer.json" ): os.remove(a_ ) logger.info(F'''=> removing {file_name}''' ) if __name__ == "__main__": SCREAMING_SNAKE_CASE :List[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--dump_path', default=None, type=str, required=True, help='Path to output generated fast tokenizer files.' ) parser.add_argument( '--tokenizer_name', default=None, type=str, help=( f'''Optional tokenizer type selected in the list of {list(TOKENIZER_CLASSES.keys())}. If not given, will ''' 'download and convert all the checkpoints from AWS.' ), ) parser.add_argument( '--checkpoint_name', default=None, type=str, help='Optional checkpoint name. If not given, will download and convert the canonical checkpoints from AWS.', ) parser.add_argument( '--force_download', action='store_true', help='Re-download checkpoints.', ) SCREAMING_SNAKE_CASE :Dict = parser.parse_args() convert_slow_checkpoint_to_fast(args.tokenizer_name, args.checkpoint_name, args.dump_path, args.force_download)
55
SCREAMING_SNAKE_CASE :int = {str(digit): digit**5 for digit in range(10)} def UpperCAmelCase ( a_ ) -> int: """simple docstring""" return sum(DIGITS_FIFTH_POWER[digit] for digit in str(a_ ) ) def UpperCAmelCase ( ) -> int: """simple docstring""" return sum( number for number in range(1_0_0_0 , 1_0_0_0_0_0_0 ) if number == digits_fifth_powers_sum(a_ ) ) if __name__ == "__main__": print(solution())
55
1
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 :Dict = logging.get_logger(__name__) class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = ["pixel_values"] def __init__( self : Tuple ,A : bool = True ,A : Dict[str, int] = None ,A : PILImageResampling = PILImageResampling.BILINEAR ,A : bool = True ,A : Union[int, float] = 1 / 2_55 ,A : bool = True ,A : Dict[str, int] = None ,A : bool = True ,**A : List[Any] ,): super().__init__(**A ) __A = size if size is not None else {"shortest_edge": 2_24} __A = get_size_dict(A ,default_to_square=A ) __A = crop_size if crop_size is not None else {"height": 2_56, "width": 2_56} __A = get_size_dict(A ,param_name="crop_size" ) __A = do_resize __A = size __A = resample __A = do_rescale __A = rescale_factor __A = do_center_crop __A = crop_size __A = do_flip_channel_order def UpperCamelCase_ ( self : List[Any] ,A : np.ndarray ,A : Dict[str, int] ,A : PILImageResampling = PIL.Image.BILINEAR ,A : Optional[Union[str, ChannelDimension]] = None ,**A : Optional[Any] ,): __A = get_size_dict(A ,default_to_square=A ) if "shortest_edge" not in size: raise ValueError(f'''The `size` dictionary must contain the key `shortest_edge`. Got {size.keys()}''' ) __A = get_resize_output_image_size(A ,size=size["shortest_edge"] ,default_to_square=A ) return resize(A ,size=A ,resample=A ,data_format=A ,**A ) def UpperCamelCase_ ( self : Optional[int] ,A : np.ndarray ,A : Dict[str, int] ,A : Optional[Union[str, ChannelDimension]] = None ,**A : Optional[int] ,): __A = get_size_dict(A ) if "height" not in size or "width" not in size: raise ValueError(f'''The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}''' ) return center_crop(A ,size=(size["height"], size["width"]) ,data_format=A ,**A ) def UpperCamelCase_ ( self : str ,A : np.ndarray ,A : Union[int, float] ,A : Optional[Union[str, ChannelDimension]] = None ,**A : List[Any] ,): return rescale(A ,scale=A ,data_format=A ,**A ) def UpperCamelCase_ ( self : Tuple ,A : np.ndarray ,A : Optional[Union[str, ChannelDimension]] = None ): return flip_channel_order(A ,data_format=A ) def UpperCamelCase_ ( self : Union[str, Any] ,A : ImageInput ,A : bool = None ,A : Dict[str, int] = None ,A : PILImageResampling = None ,A : bool = None ,A : float = None ,A : bool = None ,A : Dict[str, int] = None ,A : bool = None ,A : Optional[Union[str, TensorType]] = None ,A : ChannelDimension = ChannelDimension.FIRST ,**A : str ,): __A = do_resize if do_resize is not None else self.do_resize __A = resample if resample is not None else self.resample __A = do_rescale if do_rescale is not None else self.do_rescale __A = rescale_factor if rescale_factor is not None else self.rescale_factor __A = do_center_crop if do_center_crop is not None else self.do_center_crop __A = ( do_flip_channel_order if do_flip_channel_order is not None else self.do_flip_channel_order ) __A = size if size is not None else self.size __A = get_size_dict(A ,default_to_square=A ) __A = crop_size if crop_size is not None else self.crop_size __A = get_size_dict(A ,param_name="crop_size" ) __A = make_list_of_images(A ) if not valid_images(A ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None: raise ValueError("Size must be specified if do_resize is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_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. __A = [to_numpy_array(A ) for image in images] if do_resize: __A = [self.resize(image=A ,size=A ,resample=A ) for image in images] if do_center_crop: __A = [self.center_crop(image=A ,size=A ) for image in images] if do_rescale: __A = [self.rescale(image=A ,scale=A ) for image in images] # the pretrained checkpoints assume images are BGR, not RGB if do_flip_channel_order: __A = [self.flip_channel_order(image=A ) for image in images] __A = [to_channel_dimension_format(A ,A ) for image in images] __A = {"pixel_values": images} return BatchFeature(data=A ,tensor_type=A ) def UpperCamelCase_ ( self : Union[str, Any] ,A : Optional[int] ,A : List[Tuple] = None ): __A = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(A ) != len(A ): raise ValueError( "Make sure that you pass in as many target sizes as the batch dimension of the logits" ) if is_torch_tensor(A ): __A = target_sizes.numpy() __A = [] for idx in range(len(A ) ): __A = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) ,size=target_sizes[idx] ,mode="bilinear" ,align_corners=A ) __A = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(A ) else: __A = logits.argmax(dim=1 ) __A = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
55
import inspect import unittest from transformers import MobileNetVaConfig 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 MobileNetVaForImageClassification, MobileNetVaModel from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileNetVaImageProcessor class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def UpperCamelCase_ ( self : Any ): __A = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(A ,"tf_padding" ) ) self.parent.assertTrue(hasattr(A ,"depth_multiplier" ) ) class UpperCAmelCase : '''simple docstring''' def __init__( self : Optional[Any] ,A : int ,A : List[Any]=13 ,A : int=3 ,A : Optional[Any]=32 ,A : Union[str, Any]=0.25 ,A : Tuple=8 ,A : Optional[int]=True ,A : Union[str, Any]=10_24 ,A : Any=32 ,A : Optional[int]="relu6" ,A : int=0.1 ,A : Optional[Any]=0.02 ,A : Optional[Any]=True ,A : List[str]=True ,A : str=10 ,A : str=None ,): __A = parent __A = batch_size __A = num_channels __A = image_size __A = depth_multiplier __A = min_depth __A = tf_padding __A = int(last_hidden_size * depth_multiplier ) __A = output_stride __A = hidden_act __A = classifier_dropout_prob __A = use_labels __A = is_training __A = num_labels __A = initializer_range __A = scope def UpperCamelCase_ ( self : Optional[int] ): __A = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __A = None __A = None if self.use_labels: __A = ids_tensor([self.batch_size] ,self.num_labels ) __A = ids_tensor([self.batch_size, self.image_size, self.image_size] ,self.num_labels ) __A = self.get_config() return config, pixel_values, labels, pixel_labels def UpperCamelCase_ ( self : Any ): return MobileNetVaConfig( num_channels=self.num_channels ,image_size=self.image_size ,depth_multiplier=self.depth_multiplier ,min_depth=self.min_depth ,tf_padding=self.tf_padding ,hidden_act=self.hidden_act ,classifier_dropout_prob=self.classifier_dropout_prob ,initializer_range=self.initializer_range ,) def UpperCamelCase_ ( self : Optional[int] ,A : str ,A : Tuple ,A : Optional[int] ,A : List[str] ): __A = MobileNetVaModel(config=A ) model.to(A ) model.eval() __A = model(A ) self.parent.assertEqual( result.last_hidden_state.shape ,( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) ,) def UpperCamelCase_ ( self : List[Any] ,A : Union[str, Any] ,A : List[Any] ,A : int ,A : Union[str, Any] ): __A = self.num_labels __A = MobileNetVaForImageClassification(A ) model.to(A ) model.eval() __A = model(A ,labels=A ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def UpperCamelCase_ ( self : Tuple ): __A = self.prepare_config_and_inputs() __A , __A , __A , __A = config_and_inputs __A = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = (MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else () snake_case_ = ( {"feature-extraction": MobileNetVaModel, "image-classification": MobileNetVaForImageClassification} if is_torch_available() else {} ) snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = False def UpperCamelCase_ ( self : Any ): __A = MobileNetVaModelTester(self ) __A = MobileNetVaConfigTester(self ,config_class=A ,has_text_modality=A ) def UpperCamelCase_ ( self : str ): self.config_tester.run_common_tests() @unittest.skip(reason="MobileNetV1 does not use inputs_embeds" ) def UpperCamelCase_ ( self : Union[str, Any] ): pass @unittest.skip(reason="MobileNetV1 does not support input and output embeddings" ) def UpperCamelCase_ ( self : Tuple ): pass @unittest.skip(reason="MobileNetV1 does not output attentions" ) def UpperCamelCase_ ( self : Any ): pass def UpperCamelCase_ ( self : Optional[int] ): __A , __A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __A = model_class(A ) __A = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __A = [*signature.parameters.keys()] __A = ["pixel_values"] self.assertListEqual(arg_names[:1] ,A ) def UpperCamelCase_ ( self : List[Any] ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A ) def UpperCamelCase_ ( self : Optional[int] ): def check_hidden_states_output(A : List[Any] ,A : List[Any] ,A : Optional[int] ): __A = model_class(A ) model.to(A ) model.eval() with torch.no_grad(): __A = model(**self._prepare_for_class(A ,A ) ) __A = outputs.hidden_states __A = 26 self.assertEqual(len(A ) ,A ) __A , __A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __A = True check_hidden_states_output(A ,A ,A ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __A = True check_hidden_states_output(A ,A ,A ) def UpperCamelCase_ ( self : Tuple ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*A ) @slow def UpperCamelCase_ ( self : Union[str, Any] ): for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __A = MobileNetVaModel.from_pretrained(A ) self.assertIsNotNone(A ) def UpperCAmelCase ( ) -> str: """simple docstring""" __A = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def UpperCamelCase_ ( self : List[str] ): return ( MobileNetVaImageProcessor.from_pretrained("google/mobilenet_v1_1.0_224" ) if is_vision_available() else None ) @slow def UpperCamelCase_ ( self : Optional[Any] ): __A = MobileNetVaForImageClassification.from_pretrained("google/mobilenet_v1_1.0_224" ).to(A ) __A = self.default_image_processor __A = prepare_img() __A = image_processor(images=A ,return_tensors="pt" ).to(A ) # forward pass with torch.no_grad(): __A = model(**A ) # verify the logits __A = torch.Size((1, 10_01) ) self.assertEqual(outputs.logits.shape ,A ) __A = torch.tensor([-4.17_39, -1.12_33, 3.12_05] ).to(A ) self.assertTrue(torch.allclose(outputs.logits[0, :3] ,A ,atol=1E-4 ) )
55
1
import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin SCREAMING_SNAKE_CASE :int = get_tests_dir('fixtures/test_sentencepiece_no_bos.model') @require_sentencepiece @require_tokenizers class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = PegasusTokenizer snake_case_ = PegasusTokenizerFast snake_case_ = True snake_case_ = True def UpperCamelCase_ ( self : Dict ): super().setUp() # We have a SentencePiece fixture for testing __A = PegasusTokenizer(A ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def UpperCamelCase_ ( self : Union[str, Any] ): return PegasusTokenizer.from_pretrained("google/pegasus-large" ) def UpperCamelCase_ ( self : int ,**A : Dict ): return PegasusTokenizer.from_pretrained(self.tmpdirname ,**A ) def UpperCamelCase_ ( self : List[str] ,A : str ): return ("This is a test", "This is a test") def UpperCamelCase_ ( self : Any ): __A = "</s>" __A = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(A ) ,A ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(A ) ,A ) def UpperCamelCase_ ( self : List[str] ): __A = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] ,"<pad>" ) self.assertEqual(vocab_keys[1] ,"</s>" ) self.assertEqual(vocab_keys[-1] ,"v" ) self.assertEqual(len(A ) ,11_03 ) def UpperCamelCase_ ( self : Union[str, Any] ): self.assertEqual(self.get_tokenizer().vocab_size ,11_03 ) def UpperCamelCase_ ( self : int ): __A = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) __A = self.tokenizer_class.from_pretrained(self.tmpdirname ) __A = ( "Let's see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important" " </s> <pad> <pad> <pad>" ) __A = rust_tokenizer([raw_input_str] ,return_tensors=A ,add_special_tokens=A ).input_ids[0] __A = py_tokenizer([raw_input_str] ,return_tensors=A ,add_special_tokens=A ).input_ids[0] self.assertListEqual(A ,A ) def UpperCamelCase_ ( self : Optional[int] ): __A = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word __A = "<mask_1> To ensure a <mask_2> flow of bank resolutions." __A = [2, 4_13, 6_15, 1_14, 3, 19_71, 1_13, 16_79, 1_07_10, 1_07, 1] __A = tokenizer([raw_input_str] ,return_tensors=A ).input_ids[0] self.assertListEqual(A ,A ) def UpperCamelCase_ ( self : Tuple ): __A = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 9_61_03 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 1_03 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 1_05 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 10_24 __A = "To ensure a smooth flow of bank resolutions." __A = [4_13, 6_15, 1_14, 22_91, 19_71, 1_13, 16_79, 1_07_10, 1_07, 1] __A = tokenizer([raw_input_str] ,return_tensors=A ).input_ids[0] self.assertListEqual(A ,A ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def UpperCamelCase_ ( self : Union[str, Any] ): __A = ["This is going to be way too long." * 1_50, "short example"] __A = ["not super long but more than 5 tokens", "tiny"] __A = self._large_tokenizer(A ,padding=A ,truncation=A ,return_tensors="pt" ) __A = self._large_tokenizer( text_target=A ,max_length=5 ,padding=A ,truncation=A ,return_tensors="pt" ) assert batch.input_ids.shape == (2, 10_24) assert batch.attention_mask.shape == (2, 10_24) assert targets["input_ids"].shape == (2, 5) assert len(A ) == 2 # input_ids, attention_mask. @slow def UpperCamelCase_ ( self : List[str] ): # fmt: off __A = {"input_ids": [[3_89_79, 1_43, 1_84_85, 6_06, 1_30, 2_66_69, 8_76_86, 1_21, 5_41_89, 11_29, 1_11, 2_66_69, 8_76_86, 1_21, 91_14, 1_47_87, 1_21, 1_32_49, 1_58, 5_92, 9_56, 1_21, 1_46_21, 3_15_76, 1_43, 6_26_13, 1_08, 96_88, 9_30, 4_34_30, 1_15_62, 6_26_13, 3_04, 1_08, 1_14_43, 8_97, 1_08, 93_14, 1_74_15, 6_33_99, 1_08, 1_14_43, 76_14, 1_83_16, 1_18, 42_84, 71_48, 1_24_30, 1_43, 14_00, 2_57_03, 1_58, 1_11, 42_84, 71_48, 1_17_72, 1_43, 2_12_97, 10_64, 1_58, 1_22, 2_04, 35_06, 17_54, 11_33, 1_47_87, 15_81, 1_15, 3_32_24, 44_82, 1_11, 13_55, 1_10, 2_91_73, 3_17, 5_08_33, 1_08, 2_01_47, 9_46_65, 1_11, 7_71_98, 1_07, 1], [1_10, 6_26_13, 1_17, 6_38, 1_12, 11_33, 1_21, 2_00_98, 13_55, 7_90_50, 1_38_72, 1_35, 15_96, 5_35_41, 13_52, 1_41, 1_30_39, 55_42, 1_24, 3_02, 5_18, 1_11, 2_68, 29_56, 1_15, 1_49, 44_27, 1_07, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1_39, 12_35, 27_99, 1_82_89, 1_77_80, 2_04, 1_09, 94_74, 12_96, 1_07, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=A ,model_name="google/bigbird-pegasus-large-arxiv" ,revision="ba85d0851d708441f91440d509690f1ab6353415" ,) @require_sentencepiece @require_tokenizers class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = PegasusTokenizer snake_case_ = PegasusTokenizerFast snake_case_ = True snake_case_ = True def UpperCamelCase_ ( self : Tuple ): super().setUp() # We have a SentencePiece fixture for testing __A = PegasusTokenizer(A ,offset=0 ,mask_token_sent=A ,mask_token="[MASK]" ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def UpperCamelCase_ ( self : Union[str, Any] ): return PegasusTokenizer.from_pretrained("google/bigbird-pegasus-large-arxiv" ) def UpperCamelCase_ ( self : str ,**A : Union[str, Any] ): return PegasusTokenizer.from_pretrained(self.tmpdirname ,**A ) def UpperCamelCase_ ( self : Optional[int] ,A : Dict ): return ("This is a test", "This is a test") def UpperCamelCase_ ( self : int ): __A = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) __A = self.tokenizer_class.from_pretrained(self.tmpdirname ) __A = ( "Let's see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>" " <pad> <pad> <pad>" ) __A = rust_tokenizer([raw_input_str] ,return_tensors=A ,add_special_tokens=A ).input_ids[0] __A = py_tokenizer([raw_input_str] ,return_tensors=A ,add_special_tokens=A ).input_ids[0] self.assertListEqual(A ,A ) @require_torch def UpperCamelCase_ ( self : Optional[Any] ): __A = ["This is going to be way too long." * 10_00, "short example"] __A = ["not super long but more than 5 tokens", "tiny"] __A = self._large_tokenizer(A ,padding=A ,truncation=A ,return_tensors="pt" ) __A = self._large_tokenizer( text_target=A ,max_length=5 ,padding=A ,truncation=A ,return_tensors="pt" ) assert batch.input_ids.shape == (2, 40_96) assert batch.attention_mask.shape == (2, 40_96) assert targets["input_ids"].shape == (2, 5) assert len(A ) == 2 # input_ids, attention_mask. def UpperCamelCase_ ( self : Dict ): __A = ( "This is an example string that is used to test the original TF implementation against the HF" " implementation" ) __A = self._large_tokenizer(A ).input_ids self.assertListEqual( A ,[1_82, 1_17, 1_42, 5_87, 42_11, 1_20, 1_17, 2_63, 1_12, 8_04, 1_09, 8_56, 2_50_16, 31_37, 4_64, 1_09, 2_69_55, 31_37, 1] ,)
55
import copy import unittest from transformers.models.auto import get_values from transformers.testing_utils import require_torch, 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, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_MULTIPLE_CHOICE_MAPPING, MODEL_FOR_QUESTION_ANSWERING_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaModel, ) from transformers.models.layoutlmva.modeling_layoutlmva import LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class UpperCAmelCase : '''simple docstring''' def __init__( self : str ,A : int ,A : int=2 ,A : Optional[Any]=3 ,A : Dict=4 ,A : Optional[int]=2 ,A : Union[str, Any]=7 ,A : List[str]=True ,A : Union[str, Any]=True ,A : Optional[int]=True ,A : Optional[int]=True ,A : Tuple=99 ,A : Optional[int]=36 ,A : Dict=3 ,A : str=4 ,A : Optional[Any]=37 ,A : Dict="gelu" ,A : Dict=0.1 ,A : Union[str, Any]=0.1 ,A : Union[str, Any]=5_12 ,A : Any=16 ,A : Union[str, Any]=2 ,A : List[Any]=0.02 ,A : List[Any]=6 ,A : Optional[int]=6 ,A : List[Any]=3 ,A : Union[str, Any]=4 ,A : Tuple=None ,A : List[str]=10_00 ,): __A = parent __A = batch_size __A = num_channels __A = image_size __A = patch_size __A = text_seq_length __A = is_training __A = use_input_mask __A = use_token_type_ids __A = use_labels __A = vocab_size __A = hidden_size __A = num_hidden_layers __A = num_attention_heads __A = intermediate_size __A = hidden_act __A = hidden_dropout_prob __A = attention_probs_dropout_prob __A = max_position_embeddings __A = type_vocab_size __A = type_sequence_label_size __A = initializer_range __A = coordinate_size __A = shape_size __A = num_labels __A = num_choices __A = scope __A = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) __A = text_seq_length __A = (image_size // patch_size) ** 2 + 1 __A = self.text_seq_length + self.image_seq_length def UpperCamelCase_ ( self : int ): __A = ids_tensor([self.batch_size, self.text_seq_length] ,self.vocab_size ) __A = ids_tensor([self.batch_size, self.text_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]: __A = bbox[i, j, 3] __A = bbox[i, j, 1] __A = t if bbox[i, j, 2] < bbox[i, j, 0]: __A = bbox[i, j, 2] __A = bbox[i, j, 0] __A = t __A = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __A = None if self.use_input_mask: __A = random_attention_mask([self.batch_size, self.text_seq_length] ) __A = None if self.use_token_type_ids: __A = ids_tensor([self.batch_size, self.text_seq_length] ,self.type_vocab_size ) __A = None __A = None if self.use_labels: __A = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) __A = ids_tensor([self.batch_size, self.text_seq_length] ,self.num_labels ) __A = LayoutLMvaConfig( 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 ,coordinate_size=self.coordinate_size ,shape_size=self.shape_size ,input_size=self.image_size ,patch_size=self.patch_size ,) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def UpperCamelCase_ ( self : Optional[int] ,A : List[str] ,A : Any ,A : Dict ,A : List[Any] ,A : Optional[int] ,A : Any ,A : Dict ,A : List[Any] ): __A = LayoutLMvaModel(config=A ) model.to(A ) model.eval() # text + image __A = model(A ,pixel_values=A ) __A = model( A ,bbox=A ,pixel_values=A ,attention_mask=A ,token_type_ids=A ) __A = model(A ,bbox=A ,pixel_values=A ,token_type_ids=A ) __A = model(A ,bbox=A ,pixel_values=A ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) # text only __A = model(A ) self.parent.assertEqual( result.last_hidden_state.shape ,(self.batch_size, self.text_seq_length, self.hidden_size) ) # image only __A = model(pixel_values=A ) self.parent.assertEqual( result.last_hidden_state.shape ,(self.batch_size, self.image_seq_length, self.hidden_size) ) def UpperCamelCase_ ( self : Optional[int] ,A : Dict ,A : List[str] ,A : Any ,A : List[Any] ,A : Any ,A : Any ,A : Dict ,A : Optional[Any] ): __A = self.num_labels __A = LayoutLMvaForSequenceClassification(A ) model.to(A ) model.eval() __A = model( A ,bbox=A ,pixel_values=A ,attention_mask=A ,token_type_ids=A ,labels=A ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def UpperCamelCase_ ( self : str ,A : Optional[Any] ,A : Dict ,A : str ,A : Tuple ,A : Union[str, Any] ,A : List[Any] ,A : Any ,A : Union[str, Any] ): __A = self.num_labels __A = LayoutLMvaForTokenClassification(config=A ) model.to(A ) model.eval() __A = model( A ,bbox=A ,pixel_values=A ,attention_mask=A ,token_type_ids=A ,labels=A ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.text_seq_length, self.num_labels) ) def UpperCamelCase_ ( self : Optional[int] ,A : Optional[Any] ,A : int ,A : str ,A : List[str] ,A : int ,A : List[str] ,A : List[str] ,A : Dict ): __A = LayoutLMvaForQuestionAnswering(config=A ) model.to(A ) model.eval() __A = model( A ,bbox=A ,pixel_values=A ,attention_mask=A ,token_type_ids=A ,start_positions=A ,end_positions=A ,) self.parent.assertEqual(result.start_logits.shape ,(self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape ,(self.batch_size, self.seq_length) ) def UpperCamelCase_ ( self : str ): __A = self.prepare_config_and_inputs() ( ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ) = config_and_inputs __A = { "input_ids": input_ids, "bbox": bbox, "pixel_values": pixel_values, "token_type_ids": token_type_ids, "attention_mask": input_mask, } return config, inputs_dict @require_torch class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = ( ( LayoutLMvaModel, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaForQuestionAnswering, ) if is_torch_available() else () ) snake_case_ = ( {"document-question-answering": LayoutLMvaForQuestionAnswering, "feature-extraction": LayoutLMvaModel} if is_torch_available() else {} ) def UpperCamelCase_ ( self : str ,A : Any ,A : Any ,A : Tuple ,A : List[Any] ,A : Optional[Any] ): # `DocumentQuestionAnsweringPipeline` is expected to work with this model, but it combines the text and visual # embedding along the sequence dimension (dim 1), which causes an error during post-processing as `p_mask` has # the sequence dimension of the text embedding only. # (see the line `embedding_output = torch.cat([embedding_output, visual_embeddings], dim=1)`) return True def UpperCamelCase_ ( self : Union[str, Any] ): __A = LayoutLMvaModelTester(self ) __A = ConfigTester(self ,config_class=A ,hidden_size=37 ) def UpperCamelCase_ ( self : List[Any] ,A : int ,A : List[str] ,A : Dict=False ): __A = copy.deepcopy(A ) if model_class in get_values(A ): __A = { k: v.unsqueeze(1 ).expand(-1 ,self.model_tester.num_choices ,-1 ).contiguous() if isinstance(A ,torch.Tensor ) and v.ndim > 1 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(A ): __A = torch.ones(self.model_tester.batch_size ,dtype=torch.long ,device=A ) elif model_class in get_values(A ): __A = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=A ) __A = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=A ) elif model_class in [ *get_values(A ), ]: __A = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=A ) elif model_class in [ *get_values(A ), ]: __A = torch.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) ,dtype=torch.long ,device=A ,) return inputs_dict def UpperCamelCase_ ( self : List[Any] ): self.config_tester.run_common_tests() def UpperCamelCase_ ( self : Union[str, Any] ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A ) def UpperCamelCase_ ( self : str ): __A = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __A = type self.model_tester.create_and_check_model(*A ) def UpperCamelCase_ ( self : Optional[Any] ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*A ) def UpperCamelCase_ ( self : Optional[Any] ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*A ) def UpperCamelCase_ ( self : str ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*A ) @slow def UpperCamelCase_ ( self : Optional[int] ): for model_name in LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __A = LayoutLMvaModel.from_pretrained(A ) self.assertIsNotNone(A ) def UpperCAmelCase ( ) -> Dict: """simple docstring""" __A = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def UpperCamelCase_ ( self : Any ): return LayoutLMvaImageProcessor(apply_ocr=A ) if is_vision_available() else None @slow def UpperCamelCase_ ( self : Dict ): __A = LayoutLMvaModel.from_pretrained("microsoft/layoutlmv3-base" ).to(A ) __A = self.default_image_processor __A = prepare_img() __A = image_processor(images=A ,return_tensors="pt" ).pixel_values.to(A ) __A = torch.tensor([[1, 2]] ) __A = torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]] ).unsqueeze(0 ) # forward pass __A = model( input_ids=input_ids.to(A ) ,bbox=bbox.to(A ) ,pixel_values=pixel_values.to(A ) ,) # verify the logits __A = torch.Size((1, 1_99, 7_68) ) self.assertEqual(outputs.last_hidden_state.shape ,A ) __A = torch.tensor( [[-0.05_29, 0.36_18, 0.16_32], [-0.15_87, -0.16_67, -0.04_00], [-0.15_57, -0.16_71, -0.05_05]] ).to(A ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] ,A ,atol=1E-4 ) )
55
1
import sacrebleu as scb from packaging import version from sacrebleu import TER import datasets SCREAMING_SNAKE_CASE :Optional[Any] = '\\n@inproceedings{snover-etal-2006-study,\n title = "A Study of Translation Edit Rate with Targeted Human Annotation",\n author = "Snover, Matthew and\n Dorr, Bonnie and\n Schwartz, Rich and\n Micciulla, Linnea and\n Makhoul, John",\n booktitle = "Proceedings of the 7th Conference of the Association for Machine Translation in the Americas: Technical Papers",\n month = aug # " 8-12",\n year = "2006",\n address = "Cambridge, Massachusetts, USA",\n publisher = "Association for Machine Translation in the Americas",\n url = "https://aclanthology.org/2006.amta-papers.25",\n pages = "223--231",\n}\n@inproceedings{post-2018-call,\n title = "A Call for Clarity in Reporting {BLEU} Scores",\n author = "Post, Matt",\n booktitle = "Proceedings of the Third Conference on Machine Translation: Research Papers",\n month = oct,\n year = "2018",\n address = "Belgium, Brussels",\n publisher = "Association for Computational Linguistics",\n url = "https://www.aclweb.org/anthology/W18-6319",\n pages = "186--191",\n}\n' SCREAMING_SNAKE_CASE :int = '\\nTER (Translation Edit Rate, also called Translation Error Rate) is a metric to quantify the edit operations that a\nhypothesis requires to match a reference translation. We use the implementation that is already present in sacrebleu\n(https://github.com/mjpost/sacreBLEU#ter), which in turn is inspired by the TERCOM implementation, which can be found\nhere: https://github.com/jhclark/tercom.\n\nThe implementation here is slightly different from sacrebleu in terms of the required input format. The length of\nthe references and hypotheses lists need to be the same, so you may need to transpose your references compared to\nsacrebleu\'s required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534\n\nSee the README.md file at https://github.com/mjpost/sacreBLEU#ter for more information.\n' SCREAMING_SNAKE_CASE :str = '\nProduces TER scores alongside the number of edits and reference length.\n\nArgs:\n predictions (list of str): The system stream (a sequence of segments).\n references (list of list of str): A list of one or more reference streams (each a sequence of segments).\n normalized (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.\n ignore_punct (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.\n support_zh_ja_chars (boolean): If `True`, tokenization/normalization supports processing of Chinese characters,\n as well as Japanese Kanji, Hiragana, Katakana, and Phonetic Extensions of Katakana.\n Only applies if `normalized = True`. Defaults to `False`.\n case_sensitive (boolean): If `False`, makes all predictions and references lowercase to ignore differences in case. Defaults to `False`.\n\nReturns:\n \'score\' (float): TER score (num_edits / sum_ref_lengths * 100)\n \'num_edits\' (int): The cumulative number of edits\n \'ref_length\' (float): The cumulative average reference length\n\nExamples:\n Example 1:\n >>> predictions = ["does this sentence match??",\n ... "what about this sentence?",\n ... "What did the TER metric user say to the developer?"]\n >>> references = [["does this sentence match", "does this sentence match!?!"],\n ... ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"],\n ... ["Your jokes are...", "...TERrible"]]\n >>> ter = datasets.load_metric("ter")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... case_sensitive=True)\n >>> print(results)\n {\'score\': 150.0, \'num_edits\': 15, \'ref_length\': 10.0}\n\n Example 2:\n >>> predictions = ["does this sentence match??",\n ... "what about this sentence?"]\n >>> references = [["does this sentence match", "does this sentence match!?!"],\n ... ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"]]\n >>> ter = datasets.load_metric("ter")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... case_sensitive=True)\n >>> print(results)\n {\'score\': 62.5, \'num_edits\': 5, \'ref_length\': 8.0}\n\n Example 3:\n >>> predictions = ["does this sentence match??",\n ... "what about this sentence?"]\n >>> references = [["does this sentence match", "does this sentence match!?!"],\n ... ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"]]\n >>> ter = datasets.load_metric("ter")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... normalized=True,\n ... case_sensitive=True)\n >>> print(results)\n {\'score\': 57.14285714285714, \'num_edits\': 6, \'ref_length\': 10.5}\n\n Example 4:\n >>> predictions = ["does this sentence match??",\n ... "what about this sentence?"]\n >>> references = [["does this sentence match", "does this sentence match!?!"],\n ... ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"]]\n >>> ter = datasets.load_metric("ter")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... ignore_punct=True,\n ... case_sensitive=False)\n >>> print(results)\n {\'score\': 0.0, \'num_edits\': 0, \'ref_length\': 8.0}\n\n Example 5:\n >>> predictions = ["does this sentence match??",\n ... "what about this sentence?",\n ... "What did the TER metric user say to the developer?"]\n >>> references = [["does this sentence match", "does this sentence match!?!"],\n ... ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"],\n ... ["Your jokes are...", "...TERrible"]]\n >>> ter = datasets.load_metric("ter")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... ignore_punct=True,\n ... case_sensitive=False)\n >>> print(results)\n {\'score\': 100.0, \'num_edits\': 10, \'ref_length\': 10.0}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCAmelCase ( datasets.Metric ): '''simple docstring''' def UpperCamelCase_ ( self : Tuple ): if version.parse(scb.__version__ ) < version.parse("1.4.12" ): raise ImportWarning( "To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn't match this condition.\n" "You can install it with `pip install \"sacrebleu>=1.4.12\"`." ) return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,homepage="http://www.cs.umd.edu/~snover/tercom/" ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { "predictions": datasets.Value("string" ,id="sequence" ), "references": datasets.Sequence(datasets.Value("string" ,id="sequence" ) ,id="references" ), } ) ,codebase_urls=["https://github.com/mjpost/sacreBLEU#ter"] ,reference_urls=[ "https://github.com/jhclark/tercom", ] ,) def UpperCamelCase_ ( self : Any ,A : Optional[int] ,A : str ,A : bool = False ,A : bool = False ,A : bool = False ,A : bool = False ,): __A = len(references[0] ) if any(len(A ) != references_per_prediction for refs in references ): raise ValueError("Sacrebleu requires the same number of references for each prediction" ) __A = [[refs[i] for refs in references] for i in range(A )] __A = TER( normalized=A ,no_punct=A ,asian_support=A ,case_sensitive=A ,) __A = sb_ter.corpus_score(A ,A ) return {"score": output.score, "num_edits": output.num_edits, "ref_length": output.ref_length}
55
import unittest import numpy as np from datasets import load_dataset 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 BeitImageProcessor class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self : Any ,A : List[str] ,A : str=7 ,A : Optional[Any]=3 ,A : Any=18 ,A : int=30 ,A : int=4_00 ,A : List[str]=True ,A : Union[str, Any]=None ,A : Union[str, Any]=True ,A : Tuple=None ,A : Tuple=True ,A : Union[str, Any]=[0.5, 0.5, 0.5] ,A : str=[0.5, 0.5, 0.5] ,A : List[Any]=False ,): __A = size if size is not None else {"height": 20, "width": 20} __A = crop_size if crop_size is not None else {"height": 18, "width": 18} __A = parent __A = batch_size __A = num_channels __A = image_size __A = min_resolution __A = max_resolution __A = do_resize __A = size __A = do_center_crop __A = crop_size __A = do_normalize __A = image_mean __A = image_std __A = do_reduce_labels def UpperCamelCase_ ( self : List[str] ): return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_reduce_labels": self.do_reduce_labels, } def UpperCAmelCase ( ) -> int: """simple docstring""" __A = load_dataset("hf-internal-testing/fixtures_ade20k" , split="test" ) __A = Image.open(dataset[0]["file"] ) __A = Image.open(dataset[1]["file"] ) return image, map def UpperCAmelCase ( ) -> Optional[int]: """simple docstring""" __A = load_dataset("hf-internal-testing/fixtures_ade20k" , split="test" ) __A = Image.open(ds[0]["file"] ) __A = Image.open(ds[1]["file"] ) __A = Image.open(ds[2]["file"] ) __A = Image.open(ds[3]["file"] ) return [imagea, imagea], [mapa, mapa] @require_torch @require_vision class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = BeitImageProcessor if is_vision_available() else None def UpperCamelCase_ ( self : List[Any] ): __A = BeitImageProcessingTester(self ) @property def UpperCamelCase_ ( self : List[Any] ): return self.image_processor_tester.prepare_image_processor_dict() def UpperCamelCase_ ( self : int ): __A = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(A ,"do_resize" ) ) self.assertTrue(hasattr(A ,"size" ) ) self.assertTrue(hasattr(A ,"do_center_crop" ) ) self.assertTrue(hasattr(A ,"center_crop" ) ) self.assertTrue(hasattr(A ,"do_normalize" ) ) self.assertTrue(hasattr(A ,"image_mean" ) ) self.assertTrue(hasattr(A ,"image_std" ) ) def UpperCamelCase_ ( self : List[str] ): __A = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size ,{"height": 20, "width": 20} ) self.assertEqual(image_processor.crop_size ,{"height": 18, "width": 18} ) self.assertEqual(image_processor.do_reduce_labels ,A ) __A = self.image_processing_class.from_dict( self.image_processor_dict ,size=42 ,crop_size=84 ,reduce_labels=A ) self.assertEqual(image_processor.size ,{"height": 42, "width": 42} ) self.assertEqual(image_processor.crop_size ,{"height": 84, "width": 84} ) self.assertEqual(image_processor.do_reduce_labels ,A ) def UpperCamelCase_ ( self : List[Any] ): pass def UpperCamelCase_ ( self : Optional[int] ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __A = prepare_image_inputs(self.image_processor_tester ,equal_resolution=A ) for image in image_inputs: self.assertIsInstance(A ,Image.Image ) # Test not batched input __A = 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 __A = image_processing(A ,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 UpperCamelCase_ ( self : List[str] ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __A = prepare_image_inputs(self.image_processor_tester ,equal_resolution=A ,numpify=A ) for image in image_inputs: self.assertIsInstance(A ,np.ndarray ) # Test not batched input __A = 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 __A = image_processing(A ,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 UpperCamelCase_ ( self : int ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A = prepare_image_inputs(self.image_processor_tester ,equal_resolution=A ,torchify=A ) for image in image_inputs: self.assertIsInstance(A ,torch.Tensor ) # Test not batched input __A = 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 __A = image_processing(A ,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 UpperCamelCase_ ( self : str ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A = prepare_image_inputs(self.image_processor_tester ,equal_resolution=A ,torchify=A ) __A = [] for image in image_inputs: self.assertIsInstance(A ,torch.Tensor ) maps.append(torch.zeros(image.shape[-2:] ).long() ) # Test not batched input __A = image_processing(image_inputs[0] ,maps[0] ,return_tensors="pt" ) self.assertEqual( encoding["pixel_values"].shape ,( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,) self.assertEqual( encoding["labels"].shape ,( 1, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,) self.assertEqual(encoding["labels"].dtype ,torch.long ) self.assertTrue(encoding["labels"].min().item() >= 0 ) self.assertTrue(encoding["labels"].max().item() <= 2_55 ) # Test batched __A = image_processing(A ,A ,return_tensors="pt" ) self.assertEqual( encoding["pixel_values"].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"], ) ,) self.assertEqual( encoding["labels"].shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,) self.assertEqual(encoding["labels"].dtype ,torch.long ) self.assertTrue(encoding["labels"].min().item() >= 0 ) self.assertTrue(encoding["labels"].max().item() <= 2_55 ) # Test not batched input (PIL images) __A , __A = prepare_semantic_single_inputs() __A = image_processing(A ,A ,return_tensors="pt" ) self.assertEqual( encoding["pixel_values"].shape ,( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,) self.assertEqual( encoding["labels"].shape ,( 1, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,) self.assertEqual(encoding["labels"].dtype ,torch.long ) self.assertTrue(encoding["labels"].min().item() >= 0 ) self.assertTrue(encoding["labels"].max().item() <= 2_55 ) # Test batched input (PIL images) __A , __A = prepare_semantic_batch_inputs() __A = image_processing(A ,A ,return_tensors="pt" ) self.assertEqual( encoding["pixel_values"].shape ,( 2, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,) self.assertEqual( encoding["labels"].shape ,( 2, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,) self.assertEqual(encoding["labels"].dtype ,torch.long ) self.assertTrue(encoding["labels"].min().item() >= 0 ) self.assertTrue(encoding["labels"].max().item() <= 2_55 ) def UpperCamelCase_ ( self : Dict ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # ADE20k has 150 classes, and the background is included, so labels should be between 0 and 150 __A , __A = prepare_semantic_single_inputs() __A = image_processing(A ,A ,return_tensors="pt" ) self.assertTrue(encoding["labels"].min().item() >= 0 ) self.assertTrue(encoding["labels"].max().item() <= 1_50 ) __A = True __A = image_processing(A ,A ,return_tensors="pt" ) self.assertTrue(encoding["labels"].min().item() >= 0 ) self.assertTrue(encoding["labels"].max().item() <= 2_55 )
55
1
import inspect import os import unittest import torch import accelerate from accelerate import debug_launcher from accelerate.test_utils import ( execute_subprocess_async, require_cpu, require_huggingface_suite, require_multi_gpu, require_single_gpu, ) from accelerate.utils import patch_environment @require_huggingface_suite class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase_ ( self : List[str] ): __A = inspect.getfile(accelerate.test_utils ) __A = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ["scripts", "external_deps", "test_metrics.py"] ) from accelerate.test_utils.scripts.external_deps import test_metrics # noqa: F401 __A = test_metrics @require_cpu def UpperCamelCase_ ( self : str ): debug_launcher(self.test_metrics.main ,num_processes=1 ) @require_cpu def UpperCamelCase_ ( self : str ): debug_launcher(self.test_metrics.main ) @require_single_gpu def UpperCamelCase_ ( self : List[str] ): self.test_metrics.main() @require_multi_gpu def UpperCamelCase_ ( self : int ): print(f'''Found {torch.cuda.device_count()} devices.''' ) __A = ["torchrun", f'''--nproc_per_node={torch.cuda.device_count()}''', self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(A ,env=os.environ.copy() )
55
from numpy import exp, pi, sqrt def UpperCAmelCase ( a_ , a_ = 0.0 , a_ = 1.0 ) -> int: """simple docstring""" return 1 / sqrt(2 * pi * sigma**2 ) * exp(-((x - mu) ** 2) / (2 * sigma**2) ) if __name__ == "__main__": import doctest doctest.testmod()
55
1
def UpperCAmelCase ( ) -> List[Any]: """simple docstring""" __A = 0 for i in range(1 , 1_0_0_1 ): total += i**i return str(a_ )[-1_0:] if __name__ == "__main__": print(solution())
55
import gc import unittest from diffusers import FlaxStableDiffusionInpaintPipeline from diffusers.utils import is_flax_available, load_image, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard @slow @require_flax class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase_ ( self : Tuple ): # clean up the VRAM after each test super().tearDown() gc.collect() def UpperCamelCase_ ( self : Optional[int] ): __A = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/sd2-inpaint/init_image.png" ) __A = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png" ) __A = "xvjiarui/stable-diffusion-2-inpainting" __A , __A = FlaxStableDiffusionInpaintPipeline.from_pretrained(A ,safety_checker=A ) __A = "Face of a yellow cat, high resolution, sitting on a park bench" __A = jax.random.PRNGKey(0 ) __A = 50 __A = jax.device_count() __A = num_samples * [prompt] __A = num_samples * [init_image] __A = num_samples * [mask_image] __A , __A , __A = pipeline.prepare_inputs(A ,A ,A ) # shard inputs and rng __A = replicate(A ) __A = jax.random.split(A ,jax.device_count() ) __A = shard(A ) __A = shard(A ) __A = shard(A ) __A = pipeline( A ,A ,A ,A ,A ,A ,jit=A ) __A = output.images.reshape(A ,5_12 ,5_12 ,3 ) __A = images[0, 2_53:2_56, 2_53:2_56, -1] __A = jnp.asarray(jax.device_get(image_slice.flatten() ) ) __A = jnp.array( [0.3_61_13_07, 0.37_64_97_36, 0.3_75_74_08, 0.38_21_39_53, 0.39_29_51_67, 0.3_84_16_31, 0.41_55_49_78, 0.4_13_74_75, 0.4_21_70_84] ) print(f'''output_slice: {output_slice}''' ) assert jnp.abs(output_slice - expected_slice ).max() < 1E-2
55
1
from .constants import ( MODEL_NAME, OPTIMIZER_NAME, RNG_STATE_NAME, SAFE_WEIGHTS_INDEX_NAME, SAFE_WEIGHTS_NAME, SCALER_NAME, SCHEDULER_NAME, TORCH_LAUNCH_PARAMS, WEIGHTS_INDEX_NAME, WEIGHTS_NAME, ) from .dataclasses import ( BnbQuantizationConfig, ComputeEnvironment, CustomDtype, DeepSpeedPlugin, DistributedDataParallelKwargs, DistributedType, DynamoBackend, FPaRecipeKwargs, FullyShardedDataParallelPlugin, GradientAccumulationPlugin, GradScalerKwargs, InitProcessGroupKwargs, KwargsHandler, LoggerType, MegatronLMPlugin, PrecisionType, ProjectConfiguration, RNGType, SageMakerDistributedType, TensorInformation, TorchDynamoPlugin, ) from .environment import get_int_from_env, parse_choice_from_env, parse_flag_from_env from .imports import ( get_ccl_version, is_abit_bnb_available, is_abit_bnb_available, is_aim_available, is_bfaa_available, is_bnb_available, is_botoa_available, is_ccl_available, is_comet_ml_available, is_datasets_available, is_deepspeed_available, is_fpa_available, is_ipex_available, is_megatron_lm_available, is_mlflow_available, is_mps_available, is_npu_available, is_rich_available, is_safetensors_available, is_sagemaker_available, is_tensorboard_available, is_tpu_available, is_transformers_available, is_wandb_available, is_xpu_available, ) from .modeling import ( check_device_map, check_tied_parameters_in_config, check_tied_parameters_on_same_device, compute_module_sizes, convert_file_size_to_int, dtype_byte_size, find_tied_parameters, get_balanced_memory, get_max_layer_size, get_max_memory, get_mixed_precision_context_manager, id_tensor_storage, infer_auto_device_map, load_checkpoint_in_model, load_offloaded_weights, load_state_dict, named_module_tensors, retie_parameters, set_module_tensor_to_device, shard_checkpoint, ) from .offload import ( OffloadedWeightsLoader, PrefixedDataset, extract_submodules_state_dict, load_offloaded_weight, offload_state_dict, offload_weight, save_offload_index, ) from .operations import ( broadcast, broadcast_object_list, concatenate, convert_outputs_to_fpaa, convert_to_fpaa, find_batch_size, find_device, gather, gather_object, get_data_structure, honor_type, initialize_tensors, is_namedtuple, is_tensor_information, is_torch_tensor, listify, pad_across_processes, recursively_apply, reduce, send_to_device, slice_tensors, ) from .versions import compare_versions, is_torch_version if is_deepspeed_available(): from .deepspeed import ( DeepSpeedEngineWrapper, DeepSpeedOptimizerWrapper, DeepSpeedSchedulerWrapper, DummyOptim, DummyScheduler, HfDeepSpeedConfig, ) from .bnb import has_abit_bnb_layers, load_and_quantize_model from .fsdp_utils import load_fsdp_model, load_fsdp_optimizer, save_fsdp_model, save_fsdp_optimizer from .launch import ( PrepareForLaunch, _filter_args, prepare_deepspeed_cmd_env, prepare_multi_gpu_env, prepare_sagemager_args_inputs, prepare_simple_launcher_cmd_env, prepare_tpu, ) from .megatron_lm import ( AbstractTrainStep, BertTrainStep, GPTTrainStep, MegatronEngine, MegatronLMDummyDataLoader, MegatronLMDummyScheduler, MegatronLMOptimizerWrapper, MegatronLMSchedulerWrapper, TaTrainStep, avg_losses_across_data_parallel_group, gather_across_data_parallel_groups, ) from .megatron_lm import initialize as megatron_lm_initialize from .megatron_lm import prepare_data_loader as megatron_lm_prepare_data_loader from .megatron_lm import prepare_model as megatron_lm_prepare_model from .megatron_lm import prepare_optimizer as megatron_lm_prepare_optimizer from .megatron_lm import prepare_scheduler as megatron_lm_prepare_scheduler from .memory import find_executable_batch_size, release_memory from .other import ( extract_model_from_parallel, get_pretty_name, is_port_in_use, merge_dicts, patch_environment, save, wait_for_everyone, write_basic_config, ) from .random import set_seed, synchronize_rng_state, synchronize_rng_states from .torch_xla import install_xla from .tqdm import tqdm from .transformer_engine import convert_model, has_transformer_engine_layers
55
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 GLPNImageProcessor class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self : Any ,A : Optional[int] ,A : Optional[int]=7 ,A : Optional[Any]=3 ,A : List[str]=18 ,A : Any=30 ,A : Tuple=4_00 ,A : Union[str, Any]=True ,A : Optional[Any]=32 ,A : Union[str, Any]=True ,): __A = parent __A = batch_size __A = num_channels __A = image_size __A = min_resolution __A = max_resolution __A = do_resize __A = size_divisor __A = do_rescale def UpperCamelCase_ ( self : Union[str, Any] ): return { "do_resize": self.do_resize, "size_divisor": self.size_divisor, "do_rescale": self.do_rescale, } @require_torch @require_vision class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = GLPNImageProcessor if is_vision_available() else None def UpperCamelCase_ ( self : int ): __A = GLPNImageProcessingTester(self ) @property def UpperCamelCase_ ( self : Optional[Any] ): return self.image_processor_tester.prepare_image_processor_dict() def UpperCamelCase_ ( self : Any ): __A = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(A ,"do_resize" ) ) self.assertTrue(hasattr(A ,"size_divisor" ) ) self.assertTrue(hasattr(A ,"resample" ) ) self.assertTrue(hasattr(A ,"do_rescale" ) ) def UpperCamelCase_ ( self : str ): pass def UpperCamelCase_ ( self : Dict ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __A = prepare_image_inputs(self.image_processor_tester ,equal_resolution=A ) for image in image_inputs: self.assertIsInstance(A ,Image.Image ) # Test not batched input (GLPNImageProcessor doesn't support batching) __A = image_processing(image_inputs[0] ,return_tensors="pt" ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 ) def UpperCamelCase_ ( self : Optional[Any] ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __A = prepare_image_inputs(self.image_processor_tester ,equal_resolution=A ,numpify=A ) for image in image_inputs: self.assertIsInstance(A ,np.ndarray ) # Test not batched input (GLPNImageProcessor doesn't support batching) __A = image_processing(image_inputs[0] ,return_tensors="pt" ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 ) def UpperCamelCase_ ( self : int ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A = prepare_image_inputs(self.image_processor_tester ,equal_resolution=A ,torchify=A ) for image in image_inputs: self.assertIsInstance(A ,torch.Tensor ) # Test not batched input (GLPNImageProcessor doesn't support batching) __A = image_processing(image_inputs[0] ,return_tensors="pt" ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 )
55
1
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 from accelerate.local_sgd import LocalSGD ######################################################################## # This is a fully working simple example to use Accelerate # with LocalSGD, which is a method to synchronize model # parameters every K batches. It is different, but complementary # to gradient accumulation. # # 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 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 :int = 16 SCREAMING_SNAKE_CASE :Any = 32 def UpperCAmelCase ( a_ , a_ = 1_6 ) -> List[Any]: """simple docstring""" __A = AutoTokenizer.from_pretrained("bert-base-cased" ) __A = load_dataset("glue" , "mrpc" ) def tokenize_function(a_ ): # max_length=None => use the model max length (it's actually the default) __A = tokenizer(examples["sentence1"] , examples["sentence2"] , truncation=a_ , max_length=a_ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): __A = datasets.map( a_ , batched=a_ , 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 __A = tokenized_datasets.rename_column("label" , "labels" ) def collate_fn(a_ ): # On TPU it's best to pad everything to the same length or training will be very slow. __A = 1_2_8 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": __A = 1_6 elif accelerator.mixed_precision != "no": __A = 8 else: __A = None return tokenizer.pad( a_ , padding="longest" , max_length=a_ , pad_to_multiple_of=a_ , return_tensors="pt" , ) # Instantiate dataloaders. __A = DataLoader( tokenized_datasets["train"] , shuffle=a_ , collate_fn=a_ , batch_size=a_ ) __A = DataLoader( tokenized_datasets["validation"] , shuffle=a_ , collate_fn=a_ , batch_size=a_ ) 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 :Any = mocked_dataloaders # noqa: F811 def UpperCAmelCase ( a_ , a_ ) -> str: """simple docstring""" if os.environ.get("TESTING_MOCKED_DATALOADERS" , a_ ) == "1": __A = 2 # New Code # __A = int(args.gradient_accumulation_steps ) __A = int(args.local_sgd_steps ) # Initialize accelerator __A = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , gradient_accumulation_steps=a_ ) if accelerator.distributed_type not in [DistributedType.NO, DistributedType.MULTI_CPU, DistributedType.MULTI_GPU]: raise NotImplementedError("LocalSGD is supported only for CPUs and GPUs (no DeepSpeed or MegatronLM)" ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs __A = config["lr"] __A = int(config["num_epochs"] ) __A = int(config["seed"] ) __A = int(config["batch_size"] ) __A = evaluate.load("glue" , "mrpc" ) set_seed(a_ ) __A , __A = get_dataloaders(a_ , a_ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) __A = AutoModelForSequenceClassification.from_pretrained("bert-base-cased" , return_dict=a_ ) # 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). __A = model.to(accelerator.device ) # Instantiate optimizer __A = AdamW(params=model.parameters() , lr=a_ ) # Instantiate scheduler __A = get_linear_schedule_with_warmup( optimizer=a_ , num_warmup_steps=1_0_0 , num_training_steps=(len(a_ ) * num_epochs) , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. __A , __A , __A , __A , __A = accelerator.prepare( a_ , a_ , a_ , a_ , a_ ) # Now we train the model for epoch in range(a_ ): model.train() with LocalSGD( accelerator=a_ , model=a_ , local_sgd_steps=a_ , enabled=local_sgd_steps is not None ) as local_sgd: for step, batch in enumerate(a_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(a_ ): __A = model(**a_ ) __A = output.loss accelerator.backward(a_ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() # LocalSGD-specific line local_sgd.step() model.eval() for step, batch in enumerate(a_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): __A = model(**a_ ) __A = outputs.logits.argmax(dim=-1 ) __A , __A = accelerator.gather_for_metrics((predictions, batch["labels"]) ) metric.add_batch( predictions=a_ , references=a_ , ) __A = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'''epoch {epoch}:''' , a_ ) def UpperCAmelCase ( ) -> int: """simple docstring""" __A = argparse.ArgumentParser(description="Simple example of training script." ) parser.add_argument( "--mixed_precision" , type=a_ , default=a_ , 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." , ) # New Code # parser.add_argument( "--gradient_accumulation_steps" , type=a_ , default=1 , help="The number of minibatches to be ran before gradients are accumulated." , ) parser.add_argument( "--local_sgd_steps" , type=a_ , default=8 , help="Number of local SGD steps or None to disable local SGD" ) parser.add_argument("--cpu" , action="store_true" , help="If passed, will train on the CPU." ) __A = parser.parse_args() __A = {"lr": 2E-5, "num_epochs": 3, "seed": 4_2, "batch_size": 1_6} training_function(a_ , a_ ) if __name__ == "__main__": main()
55
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Image from .base import TaskTemplate @dataclass(frozen=__SCREAMING_SNAKE_CASE ) class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = field(default="image-classification" , metadata={"include_in_asdict_even_if_is_default": True} ) snake_case_ = Features({"image": Image()} ) snake_case_ = Features({"labels": ClassLabel} ) snake_case_ = "image" snake_case_ = "labels" def UpperCamelCase_ ( self : Optional[Any] ,A : Tuple ): if self.label_column not in features: raise ValueError(f'''Column {self.label_column} is not present in features.''' ) if not isinstance(features[self.label_column] ,A ): raise ValueError(f'''Column {self.label_column} is not a ClassLabel.''' ) __A = copy.deepcopy(self ) __A = self.label_schema.copy() __A = features[self.label_column] __A = label_schema return task_template @property def UpperCamelCase_ ( self : Any ): return { self.image_column: "image", self.label_column: "labels", }
55
1
SCREAMING_SNAKE_CASE :Optional[Any] = 8.314462 # Unit - J mol-1 K-1 def UpperCAmelCase ( a_ , a_ , a_ ) -> float: """simple docstring""" if moles < 0 or kelvin < 0 or volume < 0: raise ValueError("Invalid inputs. Enter positive value." ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / volume def UpperCAmelCase ( a_ , a_ , a_ ) -> float: """simple docstring""" if moles < 0 or kelvin < 0 or pressure < 0: raise ValueError("Invalid inputs. Enter positive value." ) return moles * kelvin * UNIVERSAL_GAS_CONSTANT / pressure if __name__ == "__main__": from doctest import testmod testmod()
55
from math import sqrt def UpperCAmelCase ( a_ ) -> bool: """simple docstring""" assert isinstance(a_ , a_ ) and ( number >= 0 ), "'number' must been an int and positive" __A = True # 0 and 1 are none primes. if number <= 1: __A = False for divisor in range(2 , int(round(sqrt(a_ ) ) ) + 1 ): # if 'number' divisible by 'divisor' then sets 'status' # of false and break up the loop. if number % divisor == 0: __A = False break # precondition assert isinstance(a_ , a_ ), "'status' must been from type bool" return status def UpperCAmelCase ( a_ ) -> Any: """simple docstring""" assert isinstance(a_ , a_ ) and (n > 2), "'N' must been an int and > 2" # beginList: contains all natural numbers from 2 up to N __A = list(range(2 , n + 1 ) ) __A = [] # this list will be returns. # actual sieve of erathostenes for i in range(len(a_ ) ): for j in range(i + 1 , len(a_ ) ): if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0): __A = 0 # filters actual prime numbers. __A = [x for x in begin_list if x != 0] # precondition assert isinstance(a_ , a_ ), "'ans' must been from type list" return ans def UpperCAmelCase ( a_ ) -> Optional[int]: """simple docstring""" assert isinstance(a_ , a_ ) and (n > 2), "'N' must been an int and > 2" __A = [] # iterates over all numbers between 2 up to N+1 # if a number is prime then appends to list 'ans' for number in range(2 , n + 1 ): if is_prime(a_ ): ans.append(a_ ) # precondition assert isinstance(a_ , a_ ), "'ans' must been from type list" return ans def UpperCAmelCase ( a_ ) -> Optional[int]: """simple docstring""" assert isinstance(a_ , a_ ) and number >= 0, "'number' must been an int and >= 0" __A = [] # this list will be returns of the function. # potential prime number factors. __A = 2 __A = number if number == 0 or number == 1: ans.append(a_ ) # if 'number' not prime then builds the prime factorization of 'number' elif not is_prime(a_ ): while quotient != 1: if is_prime(a_ ) and (quotient % factor == 0): ans.append(a_ ) quotient /= factor else: factor += 1 else: ans.append(a_ ) # precondition assert isinstance(a_ , a_ ), "'ans' must been from type list" return ans def UpperCAmelCase ( a_ ) -> Any: """simple docstring""" assert isinstance(a_ , a_ ) and ( number >= 0 ), "'number' bust been an int and >= 0" __A = 0 # prime factorization of 'number' __A = prime_factorization(a_ ) __A = max(a_ ) # precondition assert isinstance(a_ , a_ ), "'ans' must been from type int" return ans def UpperCAmelCase ( a_ ) -> Optional[Any]: """simple docstring""" assert isinstance(a_ , a_ ) and ( number >= 0 ), "'number' bust been an int and >= 0" __A = 0 # prime factorization of 'number' __A = prime_factorization(a_ ) __A = min(a_ ) # precondition assert isinstance(a_ , a_ ), "'ans' must been from type int" return ans def UpperCAmelCase ( a_ ) -> int: """simple docstring""" assert isinstance(a_ , a_ ), "'number' must been an int" assert isinstance(number % 2 == 0 , a_ ), "compare bust been from type bool" return number % 2 == 0 def UpperCAmelCase ( a_ ) -> List[Any]: """simple docstring""" assert isinstance(a_ , a_ ), "'number' must been an int" assert isinstance(number % 2 != 0 , a_ ), "compare bust been from type bool" return number % 2 != 0 def UpperCAmelCase ( a_ ) -> Optional[Any]: """simple docstring""" assert ( isinstance(a_ , a_ ) and (number > 2) and is_even(a_ ) ), "'number' must been an int, even and > 2" __A = [] # this list will returned # creates a list of prime numbers between 2 up to 'number' __A = get_prime_numbers(a_ ) __A = len(a_ ) # run variable for while-loops. __A = 0 __A = None # exit variable. for break up the loops __A = True while i < len_pn and loop: __A = i + 1 while j < len_pn and loop: if prime_numbers[i] + prime_numbers[j] == number: __A = False ans.append(prime_numbers[i] ) ans.append(prime_numbers[j] ) j += 1 i += 1 # precondition assert ( isinstance(a_ , a_ ) and (len(a_ ) == 2) and (ans[0] + ans[1] == number) and is_prime(ans[0] ) and is_prime(ans[1] ) ), "'ans' must contains two primes. And sum of elements must been eq 'number'" return ans def UpperCAmelCase ( a_ , a_ ) -> Optional[Any]: """simple docstring""" assert ( isinstance(a_ , a_ ) and isinstance(a_ , a_ ) and (numbera >= 0) and (numbera >= 0) ), "'number1' and 'number2' must been positive integer." __A = 0 while numbera != 0: __A = numbera % numbera __A = numbera __A = rest # precondition assert isinstance(a_ , a_ ) and ( numbera >= 0 ), "'number' must been from type int and positive" return numbera def UpperCAmelCase ( a_ , a_ ) -> List[str]: """simple docstring""" assert ( isinstance(a_ , a_ ) and isinstance(a_ , a_ ) and (numbera >= 1) and (numbera >= 1) ), "'number1' and 'number2' must been positive integer." __A = 1 # actual answer that will be return. # for kgV (x,1) if numbera > 1 and numbera > 1: # builds the prime factorization of 'number1' and 'number2' __A = prime_factorization(a_ ) __A = prime_factorization(a_ ) elif numbera == 1 or numbera == 1: __A = [] __A = [] __A = max(a_ , a_ ) __A = 0 __A = 0 __A = [] # captured numbers int both 'primeFac1' and 'primeFac2' # iterates through primeFac1 for n in prime_fac_a: if n not in done: if n in prime_fac_a: __A = prime_fac_a.count(a_ ) __A = prime_fac_a.count(a_ ) for _ in range(max(a_ , a_ ) ): ans *= n else: __A = prime_fac_a.count(a_ ) for _ in range(a_ ): ans *= n done.append(a_ ) # iterates through primeFac2 for n in prime_fac_a: if n not in done: __A = prime_fac_a.count(a_ ) for _ in range(a_ ): ans *= n done.append(a_ ) # precondition assert isinstance(a_ , a_ ) and ( ans >= 0 ), "'ans' must been from type int and positive" return ans def UpperCAmelCase ( a_ ) -> str: """simple docstring""" assert isinstance(a_ , a_ ) and (n >= 0), "'number' must been a positive int" __A = 0 __A = 2 # this variable holds the answer while index < n: index += 1 ans += 1 # counts to the next number # if ans not prime then # runs to the next prime number. while not is_prime(a_ ): ans += 1 # precondition assert isinstance(a_ , a_ ) and is_prime( a_ ), "'ans' must been a prime number and from type int" return ans def UpperCAmelCase ( a_ , a_ ) -> Tuple: """simple docstring""" assert ( is_prime(a_ ) and is_prime(a_ ) and (p_number_a < p_number_a) ), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'" __A = p_number_a + 1 # jump to the next number __A = [] # this list will be returns. # if number is not prime then # fetch the next prime number. while not is_prime(a_ ): number += 1 while number < p_number_a: ans.append(a_ ) number += 1 # fetch the next prime number. while not is_prime(a_ ): number += 1 # precondition assert ( isinstance(a_ , a_ ) and ans[0] != p_number_a and ans[len(a_ ) - 1] != p_number_a ), "'ans' must been a list without the arguments" # 'ans' contains not 'pNumber1' and 'pNumber2' ! return ans def UpperCAmelCase ( a_ ) -> str: """simple docstring""" assert isinstance(a_ , a_ ) and (n >= 1), "'n' must been int and >= 1" __A = [] # will be returned. for divisor in range(1 , n + 1 ): if n % divisor == 0: ans.append(a_ ) # precondition assert ans[0] == 1 and ans[len(a_ ) - 1] == n, "Error in function getDivisiors(...)" return ans def UpperCAmelCase ( a_ ) -> Dict: """simple docstring""" assert isinstance(a_ , a_ ) and ( number > 1 ), "'number' must been an int and >= 1" __A = get_divisors(a_ ) # precondition assert ( isinstance(a_ , a_ ) and (divisors[0] == 1) and (divisors[len(a_ ) - 1] == number) ), "Error in help-function getDivisiors(...)" # summed all divisors up to 'number' (exclusive), hence [:-1] return sum(divisors[:-1] ) == number def UpperCAmelCase ( a_ , a_ ) -> str: """simple docstring""" assert ( isinstance(a_ , a_ ) and isinstance(a_ , a_ ) and (denominator != 0) ), "The arguments must been from type int and 'denominator' != 0" # build the greatest common divisor of numerator and denominator. __A = gcd(abs(a_ ) , abs(a_ ) ) # precondition assert ( isinstance(a_ , a_ ) and (numerator % gcd_of_fraction == 0) and (denominator % gcd_of_fraction == 0) ), "Error in function gcd(...,...)" return (numerator // gcd_of_fraction, denominator // gcd_of_fraction) def UpperCAmelCase ( a_ ) -> Optional[int]: """simple docstring""" assert isinstance(a_ , a_ ) and (n >= 0), "'n' must been a int and >= 0" __A = 1 # this will be return. for factor in range(1 , n + 1 ): ans *= factor return ans def UpperCAmelCase ( a_ ) -> List[Any]: """simple docstring""" assert isinstance(a_ , a_ ) and (n >= 0), "'n' must been an int and >= 0" __A = 0 __A = 1 __A = 1 # this will be return for _ in range(n - 1 ): __A = ans ans += fiba __A = tmp return ans
55
1
from pickle import UnpicklingError import jax import jax.numpy as jnp import numpy as np from flax.serialization import from_bytes from flax.traverse_util import flatten_dict from ..utils import logging SCREAMING_SNAKE_CASE :Tuple = logging.get_logger(__name__) def UpperCAmelCase ( a_ , a_ ) -> List[str]: """simple docstring""" try: with open(a_ , "rb" ) as flax_state_f: __A = from_bytes(a_ , flax_state_f.read() ) except UnpicklingError as e: try: with open(a_ ) as f: if f.read().startswith("version" ): raise OSError( "You seem to have cloned a repository without having git-lfs installed. Please" " install git-lfs and run `git lfs install` followed by `git lfs pull` in the" " folder you cloned." ) else: raise ValueError from e except (UnicodeDecodeError, ValueError): raise EnvironmentError(F'''Unable to convert {model_file} to Flax deserializable object. ''' ) return load_flax_weights_in_pytorch_model(a_ , a_ ) def UpperCAmelCase ( a_ , a_ ) -> List[Any]: """simple docstring""" try: import torch # noqa: F401 except ImportError: logger.error( "Loading Flax weights in PyTorch requires both PyTorch and Flax to be installed. Please see" " https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation" " instructions." ) raise # check if we have bf16 weights __A = flatten_dict(jax.tree_util.tree_map(lambda a_ : x.dtype == jnp.bfloataa , a_ ) ).values() if any(a_ ): # convert all weights to fp32 if they are bf16 since torch.from_numpy can-not handle bf16 # and bf16 is not fully supported in PT yet. logger.warning( "Found ``bfloat16`` weights in Flax model. Casting all ``bfloat16`` weights to ``float32`` " "before loading those in PyTorch model." ) __A = jax.tree_util.tree_map( lambda a_ : params.astype(np.floataa ) if params.dtype == jnp.bfloataa else params , a_ ) __A = "" __A = flatten_dict(a_ , sep="." ) __A = pt_model.state_dict() # keep track of unexpected & missing keys __A = [] __A = set(pt_model_dict.keys() ) for flax_key_tuple, flax_tensor in flax_state_dict.items(): __A = flax_key_tuple.split("." ) if flax_key_tuple_array[-1] == "kernel" and flax_tensor.ndim == 4: __A = flax_key_tuple_array[:-1] + ["weight"] __A = jnp.transpose(a_ , (3, 2, 0, 1) ) elif flax_key_tuple_array[-1] == "kernel": __A = flax_key_tuple_array[:-1] + ["weight"] __A = flax_tensor.T elif flax_key_tuple_array[-1] == "scale": __A = flax_key_tuple_array[:-1] + ["weight"] if "time_embedding" not in flax_key_tuple_array: for i, flax_key_tuple_string in enumerate(a_ ): __A = ( flax_key_tuple_string.replace("_0" , ".0" ) .replace("_1" , ".1" ) .replace("_2" , ".2" ) .replace("_3" , ".3" ) .replace("_4" , ".4" ) .replace("_5" , ".5" ) .replace("_6" , ".6" ) .replace("_7" , ".7" ) .replace("_8" , ".8" ) .replace("_9" , ".9" ) ) __A = ".".join(a_ ) if flax_key in pt_model_dict: if flax_tensor.shape != pt_model_dict[flax_key].shape: raise ValueError( F'''Flax checkpoint seems to be incorrect. Weight {flax_key_tuple} was expected ''' F'''to be of shape {pt_model_dict[flax_key].shape}, but is {flax_tensor.shape}.''' ) else: # add weight to pytorch dict __A = np.asarray(a_ ) if not isinstance(a_ , np.ndarray ) else flax_tensor __A = torch.from_numpy(a_ ) # remove from missing keys missing_keys.remove(a_ ) else: # weight is not expected by PyTorch model unexpected_keys.append(a_ ) pt_model.load_state_dict(a_ ) # re-transform missing_keys to list __A = list(a_ ) if len(a_ ) > 0: logger.warning( "Some weights of the Flax model were not used when initializing the PyTorch model" F''' {pt_model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are initializing''' F''' {pt_model.__class__.__name__} from a Flax model trained on another task or with another architecture''' " (e.g. initializing a BertForSequenceClassification model from a FlaxBertForPreTraining model).\n- This" F''' IS NOT expected if you are initializing {pt_model.__class__.__name__} from a Flax model that you expect''' " to be exactly identical (e.g. initializing a BertForSequenceClassification model from a" " FlaxBertForSequenceClassification model)." ) if len(a_ ) > 0: logger.warning( F'''Some weights of {pt_model.__class__.__name__} were not initialized from the Flax model and are newly''' F''' initialized: {missing_keys}\nYou should probably TRAIN this model on a down-stream task to be able to''' " use it for predictions and inference." ) return pt_model
55
import os def UpperCAmelCase ( ) -> Any: """simple docstring""" __A = os.path.dirname(os.path.realpath(a_ ) ) __A = os.path.join(a_ , "triangle.txt" ) with open(a_ ) as f: __A = f.readlines() __A = [] for line in triangle: __A = [] for number in line.strip().split(" " ): numbers_from_line.append(int(a_ ) ) a.append(a_ ) for i in range(1 , len(a_ ) ): for j in range(len(a[i] ) ): __A = a[i - 1][j] if j != len(a[i - 1] ) else 0 __A = a[i - 1][j - 1] if j > 0 else 0 a[i][j] += max(a_ , a_ ) return max(a[-1] ) if __name__ == "__main__": print(solution())
55
1
def UpperCAmelCase ( a_ = 1_0_0_0 ) -> int: """simple docstring""" __A = 3 __A = 0 while a < n: if a % 3 == 0 or a % 5 == 0: result += a elif a % 1_5 == 0: result -= a a += 1 return result if __name__ == "__main__": print(f'''{solution() = }''')
55
import re from flax.core.frozen_dict import freeze from flax.traverse_util import flatten_dict, unflatten_dict from jax.experimental import PartitionSpec as P # Sentinels SCREAMING_SNAKE_CASE :Union[str, Any] = object() # For specifying empty leaf dict `{}` SCREAMING_SNAKE_CASE :List[str] = object() def UpperCAmelCase ( a_ , a_ ) -> Tuple: """simple docstring""" __A = tuple((re.compile(x + "$" ) for x in qs) ) for i in range(len(a_ ) - len(a_ ) + 1 ): __A = [x.match(a_ ) for x, y in zip(a_ , ks[i:] )] if matches and all(a_ ): return True return False def UpperCAmelCase ( a_ ) -> Optional[int]: """simple docstring""" def replace(a_ , a_ ): for rule, replacement in rules: if _match(a_ , a_ ): return replacement return val return replace def UpperCAmelCase ( ) -> int: """simple docstring""" return [ # embeddings (("transformer", "wpe", "embedding"), P("mp" , a_ )), (("transformer", "wte", "embedding"), P("mp" , a_ )), # atention (("attention", "(q_proj|k_proj|v_proj)", "kernel"), P(a_ , "mp" )), (("attention", "out_proj", "kernel"), P("mp" , a_ )), (("attention", "out_proj", "bias"), None), # mlp (("mlp", "c_fc", "kernel"), P(a_ , "mp" )), (("mlp", "c_fc", "bias"), P("mp" )), (("mlp", "c_proj", "kernel"), P("mp" , a_ )), (("mlp", "c_proj", "bias"), None), # layer norms ((r"ln_\d+", "bias"), None), ((r"\d+", r"ln_\d+", "scale"), None), (("ln_f", "bias"), None), (("ln_f", "scale"), None), ] def UpperCAmelCase ( a_ ) -> List[Any]: """simple docstring""" __A = _get_partition_rules() __A = _replacement_rules(a_ ) __A = {k: _unmatched for k in flatten_dict(a_ )} __A = {k: replace(a_ , a_ ) for k, v in initd.items()} assert _unmatched not in result.values(), "Incomplete partition spec." return freeze(unflatten_dict(a_ ) )
55
1
import os import pickle import unittest from transformers import AutoTokenizer from transformers.models.bert.tokenization_bert import BertTokenizer from transformers.models.bert_japanese.tokenization_bert_japanese import ( VOCAB_FILES_NAMES, BertJapaneseTokenizer, CharacterTokenizer, JumanppTokenizer, MecabTokenizer, SudachiTokenizer, WordpieceTokenizer, ) from transformers.testing_utils import custom_tokenizers, require_jumanpp, require_sudachi from ...test_tokenization_common import TokenizerTesterMixin @custom_tokenizers class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = BertJapaneseTokenizer snake_case_ = False snake_case_ = True def UpperCamelCase_ ( self : Any ): super().setUp() __A = [ "[UNK]", "[CLS]", "[SEP]", "こんにちは", "こん", "にちは", "ばんは", "##こん", "##にちは", "##ばんは", "世界", "##世界", "、", "##、", "。", "##。", ] __A = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file ,"w" ,encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) def UpperCamelCase_ ( self : Dict ,A : Optional[Any] ): __A = "こんにちは、世界。 \nこんばんは、世界。" __A = "こんにちは 、 世界 。 こんばんは 、 世界 。" return input_text, output_text def UpperCamelCase_ ( self : int ,A : Tuple ): __A , __A = self.get_input_output_texts(A ) __A = tokenizer.encode(A ,add_special_tokens=A ) __A = tokenizer.decode(A ,clean_up_tokenization_spaces=A ) return text, ids def UpperCamelCase_ ( self : Any ): pass # TODO add if relevant def UpperCamelCase_ ( self : Tuple ): pass # TODO add if relevant def UpperCamelCase_ ( self : List[Any] ): pass # TODO add if relevant def UpperCamelCase_ ( self : Optional[int] ): __A = self.tokenizer_class(self.vocab_file ) __A = tokenizer.tokenize("こんにちは、世界。\nこんばんは、世界。" ) self.assertListEqual(A ,["こんにちは", "、", "世界", "。", "こん", "##ばんは", "、", "世界", "。"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(A ) ,[3, 12, 10, 14, 4, 9, 12, 10, 14] ) def UpperCamelCase_ ( self : List[str] ): __A = self.tokenizer_class(self.vocab_file ,word_tokenizer_type="mecab" ) self.assertIsNotNone(A ) __A = "こんにちは、世界。\nこんばんは、世界。" __A = tokenizer.tokenize(A ) self.assertListEqual(A ,["こんにちは", "、", "世界", "。", "こん", "##ばんは", "、", "世界", "。"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(A ) ,[3, 12, 10, 14, 4, 9, 12, 10, 14] ) __A = os.path.join(self.tmpdirname ,"tokenizer.bin" ) with open(A ,"wb" ) as handle: pickle.dump(A ,A ) with open(A ,"rb" ) as handle: __A = pickle.load(A ) __A = tokenizer_new.tokenize(A ) self.assertListEqual(A ,A ) def UpperCamelCase_ ( self : Union[str, Any] ): __A = MecabTokenizer(mecab_dic="ipadic" ) self.assertListEqual( tokenizer.tokenize(" \tアップルストアでiPhone8 が \n 発売された 。 " ) ,["アップルストア", "で", "iPhone", "8", "が", "発売", "さ", "れ", "た", "。"] ,) def UpperCamelCase_ ( self : Union[str, Any] ): try: __A = MecabTokenizer(mecab_dic="unidic_lite" ) except ModuleNotFoundError: return self.assertListEqual( tokenizer.tokenize(" \tアップルストアでiPhone8 が \n 発売された 。 " ) ,["アップル", "ストア", "で", "iPhone", "8", "が", "発売", "さ", "れ", "た", "。"] ,) def UpperCamelCase_ ( self : Dict ): try: __A = MecabTokenizer(mecab_dic="unidic" ) except ModuleNotFoundError: return self.assertListEqual( tokenizer.tokenize(" \tアップルストアでiPhone8 が \n 発売された 。 " ) ,["アップル", "ストア", "で", "iPhone", "8", "が", "発売", "さ", "れ", "た", "。"] ,) def UpperCamelCase_ ( self : Union[str, Any] ): __A = MecabTokenizer(do_lower_case=A ,mecab_dic="ipadic" ) self.assertListEqual( tokenizer.tokenize(" \tアップルストアでiPhone8 が \n 発売された 。 " ) ,["アップルストア", "で", "iphone", "8", "が", "発売", "さ", "れ", "た", "。"] ,) def UpperCamelCase_ ( self : Union[str, Any] ): try: __A = MecabTokenizer( do_lower_case=A ,normalize_text=A ,mecab_option="-d /usr/local/lib/mecab/dic/jumandic" ) except RuntimeError: # if dict doesn't exist in the system, previous code raises this error. return self.assertListEqual( tokenizer.tokenize(" \tアップルストアでiPhone8 が \n 発売された 。 " ) ,["アップルストア", "で", "iPhone", "8", "が", "発売", "さ", "れた", "\u3000", "。"] ,) def UpperCamelCase_ ( self : Union[str, Any] ): __A = MecabTokenizer(normalize_text=A ,mecab_dic="ipadic" ) self.assertListEqual( tokenizer.tokenize(" \tアップルストアでiPhone8 が \n 発売された 。 " ) ,["アップルストア", "で", "iPhone", "8", "が", "発売", "さ", "れ", "た", " ", "。"] ,) @require_sudachi def UpperCamelCase_ ( self : Union[str, Any] ): __A = self.tokenizer_class(self.vocab_file ,word_tokenizer_type="sudachi" ) self.assertIsNotNone(A ) __A = "こんにちは、世界。\nこんばんは、世界。" __A = tokenizer.tokenize(A ) self.assertListEqual(A ,["こんにちは", "、", "世界", "。", "こん", "##ばんは", "、", "世界", "。"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(A ) ,[3, 12, 10, 14, 4, 9, 12, 10, 14] ) __A = os.path.join(self.tmpdirname ,"tokenizer.bin" ) with open(A ,"wb" ) as handle: pickle.dump(A ,A ) with open(A ,"rb" ) as handle: __A = pickle.load(A ) __A = tokenizer_new.tokenize(A ) self.assertListEqual(A ,A ) @require_sudachi def UpperCamelCase_ ( self : int ): __A = SudachiTokenizer(sudachi_dict_type="core" ) self.assertListEqual( tokenizer.tokenize(" \tアップルストアでiPhone8 が \n 発売された 。 " ) ,[" ", "\t", "アップル", "ストア", "で", "iPhone", "8", " ", "が", " ", " ", "\n ", "発売", "さ", "れ", "た", " ", "。", " ", " "] ,) @require_sudachi def UpperCamelCase_ ( self : str ): __A = SudachiTokenizer(sudachi_dict_type="core" ,sudachi_split_mode="A" ) self.assertListEqual(tokenizer.tokenize("外国人参政権" ) ,["外国", "人", "参政", "権"] ) @require_sudachi def UpperCamelCase_ ( self : Optional[Any] ): __A = SudachiTokenizer(sudachi_dict_type="core" ,sudachi_split_mode="B" ) self.assertListEqual(tokenizer.tokenize("外国人参政権" ) ,["外国人", "参政権"] ) @require_sudachi def UpperCamelCase_ ( self : int ): __A = SudachiTokenizer(sudachi_dict_type="core" ,sudachi_split_mode="C" ) self.assertListEqual(tokenizer.tokenize("外国人参政権" ) ,["外国人参政権"] ) @require_sudachi def UpperCamelCase_ ( self : Tuple ): __A = SudachiTokenizer(do_lower_case=A ,sudachi_dict_type="core" ) self.assertListEqual( tokenizer.tokenize(" \tアップルストアでiPhone8 が \n 発売された 。 " ) ,[" ", "\t", "アップル", "ストア", "で", "iphone", "8", " ", "が", " ", " ", "\n ", "発売", "さ", "れ", "た", " ", "。", " ", " "] ,) @require_sudachi def UpperCamelCase_ ( self : List[Any] ): __A = SudachiTokenizer(normalize_text=A ,sudachi_dict_type="core" ) self.assertListEqual( tokenizer.tokenize(" \tアップルストアでiPhone8 が \n 発売された 。 " ) ,[" ", "\t", "アップル", "ストア", "で", "iPhone", "8", " ", "が", " ", " ", "\n ", "発売", "さ", "れ", "た", "\u3000", "。", " ", " "] ,) @require_sudachi def UpperCamelCase_ ( self : Optional[Any] ): __A = SudachiTokenizer(trim_whitespace=A ,sudachi_dict_type="core" ) self.assertListEqual( tokenizer.tokenize(" \tアップルストアでiPhone8 が \n 発売された 。 " ) ,["アップル", "ストア", "で", "iPhone", "8", "が", "発売", "さ", "れ", "た", "。"] ,) @require_jumanpp def UpperCamelCase_ ( self : Optional[Any] ): __A = self.tokenizer_class(self.vocab_file ,word_tokenizer_type="jumanpp" ) self.assertIsNotNone(A ) __A = "こんにちは、世界。\nこんばんは、世界。" __A = tokenizer.tokenize(A ) self.assertListEqual(A ,["こんにちは", "、", "世界", "。", "こん", "##ばんは", "、", "世界", "。"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(A ) ,[3, 12, 10, 14, 4, 9, 12, 10, 14] ) __A = os.path.join(self.tmpdirname ,"tokenizer.bin" ) with open(A ,"wb" ) as handle: pickle.dump(A ,A ) with open(A ,"rb" ) as handle: __A = pickle.load(A ) __A = tokenizer_new.tokenize(A ) self.assertListEqual(A ,A ) @require_jumanpp def UpperCamelCase_ ( self : Any ): __A = JumanppTokenizer() self.assertListEqual( tokenizer.tokenize(" \tアップルストアでiPhone8 が \n 発売された 。 " ) ,["アップル", "ストア", "で", "iPhone", "8", "\u3000", "が", "\u3000", "\u3000", "\u3000", "発売", "さ", "れた", "\u3000", "。"] ,) @require_jumanpp def UpperCamelCase_ ( self : Any ): __A = JumanppTokenizer(do_lower_case=A ) self.assertListEqual( tokenizer.tokenize(" \tアップルストアでiPhone8 が \n 発売された 。 " ) ,["アップル", "ストア", "で", "iphone", "8", "\u3000", "が", "\u3000", "\u3000", "\u3000", "発売", "さ", "れた", "\u3000", "。"] ,) @require_jumanpp def UpperCamelCase_ ( self : List[str] ): __A = JumanppTokenizer(normalize_text=A ) self.assertListEqual( tokenizer.tokenize(" \tアップルストアでiPhone8 が \n 発売された 。 " ) ,["ア", "ッ", "フ", "゚", "ル", "ストア", "で", "iPhone", "8", "\u3000", "が", "\u3000", "\u3000", "\u3000", "発売", "さ", "れた", "\u3000", "。"] ,) @require_jumanpp def UpperCamelCase_ ( self : Tuple ): __A = JumanppTokenizer(trim_whitespace=A ) self.assertListEqual( tokenizer.tokenize(" \tアップルストアでiPhone8 が \n 発売された 。 " ) ,["アップル", "ストア", "で", "iPhone", "8", "が", "発売", "さ", "れた", "。"] ,) @require_jumanpp def UpperCamelCase_ ( self : Tuple ): __A = JumanppTokenizer() self.assertListEqual( tokenizer.tokenize("ありがとうございますm(_ _)m見つけるのが大変です。" ) ,["ありがとう", "ございます", "m(_ _)m", "見つける", "の", "が", "大変です", "。"] ,) def UpperCamelCase_ ( self : List[str] ): __A = ["[UNK]", "[CLS]", "[SEP]", "こんにちは", "こん", "にちは", "ばんは", "##こん", "##にちは", "##ばんは"] __A = {} for i, token in enumerate(A ): __A = i __A = WordpieceTokenizer(vocab=A ,unk_token="[UNK]" ) self.assertListEqual(tokenizer.tokenize("" ) ,[] ) self.assertListEqual(tokenizer.tokenize("こんにちは" ) ,["こんにちは"] ) self.assertListEqual(tokenizer.tokenize("こんばんは" ) ,["こん", "##ばんは"] ) self.assertListEqual(tokenizer.tokenize("こんばんは こんばんにちは こんにちは" ) ,["こん", "##ばんは", "[UNK]", "こんにちは"] ) def UpperCamelCase_ ( self : Union[str, Any] ): __A = BertJapaneseTokenizer.from_pretrained("nlp-waseda/roberta-base-japanese-with-auto-jumanpp" ) __A = tokenizer.subword_tokenizer __A = subword_tokenizer.tokenize("国境 の 長い トンネル を 抜ける と 雪国 であった 。" ) self.assertListEqual(A ,["▁国境", "▁の", "▁長い", "▁トンネル", "▁を", "▁抜ける", "▁と", "▁雪", "国", "▁であった", "▁。"] ) __A = subword_tokenizer.tokenize("こんばんは こんばん にち は こんにちは" ) self.assertListEqual(A ,["▁こん", "ばん", "は", "▁こん", "ばん", "▁に", "ち", "▁は", "▁こんにちは"] ) def UpperCamelCase_ ( self : Optional[Any] ): __A = self.tokenizer_class.from_pretrained("cl-tohoku/bert-base-japanese" ) __A = tokenizer.encode("ありがとう。" ,add_special_tokens=A ) __A = tokenizer.encode("どういたしまして。" ,add_special_tokens=A ) __A = tokenizer.build_inputs_with_special_tokens(A ) __A = tokenizer.build_inputs_with_special_tokens(A ,A ) # 2 is for "[CLS]", 3 is for "[SEP]" assert encoded_sentence == [2] + text + [3] assert encoded_pair == [2] + text + [3] + text_a + [3] @custom_tokenizers class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = BertJapaneseTokenizer snake_case_ = False def UpperCamelCase_ ( self : List[Any] ): super().setUp() __A = ["[UNK]", "[CLS]", "[SEP]", "こ", "ん", "に", "ち", "は", "ば", "世", "界", "、", "。"] __A = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file ,"w" ,encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) def UpperCamelCase_ ( self : int ,**A : str ): return BertJapaneseTokenizer.from_pretrained(self.tmpdirname ,subword_tokenizer_type="character" ,**A ) def UpperCamelCase_ ( self : Optional[int] ,A : Union[str, Any] ): __A = "こんにちは、世界。 \nこんばんは、世界。" __A = "こ ん に ち は 、 世 界 。 こ ん ば ん は 、 世 界 。" return input_text, output_text def UpperCamelCase_ ( self : Optional[Any] ): pass # TODO add if relevant def UpperCamelCase_ ( self : str ): pass # TODO add if relevant def UpperCamelCase_ ( self : List[str] ): pass # TODO add if relevant def UpperCamelCase_ ( self : Any ): __A = self.tokenizer_class(self.vocab_file ,subword_tokenizer_type="character" ) __A = tokenizer.tokenize("こんにちは、世界。 \nこんばんは、世界。" ) self.assertListEqual( A ,["こ", "ん", "に", "ち", "は", "、", "世", "界", "。", "こ", "ん", "ば", "ん", "は", "、", "世", "界", "。"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(A ) ,[3, 4, 5, 6, 7, 11, 9, 10, 12, 3, 4, 8, 4, 7, 11, 9, 10, 12] ) def UpperCamelCase_ ( self : Union[str, Any] ): __A = ["[UNK]", "[CLS]", "[SEP]", "こ", "ん", "に", "ち", "は", "ば", "世", "界", "、", "。"] __A = {} for i, token in enumerate(A ): __A = i __A = CharacterTokenizer(vocab=A ,unk_token="[UNK]" ) self.assertListEqual(tokenizer.tokenize("" ) ,[] ) self.assertListEqual(tokenizer.tokenize("こんにちは" ) ,["こ", "ん", "に", "ち", "は"] ) self.assertListEqual(tokenizer.tokenize("こんにちほ" ) ,["こ", "ん", "に", "ち", "[UNK]"] ) def UpperCamelCase_ ( self : str ): __A = self.tokenizer_class.from_pretrained("cl-tohoku/bert-base-japanese-char" ) __A = tokenizer.encode("ありがとう。" ,add_special_tokens=A ) __A = tokenizer.encode("どういたしまして。" ,add_special_tokens=A ) __A = tokenizer.build_inputs_with_special_tokens(A ) __A = tokenizer.build_inputs_with_special_tokens(A ,A ) # 2 is for "[CLS]", 3 is for "[SEP]" assert encoded_sentence == [2] + text + [3] assert encoded_pair == [2] + text + [3] + text_a + [3] @custom_tokenizers class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase_ ( self : Union[str, Any] ): __A = "cl-tohoku/bert-base-japanese" __A = AutoTokenizer.from_pretrained(A ) self.assertIsInstance(A ,A ) class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase_ ( self : Optional[Any] ): __A = "cl-tohoku/bert-base-japanese" with self.assertLogs("transformers" ,level="WARNING" ) as cm: BertTokenizer.from_pretrained(A ) self.assertTrue( cm.records[0].message.startswith( "The tokenizer class you load from this checkpoint is not the same type as the class this function" " is called from." ) ) __A = "bert-base-cased" with self.assertLogs("transformers" ,level="WARNING" ) as cm: BertJapaneseTokenizer.from_pretrained(A ) self.assertTrue( cm.records[0].message.startswith( "The tokenizer class you load from this checkpoint is not the same type as the class this function" " is called from." ) )
55
from __future__ import annotations import inspect import unittest import numpy as np from transformers import DeiTConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, TFDeiTModel, ) from transformers.models.deit.modeling_tf_deit import TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class UpperCAmelCase : '''simple docstring''' def __init__( self : List[Any] ,A : Union[str, Any] ,A : List[Any]=13 ,A : Optional[Any]=30 ,A : Union[str, Any]=2 ,A : Union[str, Any]=3 ,A : Any=True ,A : Dict=True ,A : str=32 ,A : Tuple=2 ,A : Optional[int]=4 ,A : Tuple=37 ,A : List[Any]="gelu" ,A : Dict=0.1 ,A : Optional[int]=0.1 ,A : List[Any]=10 ,A : Optional[Any]=0.02 ,A : Dict=3 ,A : Dict=None ,A : List[Any]=2 ,): __A = parent __A = batch_size __A = image_size __A = patch_size __A = num_channels __A = is_training __A = use_labels __A = hidden_size __A = num_hidden_layers __A = num_attention_heads __A = intermediate_size __A = hidden_act __A = hidden_dropout_prob __A = attention_probs_dropout_prob __A = type_sequence_label_size __A = initializer_range __A = scope __A = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) __A = (image_size // patch_size) ** 2 __A = num_patches + 2 def UpperCamelCase_ ( self : List[Any] ): __A = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __A = None if self.use_labels: __A = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) __A = self.get_config() return config, pixel_values, labels def UpperCamelCase_ ( self : Optional[int] ): return DeiTConfig( image_size=self.image_size ,patch_size=self.patch_size ,num_channels=self.num_channels ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,hidden_act=self.hidden_act ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,is_decoder=A ,initializer_range=self.initializer_range ,encoder_stride=self.encoder_stride ,) def UpperCamelCase_ ( self : List[str] ,A : List[Any] ,A : Optional[int] ,A : Union[str, Any] ): __A = TFDeiTModel(config=A ) __A = model(A ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase_ ( self : List[Any] ,A : List[Any] ,A : Optional[Any] ,A : Dict ): __A = TFDeiTForMaskedImageModeling(config=A ) __A = model(A ) self.parent.assertEqual( result.reconstruction.shape ,(self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images __A = 1 __A = TFDeiTForMaskedImageModeling(A ) __A = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __A = model(A ) self.parent.assertEqual(result.reconstruction.shape ,(self.batch_size, 1, self.image_size, self.image_size) ) def UpperCamelCase_ ( self : Optional[Any] ,A : Union[str, Any] ,A : Dict ,A : Union[str, Any] ): __A = self.type_sequence_label_size __A = TFDeiTForImageClassification(A ) __A = model(A ,labels=A ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) # test greyscale images __A = 1 __A = TFDeiTForImageClassification(A ) __A = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __A = model(A ,labels=A ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) def UpperCamelCase_ ( self : str ): __A = self.prepare_config_and_inputs() __A , __A , __A = config_and_inputs __A = {"pixel_values": pixel_values} return config, inputs_dict @require_tf class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = ( ( TFDeiTModel, TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, ) if is_tf_available() else () ) snake_case_ = ( { "feature-extraction": TFDeiTModel, "image-classification": (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher), } if is_tf_available() else {} ) snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = False def UpperCamelCase_ ( self : str ): __A = TFDeiTModelTester(self ) __A = ConfigTester(self ,config_class=A ,has_text_modality=A ,hidden_size=37 ) def UpperCamelCase_ ( self : Any ): self.config_tester.run_common_tests() @unittest.skip(reason="DeiT does not use inputs_embeds" ) def UpperCamelCase_ ( self : Union[str, Any] ): pass def UpperCamelCase_ ( self : List[Any] ): __A , __A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __A = model_class(A ) self.assertIsInstance(model.get_input_embeddings() ,(tf.keras.layers.Layer) ) __A = model.get_output_embeddings() self.assertTrue(x is None or isinstance(A ,tf.keras.layers.Dense ) ) def UpperCamelCase_ ( self : Union[str, Any] ): __A , __A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __A = model_class(A ) __A = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __A = [*signature.parameters.keys()] __A = ["pixel_values"] self.assertListEqual(arg_names[:1] ,A ) def UpperCamelCase_ ( self : Union[str, Any] ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A ) def UpperCamelCase_ ( self : Union[str, Any] ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*A ) def UpperCamelCase_ ( self : Optional[Any] ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*A ) def UpperCamelCase_ ( self : Optional[int] ,A : Union[str, Any] ,A : List[str] ,A : Optional[Any]=False ): __A = super()._prepare_for_class(A ,A ,return_labels=A ) if return_labels: if "labels" in inputs_dict and "labels" not in inspect.signature(model_class.call ).parameters: del inputs_dict["labels"] return inputs_dict @slow def UpperCamelCase_ ( self : Any ): for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __A = TFDeiTModel.from_pretrained(A ) self.assertIsNotNone(A ) def UpperCAmelCase ( ) -> str: """simple docstring""" __A = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_tf @require_vision class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def UpperCamelCase_ ( self : int ): return ( DeiTImageProcessor.from_pretrained("facebook/deit-base-distilled-patch16-224" ) if is_vision_available() else None ) @slow def UpperCamelCase_ ( self : Optional[int] ): __A = TFDeiTForImageClassificationWithTeacher.from_pretrained("facebook/deit-base-distilled-patch16-224" ) __A = self.default_image_processor __A = prepare_img() __A = image_processor(images=A ,return_tensors="tf" ) # forward pass __A = model(**A ) # verify the logits __A = tf.TensorShape((1, 10_00) ) self.assertEqual(outputs.logits.shape ,A ) __A = tf.constant([-1.02_66, 0.19_12, -1.28_61] ) self.assertTrue(np.allclose(outputs.logits[0, :3] ,A ,atol=1E-4 ) )
55
1
import subprocess import sys from transformers import BertConfig, BertModel, BertTokenizer, pipeline from transformers.testing_utils import TestCasePlus, require_torch class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' @require_torch def UpperCamelCase_ ( self : Optional[int] ): # this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before # `transformers` is loaded, and it's too late for inside pytest - so we are changing it # while running an external program # python one-liner segments # this must be loaded before socket.socket is monkey-patched __A = "\nfrom transformers import BertConfig, BertModel, BertTokenizer, pipeline\n " __A = "\nmname = \"hf-internal-testing/tiny-random-bert\"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretrained(mname)\npipe = pipeline(task=\"fill-mask\", model=mname)\nprint(\"success\")\n " __A = "\nimport socket\ndef offline_socket(*args, **kwargs): raise RuntimeError(\"Offline mode is enabled, we shouldn't access internet\")\nsocket.socket = offline_socket\n " # Force fetching the files so that we can use the cache __A = "hf-internal-testing/tiny-random-bert" BertConfig.from_pretrained(A ) BertModel.from_pretrained(A ) BertTokenizer.from_pretrained(A ) pipeline(task="fill-mask" ,model=A ) # baseline - just load from_pretrained with normal network __A = [sys.executable, "-c", "\n".join([load, run, mock] )] # should succeed __A = self.get_env() # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files __A = "1" __A = subprocess.run(A ,env=A ,check=A ,capture_output=A ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn("success" ,result.stdout.decode() ) @require_torch def UpperCamelCase_ ( self : Union[str, Any] ): # python one-liner segments # this must be loaded before socket.socket is monkey-patched __A = "\nfrom transformers import BertConfig, BertModel, BertTokenizer, pipeline\n " __A = "\nmname = \"hf-internal-testing/tiny-random-bert\"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretrained(mname)\npipe = pipeline(task=\"fill-mask\", model=mname)\nprint(\"success\")\n " __A = "\nimport socket\ndef offline_socket(*args, **kwargs): raise socket.error(\"Faking flaky internet\")\nsocket.socket = offline_socket\n " # Force fetching the files so that we can use the cache __A = "hf-internal-testing/tiny-random-bert" BertConfig.from_pretrained(A ) BertModel.from_pretrained(A ) BertTokenizer.from_pretrained(A ) pipeline(task="fill-mask" ,model=A ) # baseline - just load from_pretrained with normal network __A = [sys.executable, "-c", "\n".join([load, run, mock] )] # should succeed __A = self.get_env() __A = subprocess.run(A ,env=A ,check=A ,capture_output=A ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn("success" ,result.stdout.decode() ) @require_torch def UpperCamelCase_ ( self : Optional[int] ): # this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before # `transformers` is loaded, and it's too late for inside pytest - so we are changing it # while running an external program # python one-liner segments # this must be loaded before socket.socket is monkey-patched __A = "\nfrom transformers import BertConfig, BertModel, BertTokenizer\n " __A = "\nmname = \"hf-internal-testing/tiny-random-bert-sharded\"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nprint(\"success\")\n " __A = "\nimport socket\ndef offline_socket(*args, **kwargs): raise ValueError(\"Offline mode is enabled\")\nsocket.socket = offline_socket\n " # baseline - just load from_pretrained with normal network __A = [sys.executable, "-c", "\n".join([load, run] )] # should succeed __A = self.get_env() __A = subprocess.run(A ,env=A ,check=A ,capture_output=A ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn("success" ,result.stdout.decode() ) # next emulate no network __A = [sys.executable, "-c", "\n".join([load, mock, run] )] # Doesn't fail anymore since the model is in the cache due to other tests, so commenting this. # env["TRANSFORMERS_OFFLINE"] = "0" # result = subprocess.run(cmd, env=env, check=False, capture_output=True) # self.assertEqual(result.returncode, 1, result.stderr) # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files __A = "1" __A = subprocess.run(A ,env=A ,check=A ,capture_output=A ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn("success" ,result.stdout.decode() ) @require_torch def UpperCamelCase_ ( self : List[str] ): __A = "\nfrom transformers import pipeline\n " __A = "\nmname = \"hf-internal-testing/tiny-random-bert\"\npipe = pipeline(model=mname)\n " __A = "\nimport socket\ndef offline_socket(*args, **kwargs): raise socket.error(\"Offline mode is enabled\")\nsocket.socket = offline_socket\n " __A = self.get_env() __A = "1" __A = [sys.executable, "-c", "\n".join([load, mock, run] )] __A = subprocess.run(A ,env=A ,check=A ,capture_output=A ) self.assertEqual(result.returncode ,1 ,result.stderr ) self.assertIn( "You cannot infer task automatically within `pipeline` when using offline mode" ,result.stderr.decode().replace("\n" ,"" ) ,) @require_torch def UpperCamelCase_ ( self : Union[str, Any] ): __A = "\nfrom transformers import AutoModel\n " __A = "\nmname = \"hf-internal-testing/test_dynamic_model\"\nAutoModel.from_pretrained(mname, trust_remote_code=True)\nprint(\"success\")\n " # baseline - just load from_pretrained with normal network __A = [sys.executable, "-c", "\n".join([load, run] )] # should succeed __A = self.get_env() __A = subprocess.run(A ,env=A ,check=A ,capture_output=A ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn("success" ,result.stdout.decode() ) # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files __A = "1" __A = subprocess.run(A ,env=A ,check=A ,capture_output=A ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn("success" ,result.stdout.decode() )
55
SCREAMING_SNAKE_CASE :List[Any] = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] SCREAMING_SNAKE_CASE :Union[str, Any] = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] SCREAMING_SNAKE_CASE :int = { 0: 'Sunday', 1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday', 5: 'Friday', 6: 'Saturday', } def UpperCAmelCase ( a_ , a_ , a_ ) -> str: """simple docstring""" assert len(str(a_ ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 1_2, "month should be between 1 to 12" assert 1 <= day <= 3_1, "day should be between 1 to 31" # Doomsday algorithm: __A = year // 1_0_0 __A = (5 * (century % 4) + 2) % 7 __A = year % 1_0_0 __A = centurian % 1_2 __A = ( (centurian // 1_2) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 __A = ( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 4_0_0) == 0) else DOOMSDAY_LEAP[month - 1] ) __A = (dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
55
1
import string def UpperCAmelCase ( a_ ) -> None: """simple docstring""" for key in range(len(string.ascii_uppercase ) ): __A = "" for symbol in message: if symbol in string.ascii_uppercase: __A = string.ascii_uppercase.find(a_ ) __A = num - key if num < 0: __A = num + len(string.ascii_uppercase ) __A = translated + string.ascii_uppercase[num] else: __A = translated + symbol print(F'''Decryption using Key #{key}: {translated}''' ) def UpperCAmelCase ( ) -> None: """simple docstring""" __A = input("Encrypted message: " ) __A = message.upper() decrypt(a_ ) if __name__ == "__main__": import doctest doctest.testmod() main()
55
from json import JSONDecodeError # Workaround for requests.exceptions.JSONDecodeError import requests def UpperCAmelCase ( a_ = "isbn/0140328726" ) -> dict: """simple docstring""" __A = olid.strip().strip("/" ) # Remove leading/trailing whitespace & slashes if new_olid.count("/" ) != 1: __A = F'''{olid} is not a valid Open Library olid''' raise ValueError(a_ ) return requests.get(F'''https://openlibrary.org/{new_olid}.json''' ).json() def UpperCAmelCase ( a_ ) -> dict: """simple docstring""" __A = { "title": "Title", "publish_date": "Publish date", "authors": "Authors", "number_of_pages": "Number of pages:", "first_sentence": "First sentence", "isbn_10": "ISBN (10)", "isbn_13": "ISBN (13)", } __A = {better_key: ol_book_data[key] for key, better_key in desired_keys.items()} __A = [ get_openlibrary_data(author["key"] )["name"] for author in data["Authors"] ] __A = data["First sentence"]["value"] for key, value in data.items(): if isinstance(a_ , a_ ): __A = ", ".join(a_ ) return data if __name__ == "__main__": import doctest doctest.testmod() while True: SCREAMING_SNAKE_CASE :int = input('\nEnter the ISBN code to search (or \'quit\' to stop): ').strip() if isbn.lower() in ("", "q", "quit", "exit", "stop"): break if len(isbn) not in (10, 13) or not isbn.isdigit(): print(f'''Sorry, {isbn} is not a valid ISBN. Please, input a valid ISBN.''') continue print(f'''\nSearching Open Library for ISBN: {isbn}...\n''') try: SCREAMING_SNAKE_CASE :Any = summarize_book(get_openlibrary_data(f'''isbn/{isbn}''')) print('\n'.join(f'''{key}: {value}''' for key, value in book_summary.items())) except JSONDecodeError: # Workaround for requests.exceptions.RequestException: print(f'''Sorry, there are no results for ISBN: {isbn}.''')
55
1
import unittest from accelerate import debug_launcher from accelerate.test_utils import require_cpu, test_ops, test_script @require_cpu class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase_ ( self : Optional[Any] ): debug_launcher(test_script.main ) def UpperCamelCase_ ( self : List[Any] ): debug_launcher(test_ops.main )
55
import requests SCREAMING_SNAKE_CASE :List[str] = 'YOUR API KEY' def UpperCAmelCase ( a_ , a_ = giphy_api_key ) -> list: """simple docstring""" __A = "+".join(query.split() ) __A = F'''https://api.giphy.com/v1/gifs/search?q={formatted_query}&api_key={api_key}''' __A = requests.get(a_ ).json()["data"] return [gif["url"] for gif in gifs] if __name__ == "__main__": print('\n'.join(get_gifs('space ship')))
55
1
import unittest from transformers import XLMConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMWithLMHeadModel, ) from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCAmelCase : '''simple docstring''' def __init__( self : Dict ,A : str ,A : Any=13 ,A : Dict=7 ,A : Union[str, Any]=True ,A : Any=True ,A : Optional[int]=True ,A : Optional[Any]=True ,A : Union[str, Any]=True ,A : Tuple=False ,A : Optional[Any]=False ,A : Union[str, Any]=False ,A : Optional[int]=2 ,A : int=99 ,A : List[str]=0 ,A : Dict=32 ,A : int=5 ,A : Dict=4 ,A : List[Any]=0.1 ,A : Union[str, Any]=0.1 ,A : Any=5_12 ,A : str=2 ,A : Tuple=0.02 ,A : List[Any]=2 ,A : int=4 ,A : Dict="last" ,A : Optional[Any]=True ,A : Optional[Any]=None ,A : Tuple=0 ,): __A = parent __A = batch_size __A = seq_length __A = is_training __A = use_input_lengths __A = use_token_type_ids __A = use_labels __A = gelu_activation __A = sinusoidal_embeddings __A = causal __A = asm __A = n_langs __A = vocab_size __A = n_special __A = hidden_size __A = num_hidden_layers __A = num_attention_heads __A = hidden_dropout_prob __A = attention_probs_dropout_prob __A = max_position_embeddings __A = type_sequence_label_size __A = initializer_range __A = num_labels __A = num_choices __A = summary_type __A = use_proj __A = scope __A = bos_token_id def UpperCamelCase_ ( self : Optional[int] ): __A = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) __A = random_attention_mask([self.batch_size, self.seq_length] ) __A = None if self.use_input_lengths: __A = ( ids_tensor([self.batch_size] ,vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length __A = None if self.use_token_type_ids: __A = ids_tensor([self.batch_size, self.seq_length] ,self.n_langs ) __A = None __A = None __A = None if self.use_labels: __A = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) __A = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) __A = ids_tensor([self.batch_size] ,2 ).float() __A = ids_tensor([self.batch_size] ,self.num_choices ) __A = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def UpperCamelCase_ ( self : Union[str, Any] ): return XLMConfig( vocab_size=self.vocab_size ,n_special=self.n_special ,emb_dim=self.hidden_size ,n_layers=self.num_hidden_layers ,n_heads=self.num_attention_heads ,dropout=self.hidden_dropout_prob ,attention_dropout=self.attention_probs_dropout_prob ,gelu_activation=self.gelu_activation ,sinusoidal_embeddings=self.sinusoidal_embeddings ,asm=self.asm ,causal=self.causal ,n_langs=self.n_langs ,max_position_embeddings=self.max_position_embeddings ,initializer_range=self.initializer_range ,summary_type=self.summary_type ,use_proj=self.use_proj ,num_labels=self.num_labels ,bos_token_id=self.bos_token_id ,) def UpperCamelCase_ ( self : str ,A : Union[str, Any] ,A : Any ,A : int ,A : Optional[int] ,A : List[str] ,A : str ,A : List[str] ,A : int ,A : Any ,): __A = XLMModel(config=A ) model.to(A ) model.eval() __A = model(A ,lengths=A ,langs=A ) __A = model(A ,langs=A ) __A = model(A ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase_ ( self : Any ,A : Dict ,A : int ,A : Optional[int] ,A : Optional[Any] ,A : str ,A : List[str] ,A : int ,A : Union[str, Any] ,A : Tuple ,): __A = XLMWithLMHeadModel(A ) model.to(A ) model.eval() __A = model(A ,token_type_ids=A ,labels=A ) self.parent.assertEqual(result.loss.shape ,() ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase_ ( self : List[Any] ,A : Tuple ,A : Union[str, Any] ,A : Optional[int] ,A : Dict ,A : List[Any] ,A : int ,A : int ,A : str ,A : Optional[int] ,): __A = XLMForQuestionAnsweringSimple(A ) model.to(A ) model.eval() __A = model(A ) __A = model(A ,start_positions=A ,end_positions=A ) __A = outputs self.parent.assertEqual(result.start_logits.shape ,(self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape ,(self.batch_size, self.seq_length) ) def UpperCamelCase_ ( self : int ,A : Optional[Any] ,A : Union[str, Any] ,A : Dict ,A : Optional[Any] ,A : Dict ,A : Optional[int] ,A : List[str] ,A : List[str] ,A : Tuple ,): __A = XLMForQuestionAnswering(A ) model.to(A ) model.eval() __A = model(A ) __A = model( A ,start_positions=A ,end_positions=A ,cls_index=A ,is_impossible=A ,p_mask=A ,) __A = model( A ,start_positions=A ,end_positions=A ,cls_index=A ,is_impossible=A ,) ((__A) , ) = result_with_labels.to_tuple() __A = model(A ,start_positions=A ,end_positions=A ) ((__A) , ) = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape ,() ) self.parent.assertEqual(result.start_top_log_probs.shape ,(self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape ,(self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape ,(self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape ,(self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape ,(self.batch_size,) ) def UpperCamelCase_ ( self : Optional[Any] ,A : Tuple ,A : Optional[int] ,A : Optional[Any] ,A : Any ,A : List[str] ,A : Optional[Any] ,A : List[Any] ,A : List[str] ,A : str ,): __A = XLMForSequenceClassification(A ) model.to(A ) model.eval() __A = model(A ) __A = model(A ,labels=A ) self.parent.assertEqual(result.loss.shape ,() ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) def UpperCamelCase_ ( self : Tuple ,A : List[Any] ,A : Tuple ,A : Union[str, Any] ,A : Optional[int] ,A : List[Any] ,A : int ,A : Optional[int] ,A : Optional[int] ,A : Any ,): __A = self.num_labels __A = XLMForTokenClassification(A ) model.to(A ) model.eval() __A = model(A ,attention_mask=A ,labels=A ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) ) def UpperCamelCase_ ( self : List[Any] ,A : int ,A : str ,A : List[str] ,A : List[str] ,A : List[Any] ,A : Union[str, Any] ,A : Any ,A : str ,A : Any ,): __A = self.num_choices __A = XLMForMultipleChoice(config=A ) model.to(A ) model.eval() __A = input_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() __A = token_type_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() __A = input_mask.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() __A = model( A ,attention_mask=A ,token_type_ids=A ,labels=A ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_choices) ) def UpperCamelCase_ ( self : Any ): __A = self.prepare_config_and_inputs() ( ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ) = config_and_inputs __A = {"input_ids": input_ids, "token_type_ids": token_type_ids, "lengths": input_lengths} return config, inputs_dict @require_torch class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = ( ( XLMModel, XLMWithLMHeadModel, XLMForQuestionAnswering, XLMForSequenceClassification, XLMForQuestionAnsweringSimple, XLMForTokenClassification, XLMForMultipleChoice, ) if is_torch_available() else () ) snake_case_ = ( (XLMWithLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable snake_case_ = ( { "feature-extraction": XLMModel, "fill-mask": XLMWithLMHeadModel, "question-answering": XLMForQuestionAnsweringSimple, "text-classification": XLMForSequenceClassification, "text-generation": XLMWithLMHeadModel, "token-classification": XLMForTokenClassification, "zero-shot": XLMForSequenceClassification, } if is_torch_available() else {} ) def UpperCamelCase_ ( self : Any ,A : List[Any] ,A : Optional[Any] ,A : Dict ,A : List[str] ,A : Dict ): 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 UpperCamelCase_ ( self : str ,A : Union[str, Any] ,A : str ,A : str=False ): __A = super()._prepare_for_class(A ,A ,return_labels=A ) if return_labels: if model_class.__name__ == "XLMForQuestionAnswering": __A = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=A ) __A = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=A ) return inputs_dict def UpperCamelCase_ ( self : List[Any] ): __A = XLMModelTester(self ) __A = ConfigTester(self ,config_class=A ,emb_dim=37 ) def UpperCamelCase_ ( self : List[str] ): self.config_tester.run_common_tests() def UpperCamelCase_ ( self : List[str] ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_model(*A ) def UpperCamelCase_ ( self : List[str] ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_lm_head(*A ) def UpperCamelCase_ ( self : Optional[int] ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_simple_qa(*A ) def UpperCamelCase_ ( self : str ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_qa(*A ) def UpperCamelCase_ ( self : Any ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_sequence_classif(*A ) def UpperCamelCase_ ( self : Union[str, Any] ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_token_classif(*A ) def UpperCamelCase_ ( self : Dict ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_for_multiple_choice(*A ) def UpperCamelCase_ ( self : int ,A : Dict ,A : List[Any] ,A : List[str] ,A : List[str] ,A : Dict ,A : Union[str, Any]=False ,A : Union[str, Any]=1 ): self.assertIsInstance(A ,A ) self.assertListEqual( [isinstance(A ,A ) for iter_attentions in attentions] ,[True] * len(A ) ) self.assertEqual(len(A ) ,(max_length - min_length) * num_beam_groups ) for idx, iter_attentions in enumerate(A ): # adds PAD dummy token __A = min_length + idx + 1 __A = min_length + idx + 1 __A = ( batch_size * num_beam_groups, config.num_attention_heads, tgt_len, src_len, ) # check attn size self.assertListEqual( [layer_attention.shape for layer_attention in iter_attentions] ,[expected_shape] * len(A ) ) def UpperCamelCase_ ( self : int ,A : int ,A : Optional[Any] ,A : Dict ,A : List[str] ,A : int ,A : Optional[Any]=False ,A : Optional[int]=1 ): self.assertIsInstance(A ,A ) self.assertListEqual( [isinstance(A ,A ) for iter_hidden_states in hidden_states] ,[True] * len(A ) ,) self.assertEqual(len(A ) ,(max_length - min_length) * num_beam_groups ) for idx, iter_hidden_states in enumerate(A ): # adds PAD dummy token __A = min_length + idx + 1 __A = (batch_size * num_beam_groups, seq_len, config.hidden_size) # check hidden size self.assertListEqual( [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states] ,[expected_shape] * len(A ) ,) pass @slow def UpperCamelCase_ ( self : int ): for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __A = XLMModel.from_pretrained(A ) self.assertIsNotNone(A ) @require_torch class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @slow def UpperCamelCase_ ( self : Optional[Any] ): __A = XLMWithLMHeadModel.from_pretrained("xlm-mlm-en-2048" ) model.to(A ) __A = torch.tensor([[14, 4_47]] ,dtype=torch.long ,device=A ) # the president __A = [ 14, 4_47, 14, 4_47, 14, 4_47, 14, 4_47, 14, 4_47, 14, 4_47, 14, 4_47, 14, 4_47, 14, 4_47, 14, 4_47, ] # the president the president the president the president the president the president the president the president the president the president # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference __A = model.generate(A ,do_sample=A ) self.assertListEqual(output_ids[0].cpu().numpy().tolist() ,A )
55
import itertools import math def UpperCAmelCase ( a_ ) -> bool: """simple docstring""" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(a_ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def UpperCAmelCase ( ) -> Optional[Any]: """simple docstring""" __A = 2 while True: if is_prime(a_ ): yield num num += 1 def UpperCAmelCase ( a_ = 1_0_0_0_1 ) -> int: """simple docstring""" return next(itertools.islice(prime_generator() , nth - 1 , a_ ) ) if __name__ == "__main__": print(f'''{solution() = }''')
55
1
from math import isqrt def UpperCAmelCase ( a_ ) -> list[int]: """simple docstring""" __A = [True] * max_number for i in range(2 , isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2 , a_ , a_ ): __A = False return [i for i in range(2 , a_ ) if is_prime[i]] def UpperCAmelCase ( a_ = 1_0**8 ) -> int: """simple docstring""" __A = calculate_prime_numbers(max_number // 2 ) __A = 0 __A = 0 __A = len(a_ ) - 1 while left <= right: while prime_numbers[left] * prime_numbers[right] >= max_number: right -= 1 semiprimes_count += right - left + 1 left += 1 return semiprimes_count if __name__ == "__main__": print(f'''{solution() = }''')
55
import argparse import os import numpy as np import tensorflow as tf import torch from transformers import BertModel def UpperCAmelCase ( a_ , a_ , a_ ) -> List[str]: """simple docstring""" __A = ("dense.weight", "attention.self.query", "attention.self.key", "attention.self.value") __A = ( ("layer.", "layer_"), ("word_embeddings.weight", "word_embeddings"), ("position_embeddings.weight", "position_embeddings"), ("token_type_embeddings.weight", "token_type_embeddings"), (".", "/"), ("LayerNorm/weight", "LayerNorm/gamma"), ("LayerNorm/bias", "LayerNorm/beta"), ("weight", "kernel"), ) if not os.path.isdir(a_ ): os.makedirs(a_ ) __A = model.state_dict() def to_tf_var_name(a_ ): for patt, repl in iter(a_ ): __A = name.replace(a_ , a_ ) return F'''bert/{name}''' def create_tf_var(a_ , a_ , a_ ): __A = tf.dtypes.as_dtype(tensor.dtype ) __A = tf.get_variable(dtype=a_ , shape=tensor.shape , name=a_ , initializer=tf.zeros_initializer() ) session.run(tf.variables_initializer([tf_var] ) ) session.run(a_ ) return tf_var tf.reset_default_graph() with tf.Session() as session: for var_name in state_dict: __A = to_tf_var_name(a_ ) __A = state_dict[var_name].numpy() if any(x in var_name for x in tensors_to_transpose ): __A = torch_tensor.T __A = create_tf_var(tensor=a_ , name=a_ , session=a_ ) tf.keras.backend.set_value(a_ , a_ ) __A = session.run(a_ ) print(F'''Successfully created {tf_name}: {np.allclose(a_ , a_ )}''' ) __A = tf.train.Saver(tf.trainable_variables() ) saver.save(a_ , os.path.join(a_ , model_name.replace("-" , "_" ) + ".ckpt" ) ) def UpperCAmelCase ( a_=None ) -> List[Any]: """simple docstring""" __A = argparse.ArgumentParser() parser.add_argument("--model_name" , type=a_ , required=a_ , help="model name e.g. bert-base-uncased" ) parser.add_argument( "--cache_dir" , type=a_ , default=a_ , required=a_ , help="Directory containing pytorch model" ) parser.add_argument("--pytorch_model_path" , type=a_ , required=a_ , help="/path/to/<pytorch-model-name>.bin" ) parser.add_argument("--tf_cache_dir" , type=a_ , required=a_ , help="Directory in which to save tensorflow model" ) __A = parser.parse_args(a_ ) __A = BertModel.from_pretrained( pretrained_model_name_or_path=args.model_name , state_dict=torch.load(args.pytorch_model_path ) , cache_dir=args.cache_dir , ) convert_pytorch_checkpoint_to_tf(model=a_ , ckpt_dir=args.tf_cache_dir , model_name=args.model_name ) if __name__ == "__main__": main()
55
1
import os import warnings from typing import List, Optional from ...tokenization_utils_base import BatchEncoding from ...utils import logging from .configuration_rag import RagConfig SCREAMING_SNAKE_CASE :Optional[Any] = logging.get_logger(__name__) class UpperCAmelCase : '''simple docstring''' def __init__( self : Any ,A : str ,A : Any ): __A = question_encoder __A = generator __A = self.question_encoder def UpperCamelCase_ ( self : Dict ,A : List[Any] ): if os.path.isfile(A ): raise ValueError(f'''Provided path ({save_directory}) should be a directory, not a file''' ) os.makedirs(A ,exist_ok=A ) __A = os.path.join(A ,"question_encoder_tokenizer" ) __A = os.path.join(A ,"generator_tokenizer" ) self.question_encoder.save_pretrained(A ) self.generator.save_pretrained(A ) @classmethod def UpperCamelCase_ ( cls : Any ,A : str ,**A : Optional[Any] ): # dynamically import AutoTokenizer from ..auto.tokenization_auto import AutoTokenizer __A = kwargs.pop("config" ,A ) if config is None: __A = RagConfig.from_pretrained(A ) __A = AutoTokenizer.from_pretrained( A ,config=config.question_encoder ,subfolder="question_encoder_tokenizer" ) __A = AutoTokenizer.from_pretrained( A ,config=config.generator ,subfolder="generator_tokenizer" ) return cls(question_encoder=A ,generator=A ) def __call__( self : Tuple ,*A : List[str] ,**A : str ): return self.current_tokenizer(*A ,**A ) def UpperCamelCase_ ( self : List[str] ,*A : List[str] ,**A : List[str] ): return self.generator.batch_decode(*A ,**A ) def UpperCamelCase_ ( self : int ,*A : int ,**A : Union[str, Any] ): return self.generator.decode(*A ,**A ) def UpperCamelCase_ ( self : Dict ): __A = self.question_encoder def UpperCamelCase_ ( self : Any ): __A = self.generator def UpperCamelCase_ ( self : Optional[Any] ,A : List[str] ,A : Optional[List[str]] = None ,A : Optional[int] = None ,A : Optional[int] = None ,A : str = "longest" ,A : str = None ,A : bool = True ,**A : Tuple ,): warnings.warn( "`prepare_seq2seq_batch` is deprecated and will be removed in version 5 of 🤗 Transformers. Use the " "regular `__call__` method to prepare your inputs and the tokenizer under the `with_target_tokenizer` " "context manager to prepare your targets. See the documentation of your specific tokenizer for more " "details" ,A ,) if max_length is None: __A = self.current_tokenizer.model_max_length __A = self( A ,add_special_tokens=A ,return_tensors=A ,max_length=A ,padding=A ,truncation=A ,**A ,) if tgt_texts is None: return model_inputs # Process tgt_texts if max_target_length is None: __A = self.current_tokenizer.model_max_length __A = self( text_target=A ,add_special_tokens=A ,return_tensors=A ,padding=A ,max_length=A ,truncation=A ,**A ,) __A = labels["input_ids"] return model_inputs
55
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE :Any = { 'configuration_pegasus_x': ['PEGASUS_X_PRETRAINED_CONFIG_ARCHIVE_MAP', 'PegasusXConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE :Any = [ 'PEGASUS_X_PRETRAINED_MODEL_ARCHIVE_LIST', 'PegasusXForConditionalGeneration', 'PegasusXModel', 'PegasusXPreTrainedModel', ] if TYPE_CHECKING: from .configuration_pegasus_x import PEGASUS_X_PRETRAINED_CONFIG_ARCHIVE_MAP, PegasusXConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pegasus_x import ( PEGASUS_X_PRETRAINED_MODEL_ARCHIVE_LIST, PegasusXForConditionalGeneration, PegasusXModel, PegasusXPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE :Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
55
1
import pytest import datasets # Import fixture modules as plugins SCREAMING_SNAKE_CASE :str = ['tests.fixtures.files', 'tests.fixtures.hub', 'tests.fixtures.fsspec'] def UpperCAmelCase ( a_ , a_ ) -> Optional[Any]: """simple docstring""" for item in items: if any(marker in item.keywords for marker in ["integration", "unit"] ): continue item.add_marker(pytest.mark.unit ) def UpperCAmelCase ( a_ ) -> str: """simple docstring""" config.addinivalue_line("markers" , "torchaudio_latest: mark test to run with torchaudio>=0.12" ) @pytest.fixture(autouse=a_ ) def UpperCAmelCase ( a_ , a_ ) -> Optional[int]: """simple docstring""" __A = tmp_path_factory.getbasetemp() / "cache" __A = test_hf_cache_home / "datasets" __A = test_hf_cache_home / "metrics" __A = test_hf_cache_home / "modules" monkeypatch.setattr("datasets.config.HF_DATASETS_CACHE" , str(a_ ) ) monkeypatch.setattr("datasets.config.HF_METRICS_CACHE" , str(a_ ) ) monkeypatch.setattr("datasets.config.HF_MODULES_CACHE" , str(a_ ) ) __A = test_hf_datasets_cache / "downloads" monkeypatch.setattr("datasets.config.DOWNLOADED_DATASETS_PATH" , str(a_ ) ) __A = test_hf_datasets_cache / "downloads" / "extracted" monkeypatch.setattr("datasets.config.EXTRACTED_DATASETS_PATH" , str(a_ ) ) @pytest.fixture(autouse=a_ , scope="session" ) def UpperCAmelCase ( ) -> Union[str, Any]: """simple docstring""" datasets.disable_progress_bar() @pytest.fixture(autouse=a_ ) def UpperCAmelCase ( a_ ) -> Union[str, Any]: """simple docstring""" monkeypatch.setattr("datasets.config.HF_UPDATE_DOWNLOAD_COUNTS" , a_ ) @pytest.fixture def UpperCAmelCase ( a_ ) -> str: """simple docstring""" monkeypatch.setattr("sqlalchemy.util.deprecations.SILENCE_UBER_WARNING" , a_ )
55
from __future__ import annotations from collections.abc import Generator import requests from bsa import BeautifulSoup SCREAMING_SNAKE_CASE :int = 'https://www.indeed.co.in/jobs?q=mobile+app+development&l=' def UpperCAmelCase ( a_ = "mumbai" ) -> Generator[tuple[str, str], None, None]: """simple docstring""" __A = BeautifulSoup(requests.get(url + location ).content , "html.parser" ) # This attribute finds out all the specifics listed in a job for job in soup.find_all("div" , attrs={"data-tn-component": "organicJob"} ): __A = job.find("a" , attrs={"data-tn-element": "jobTitle"} ).text.strip() __A = job.find("span" , {"class": "company"} ).text.strip() yield job_title, company_name if __name__ == "__main__": for i, job in enumerate(fetch_jobs('Bangalore'), 1): print(f'''Job {i:>2} is {job[0]} at {job[1]}''')
55
1
import functools def UpperCAmelCase ( a_ , a_ ) -> int: """simple docstring""" __A = len(a_ ) __A = len(a_ ) @functools.cache def min_distance(a_ , a_ ) -> int: # if first word index is overflow - delete all from the second word if indexa >= len_worda: return len_worda - indexa # if second word index is overflow - delete all from the first word if indexa >= len_worda: return len_worda - indexa __A = int(worda[indexa] != worda[indexa] ) # current letters not identical return min( 1 + min_distance(indexa + 1 , a_ ) , 1 + min_distance(a_ , indexa + 1 ) , diff + min_distance(indexa + 1 , indexa + 1 ) , ) return min_distance(0 , 0 ) if __name__ == "__main__": import doctest doctest.testmod()
55
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, BlipaProcessor, BlipImageProcessor, GPTaTokenizer, PreTrainedTokenizerFast @require_vision class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase_ ( self : List[str] ): __A = tempfile.mkdtemp() __A = BlipImageProcessor() __A = GPTaTokenizer.from_pretrained("hf-internal-testing/tiny-random-GPT2Model" ) __A = BlipaProcessor(A ,A ) processor.save_pretrained(self.tmpdirname ) def UpperCamelCase_ ( self : Dict ,**A : int ): return AutoProcessor.from_pretrained(self.tmpdirname ,**A ).tokenizer def UpperCamelCase_ ( self : Dict ,**A : Optional[int] ): return AutoProcessor.from_pretrained(self.tmpdirname ,**A ).image_processor def UpperCamelCase_ ( self : Dict ): shutil.rmtree(self.tmpdirname ) def UpperCamelCase_ ( self : Optional[int] ): __A = [np.random.randint(2_55 ,size=(3, 30, 4_00) ,dtype=np.uinta )] __A = [Image.fromarray(np.moveaxis(A ,0 ,-1 ) ) for x in image_inputs] return image_inputs def UpperCamelCase_ ( self : Any ): __A = BlipaProcessor(tokenizer=self.get_tokenizer() ,image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __A = self.get_tokenizer(bos_token="(BOS)" ,eos_token="(EOS)" ) __A = self.get_image_processor(do_normalize=A ,padding_value=1.0 ) __A = BlipaProcessor.from_pretrained( self.tmpdirname ,bos_token="(BOS)" ,eos_token="(EOS)" ,do_normalize=A ,padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() ,tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer ,A ) self.assertEqual(processor.image_processor.to_json_string() ,image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor ,A ) def UpperCamelCase_ ( self : List[Any] ): __A = self.get_image_processor() __A = self.get_tokenizer() __A = BlipaProcessor(tokenizer=A ,image_processor=A ) __A = self.prepare_image_inputs() __A = image_processor(A ,return_tensors="np" ) __A = processor(images=A ,return_tensors="np" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() ,input_processor[key].sum() ,delta=1E-2 ) def UpperCamelCase_ ( self : Tuple ): __A = self.get_image_processor() __A = self.get_tokenizer() __A = BlipaProcessor(tokenizer=A ,image_processor=A ) __A = "lower newer" __A = processor(text=A ) __A = tokenizer(A ,return_token_type_ids=A ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] ,encoded_processor[key] ) def UpperCamelCase_ ( self : int ): __A = self.get_image_processor() __A = self.get_tokenizer() __A = BlipaProcessor(tokenizer=A ,image_processor=A ) __A = "lower newer" __A = self.prepare_image_inputs() __A = processor(text=A ,images=A ) self.assertListEqual(list(inputs.keys() ) ,["pixel_values", "input_ids", "attention_mask"] ) # test if it raises when no input is passed with pytest.raises(A ): processor() def UpperCamelCase_ ( self : Optional[Any] ): __A = self.get_image_processor() __A = self.get_tokenizer() __A = BlipaProcessor(tokenizer=A ,image_processor=A ) __A = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __A = processor.batch_decode(A ) __A = tokenizer.batch_decode(A ) self.assertListEqual(A ,A ) def UpperCamelCase_ ( self : Optional[Any] ): __A = self.get_image_processor() __A = self.get_tokenizer() __A = BlipaProcessor(tokenizer=A ,image_processor=A ) __A = "lower newer" __A = self.prepare_image_inputs() __A = processor(text=A ,images=A ) # For now the processor supports only ['pixel_values', 'input_ids', 'attention_mask'] self.assertListEqual(list(inputs.keys() ) ,["pixel_values", "input_ids", "attention_mask"] )
55
1
from __future__ import annotations import random import unittest from transformers import TransfoXLConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST, TFTransfoXLForSequenceClassification, TFTransfoXLLMHeadModel, TFTransfoXLModel, ) class UpperCAmelCase : '''simple docstring''' def __init__( self : Dict ,A : Optional[Any] ,): __A = parent __A = 13 __A = 7 __A = 30 __A = self.seq_length + self.mem_len __A = 15 __A = True __A = True __A = 99 __A = [10, 50, 80] __A = 32 __A = 32 __A = 4 __A = 8 __A = 1_28 __A = 2 __A = 2 __A = None __A = 1 __A = 0 __A = 3 __A = self.vocab_size - 1 __A = 0.01 def UpperCamelCase_ ( self : Union[str, Any] ): __A = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) __A = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) __A = None if self.use_labels: __A = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) __A = TransfoXLConfig( vocab_size=self.vocab_size ,mem_len=self.mem_len ,clamp_len=self.clamp_len ,cutoffs=self.cutoffs ,d_model=self.hidden_size ,d_embed=self.d_embed ,n_head=self.num_attention_heads ,d_head=self.d_head ,d_inner=self.d_inner ,div_val=self.div_val ,n_layer=self.num_hidden_layers ,eos_token_id=self.eos_token_id ,pad_token_id=self.vocab_size - 1 ,init_range=self.init_range ,num_labels=self.num_labels ,) return (config, input_ids_a, input_ids_a, lm_labels) def UpperCamelCase_ ( self : Any ): random.seed(self.seed ) tf.random.set_seed(self.seed ) def UpperCamelCase_ ( self : str ,A : List[Any] ,A : str ,A : Optional[Any] ,A : Union[str, Any] ): __A = TFTransfoXLModel(A ) __A , __A = model(A ).to_tuple() __A = {"input_ids": input_ids_a, "mems": mems_a} __A , __A = model(A ).to_tuple() self.parent.assertEqual(hidden_states_a.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(hidden_states_a.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertListEqual( [mem.shape for mem in mems_a] ,[(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers ,) self.parent.assertListEqual( [mem.shape for mem in mems_a] ,[(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers ,) def UpperCamelCase_ ( self : Optional[Any] ,A : Dict ,A : Any ,A : Any ,A : Optional[Any] ): __A = TFTransfoXLLMHeadModel(A ) __A , __A = model(A ).to_tuple() __A = {"input_ids": input_ids_a, "labels": lm_labels} __A , __A = model(A ).to_tuple() __A , __A = model([input_ids_a, mems_a] ).to_tuple() __A = {"input_ids": input_ids_a, "mems": mems_a, "labels": lm_labels} __A , __A = model(A ).to_tuple() self.parent.assertEqual(lm_logits_a.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertListEqual( [mem.shape for mem in mems_a] ,[(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers ,) self.parent.assertEqual(lm_logits_a.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertListEqual( [mem.shape for mem in mems_a] ,[(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers ,) def UpperCamelCase_ ( self : Optional[Any] ,A : Tuple ,A : str ,A : Union[str, Any] ,A : Optional[int] ): __A = TFTransfoXLForSequenceClassification(A ) __A = model(A ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def UpperCamelCase_ ( self : int ): __A = self.prepare_config_and_inputs() ((__A) , (__A) , (__A) , (__A)) = config_and_inputs __A = {"input_ids": input_ids_a} return config, inputs_dict @require_tf class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = ( (TFTransfoXLModel, TFTransfoXLLMHeadModel, TFTransfoXLForSequenceClassification) if is_tf_available() else () ) snake_case_ = () if is_tf_available() else () snake_case_ = ( { "feature-extraction": TFTransfoXLModel, "text-classification": TFTransfoXLForSequenceClassification, "text-generation": TFTransfoXLLMHeadModel, "zero-shot": TFTransfoXLForSequenceClassification, } if is_tf_available() else {} ) # TODO: add this test when TFTransfoXLLMHead has a linear output layer implemented snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = False def UpperCamelCase_ ( self : List[str] ,A : str ,A : Optional[Any] ,A : Any ,A : Optional[Any] ,A : List[Any] ): if pipeline_test_casse_name == "TextGenerationPipelineTests": # Get `ValueError: AttributeError: 'NoneType' object has no attribute 'new_ones'` or `AssertionError`. # `TransfoXLConfig` was never used in pipeline tests: cannot create a simple # tokenizer. return True return False def UpperCamelCase_ ( self : Optional[Any] ): __A = TFTransfoXLModelTester(self ) __A = ConfigTester(self ,config_class=A ,d_embed=37 ) def UpperCamelCase_ ( self : Any ): self.config_tester.run_common_tests() def UpperCamelCase_ ( self : Tuple ): self.model_tester.set_seed() __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_model(*A ) def UpperCamelCase_ ( self : str ): self.model_tester.set_seed() __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_lm_head(*A ) def UpperCamelCase_ ( self : int ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_for_sequence_classification(*A ) def UpperCamelCase_ ( self : Tuple ): __A , __A = self.model_tester.prepare_config_and_inputs_for_common() __A = [TFTransfoXLForSequenceClassification] for model_class in self.all_model_classes: __A = model_class(A ) assert isinstance(model.get_input_embeddings() ,tf.keras.layers.Layer ) if model_class in list_other_models_with_output_ebd: __A = model.get_output_embeddings() assert isinstance(A ,tf.keras.layers.Layer ) __A = model.get_bias() assert name is None else: __A = model.get_output_embeddings() assert x is None __A = model.get_bias() assert name is None def UpperCamelCase_ ( self : Union[str, Any] ): # TODO JP: Make TransfoXL XLA compliant pass @slow def UpperCamelCase_ ( self : List[Any] ): for model_name in TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __A = TFTransfoXLModel.from_pretrained(A ) self.assertIsNotNone(A ) @unittest.skip(reason="This model doesn't play well with fit() due to not returning a single loss." ) def UpperCamelCase_ ( self : Union[str, Any] ): pass @require_tf class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @unittest.skip("Skip test until #12651 is resolved." ) @slow def UpperCamelCase_ ( self : List[Any] ): __A = TFTransfoXLLMHeadModel.from_pretrained("transfo-xl-wt103" ) # fmt: off __A = tf.convert_to_tensor([[33,12_97,2,1,10_09,4,11_09,1_17_39,47_62,3_58,5,25,2_45,22,17_06,17,2_00_98,5,32_15,21,37,11_10,3,13,10_41,4,24,6_03,4_90,2,7_14_77,2_00_98,10_44_47,2,2_09_61,1,26_04,4,1,3_29,3,62_24,8_31,1_60_02,2,8,6_03,7_89_67,2_95_46,23,8_03,20,25,4_16,5,8,2_32,4,2_77,6,18_55,46_01,3,2_95_46,54,8,36_09,5,5_72_11,49,4,1,2_77,18,8,17_55,1_56_91,3,3_41,25,4_16,6_93,4_25_73,71,17,4_01,94,31,1_79_19,2,2_95_46,78_73,18,1,4_35,23,1_10_11,7_55,5,51_67,3,79_83,98,84,2,2_95_46,32_67,8,36_09,4,1,48_65,10_75,2,60_87,71,6,3_46,8,58_54,3,2_95_46,8_24,14_00,18_68,2,19,1_60,2,3_11,8,54_96,2,2_09_20,17,25,1_50_97,3,24,24,0]] ,dtype=tf.intaa ) # noqa: E231 # fmt: on # In 1991 , the remains of Russian Tsar Nicholas II and his family # ( except for Alexei and Maria ) are discovered . # The voice of Nicholas's young son , Tsarevich Alexei Nikolaevich , narrates the # remainder of the story . 1883 Western Siberia , # a young Grigori Rasputin is asked by his father and a group of men to perform magic . # Rasputin has a vision and denounces one of the men as a horse thief . Although his # father initially slaps him for making such an accusation , Rasputin watches as the # man is chased outside and beaten . Twenty years later , Rasputin sees a vision of # the Virgin Mary , prompting him to become a priest . Rasputin quickly becomes famous , # with people , even a bishop , begging for his blessing . <eod> </s> <eos> # fmt: off __A = [33,12_97,2,1,10_09,4,11_09,1_17_39,47_62,3_58,5,25,2_45,22,17_06,17,2_00_98,5,32_15,21,37,11_10,3,13,10_41,4,24,6_03,4_90,2,7_14_77,2_00_98,10_44_47,2,2_09_61,1,26_04,4,1,3_29,3,62_24,8_31,1_60_02,2,8,6_03,7_89_67,2_95_46,23,8_03,20,25,4_16,5,8,2_32,4,2_77,6,18_55,46_01,3,2_95_46,54,8,36_09,5,5_72_11,49,4,1,2_77,18,8,17_55,1_56_91,3,3_41,25,4_16,6_93,4_25_73,71,17,4_01,94,31,1_79_19,2,2_95_46,78_73,18,1,4_35,23,1_10_11,7_55,5,51_67,3,79_83,98,84,2,2_95_46,32_67,8,36_09,4,1,48_65,10_75,2,60_87,71,6,3_46,8,58_54,3,2_95_46,8_24,14_00,18_68,2,19,1_60,2,3_11,8,54_96,2,2_09_20,17,25,1_50_97,3,24,24,0,33,1,18_57,2,1,10_09,4,11_09,1_17_39,47_62,3_58,5,25,2_45,28,11_10,3,13,10_41,4,24,6_03,4_90,2,7_14_77,2_00_98,10_44_47,2,2_09_61,1,26_04,4,1,3_29,3,0] # noqa: E231 # fmt: on # In 1991, the remains of Russian Tsar Nicholas II and his family ( # except for Alexei and Maria ) are discovered. The voice of young son, # Tsarevich Alexei Nikolaevich, narrates the remainder of the story. # 1883 Western Siberia, a young Grigori Rasputin is asked by his father # and a group of men to perform magic. Rasputin has a vision and # denounces one of the men as a horse thief. Although his father initially # slaps him for making such an accusation, Rasputin watches as the man # is chased outside and beaten. Twenty years later, Rasputin sees a vision # of the Virgin Mary, prompting him to become a priest. # Rasputin quickly becomes famous, with people, even a bishop, begging for # his blessing. <unk> <unk> <eos> In the 1990s, the remains of Russian Tsar # Nicholas II and his family were discovered. The voice of <unk> young son, # Tsarevich Alexei Nikolaevich, narrates the remainder of the story.<eos> __A = model.generate(A ,max_length=2_00 ,do_sample=A ) self.assertListEqual(output_ids[0].numpy().tolist() ,A )
55
import logging import torch from accelerate import Accelerator from arguments import EvaluationArguments from datasets import load_dataset from torch.utils.data import IterableDataset from torch.utils.data.dataloader import DataLoader from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, set_seed class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self : int ,A : Any ,A : List[str] ,A : Union[str, Any]=10_24 ,A : int=10_24 ,A : Optional[Any]=3.6 ): __A = tokenizer __A = tokenizer.bos_token_id __A = dataset __A = seq_length __A = seq_length * chars_per_token * num_of_sequences def __iter__( self : List[Any] ): __A = iter(self.dataset ) __A = True while more_examples: __A , __A = [], 0 while True: if buffer_len >= self.input_characters: break try: buffer.append(next(A )["content"] ) buffer_len += len(buffer[-1] ) except StopIteration: __A = False break __A = tokenizer(A ,truncation=A )["input_ids"] __A = [] for tokenized_input in tokenized_inputs: all_token_ids.extend(tokenized_input + [self.concat_token_id] ) for i in range(0 ,len(A ) ,self.seq_length ): __A = all_token_ids[i : i + self.seq_length] if len(A ) == self.seq_length: yield torch.tensor(A ) def UpperCAmelCase ( a_ ) -> Optional[int]: """simple docstring""" __A = {"streaming": True} __A = load_dataset(args.dataset_name , split="train" , **a_ ) __A = ConstantLengthDataset(a_ , a_ , seq_length=args.seq_length ) __A = DataLoader(a_ , batch_size=args.batch_size ) return eval_dataloader def UpperCAmelCase ( a_ ) -> Union[str, Any]: """simple docstring""" model.eval() __A = [] for step, batch in enumerate(a_ ): with torch.no_grad(): __A = model(a_ , labels=a_ ) __A = outputs.loss.repeat(args.batch_size ) losses.append(accelerator.gather(a_ ) ) if args.max_eval_steps > 0 and step >= args.max_eval_steps: break __A = torch.mean(torch.cat(a_ ) ) try: __A = torch.exp(a_ ) except OverflowError: __A = float("inf" ) return loss.item(), perplexity.item() # Setup Accelerator SCREAMING_SNAKE_CASE :Optional[int] = Accelerator() # Parse configuration SCREAMING_SNAKE_CASE :str = HfArgumentParser(EvaluationArguments) SCREAMING_SNAKE_CASE :int = parser.parse_args() set_seed(args.seed) # Logging SCREAMING_SNAKE_CASE :Dict = logging.getLogger(__name__) logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO ) # Load model and tokenizer SCREAMING_SNAKE_CASE :List[Any] = AutoModelForCausalLM.from_pretrained(args.model_ckpt) SCREAMING_SNAKE_CASE :int = AutoTokenizer.from_pretrained(args.model_ckpt) # Load dataset and dataloader SCREAMING_SNAKE_CASE :List[str] = create_dataloader(args) # Prepare everything with our `accelerator`. SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE :List[Any] = accelerator.prepare(model, eval_dataloader) # Evaluate and save the last checkpoint logger.info('Evaluating and saving model after training') SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE :List[Any] = evaluate(args) logger.info(f'''loss/eval: {eval_loss}, perplexity: {perplexity}''')
55
1
class UpperCAmelCase : '''simple docstring''' def __init__( self : int ,A : List[Any] ): __A = val __A = None __A = None def UpperCamelCase_ ( self : List[str] ,A : Dict ): if self.val: if val < self.val: if self.left is None: __A = Node(A ) else: self.left.insert(A ) elif val > self.val: if self.right is None: __A = Node(A ) else: self.right.insert(A ) else: __A = val def UpperCAmelCase ( a_ , a_ ) -> Optional[int]: """simple docstring""" if root: inorder(root.left , a_ ) res.append(root.val ) inorder(root.right , a_ ) def UpperCAmelCase ( a_ ) -> Union[str, Any]: """simple docstring""" if len(a_ ) == 0: return arr __A = Node(arr[0] ) for i in range(1 , len(a_ ) ): root.insert(arr[i] ) # Traverse BST in order. __A = [] inorder(a_ , a_ ) return res if __name__ == "__main__": print(tree_sort([10, 1, 3, 2, 9, 14, 13]))
55
import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = LayoutLMTokenizer snake_case_ = LayoutLMTokenizerFast snake_case_ = True snake_case_ = True def UpperCamelCase_ ( self : Any ): super().setUp() __A = [ "[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest", ] __A = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file ,"w" ,encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) def UpperCamelCase_ ( self : Tuple ,**A : int ): return LayoutLMTokenizer.from_pretrained(self.tmpdirname ,**A ) def UpperCamelCase_ ( self : Optional[Any] ,A : Any ): __A = "UNwant\u00E9d,running" __A = "unwanted, running" return input_text, output_text def UpperCamelCase_ ( self : str ): __A = self.tokenizer_class(self.vocab_file ) __A = tokenizer.tokenize("UNwant\u00E9d,running" ) self.assertListEqual(A ,["un", "##want", "##ed", ",", "runn", "##ing"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(A ) ,[7, 4, 5, 10, 8, 9] ) def UpperCamelCase_ ( self : int ): pass
55
1
import json import unittest import numpy as np from huggingface_hub import hf_hub_download 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 transformers import OneFormerImageProcessor from transformers.models.oneformer.image_processing_oneformer import binary_mask_to_rle from transformers.models.oneformer.modeling_oneformer import OneFormerForUniversalSegmentationOutput if is_vision_available(): from PIL import Image def UpperCAmelCase ( a_ , a_="shi-labs/oneformer_demo" ) -> Optional[int]: """simple docstring""" with open(hf_hub_download(a_ , a_ , repo_type="dataset" ) , "r" ) as f: __A = json.load(a_ ) __A = {} __A = [] __A = [] for key, info in class_info.items(): __A = info["name"] class_names.append(info["name"] ) if info["isthing"]: thing_ids.append(int(a_ ) ) __A = thing_ids __A = class_names return metadata class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self : str ,A : Optional[int] ,A : List[Any]=7 ,A : List[str]=3 ,A : Tuple=30 ,A : List[Any]=4_00 ,A : List[str]=None ,A : List[str]=True ,A : str=True ,A : Optional[Any]=[0.5, 0.5, 0.5] ,A : Optional[int]=[0.5, 0.5, 0.5] ,A : List[Any]=10 ,A : Dict=False ,A : Any=2_55 ,A : int="shi-labs/oneformer_demo" ,A : Tuple="ade20k_panoptic.json" ,A : List[Any]=10 ,): __A = parent __A = batch_size __A = num_channels __A = min_resolution __A = max_resolution __A = do_resize __A = {"shortest_edge": 32, "longest_edge": 13_33} if size is None else size __A = do_normalize __A = image_mean __A = image_std __A = class_info_file __A = prepare_metadata(A ,A ) __A = num_text __A = repo_path # for the post_process_functions __A = 2 __A = 10 __A = 10 __A = 3 __A = 4 __A = num_labels __A = do_reduce_labels __A = ignore_index def UpperCamelCase_ ( self : Dict ): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "num_labels": self.num_labels, "do_reduce_labels": self.do_reduce_labels, "ignore_index": self.ignore_index, "class_info_file": self.class_info_file, "metadata": self.metadata, "num_text": self.num_text, } def UpperCamelCase_ ( self : Dict ,A : Optional[int] ,A : Tuple=False ): if not batched: __A = image_inputs[0] if isinstance(A ,Image.Image ): __A , __A = image.size else: __A , __A = image.shape[1], image.shape[2] if w < h: __A = int(self.size["shortest_edge"] * h / w ) __A = self.size["shortest_edge"] elif w > h: __A = self.size["shortest_edge"] __A = int(self.size["shortest_edge"] * w / h ) else: __A = self.size["shortest_edge"] __A = self.size["shortest_edge"] else: __A = [] for image in image_inputs: __A , __A = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __A = max(A ,key=lambda A : item[0] )[0] __A = max(A ,key=lambda A : item[1] )[1] return expected_height, expected_width def UpperCamelCase_ ( self : Union[str, Any] ): return OneFormerForUniversalSegmentationOutput( # +1 for null class class_queries_logits=torch.randn((self.batch_size, self.num_queries, self.num_classes + 1) ) ,masks_queries_logits=torch.randn((self.batch_size, self.num_queries, self.height, self.width) ) ,) @require_torch @require_vision class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = OneFormerImageProcessor if (is_vision_available() and is_torch_available()) else None # only for test_image_processing_common.test_image_proc_to_json_string snake_case_ = image_processing_class def UpperCamelCase_ ( self : Union[str, Any] ): __A = OneFormerImageProcessorTester(self ) @property def UpperCamelCase_ ( self : Optional[Any] ): return self.image_processing_tester.prepare_image_processor_dict() def UpperCamelCase_ ( self : Union[str, Any] ): __A = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(A ,"image_mean" ) ) self.assertTrue(hasattr(A ,"image_std" ) ) self.assertTrue(hasattr(A ,"do_normalize" ) ) self.assertTrue(hasattr(A ,"do_resize" ) ) self.assertTrue(hasattr(A ,"size" ) ) self.assertTrue(hasattr(A ,"ignore_index" ) ) self.assertTrue(hasattr(A ,"class_info_file" ) ) self.assertTrue(hasattr(A ,"num_text" ) ) self.assertTrue(hasattr(A ,"repo_path" ) ) self.assertTrue(hasattr(A ,"metadata" ) ) self.assertTrue(hasattr(A ,"do_reduce_labels" ) ) def UpperCamelCase_ ( self : Optional[int] ): pass def UpperCamelCase_ ( self : Any ): # Initialize image_processor __A = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __A = prepare_image_inputs(self.image_processing_tester ,equal_resolution=A ) for image in image_inputs: self.assertIsInstance(A ,Image.Image ) # Test not batched input __A = image_processor(image_inputs[0] ,["semantic"] ,return_tensors="pt" ).pixel_values __A , __A = self.image_processing_tester.get_expected_values(A ) self.assertEqual( encoded_images.shape ,(1, self.image_processing_tester.num_channels, expected_height, expected_width) ,) # Test batched __A , __A = self.image_processing_tester.get_expected_values(A ,batched=A ) __A = image_processor( A ,["semantic"] * len(A ) ,return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape ,( self.image_processing_tester.batch_size, self.image_processing_tester.num_channels, expected_height, expected_width, ) ,) def UpperCamelCase_ ( self : Union[str, Any] ): # Initialize image_processor __A = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __A = prepare_image_inputs(self.image_processing_tester ,equal_resolution=A ,numpify=A ) for image in image_inputs: self.assertIsInstance(A ,np.ndarray ) # Test not batched input __A = image_processor(image_inputs[0] ,["semantic"] ,return_tensors="pt" ).pixel_values __A , __A = self.image_processing_tester.get_expected_values(A ) self.assertEqual( encoded_images.shape ,(1, self.image_processing_tester.num_channels, expected_height, expected_width) ,) # Test batched __A , __A = self.image_processing_tester.get_expected_values(A ,batched=A ) __A = image_processor( A ,["semantic"] * len(A ) ,return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape ,( self.image_processing_tester.batch_size, self.image_processing_tester.num_channels, expected_height, expected_width, ) ,) def UpperCamelCase_ ( self : Tuple ): # Initialize image_processor __A = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A = prepare_image_inputs(self.image_processing_tester ,equal_resolution=A ,torchify=A ) for image in image_inputs: self.assertIsInstance(A ,torch.Tensor ) # Test not batched input __A = image_processor(image_inputs[0] ,["semantic"] ,return_tensors="pt" ).pixel_values __A , __A = self.image_processing_tester.get_expected_values(A ) self.assertEqual( encoded_images.shape ,(1, self.image_processing_tester.num_channels, expected_height, expected_width) ,) # Test batched __A , __A = self.image_processing_tester.get_expected_values(A ,batched=A ) __A = image_processor( A ,["semantic"] * len(A ) ,return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape ,( self.image_processing_tester.batch_size, self.image_processing_tester.num_channels, expected_height, expected_width, ) ,) def UpperCamelCase_ ( self : Union[str, Any] ,A : Tuple=False ,A : List[str]=False ,A : Optional[Any]="np" ): __A = self.image_processing_class(**self.image_processor_dict ) # prepare image and target __A = self.image_processing_tester.num_labels __A = None __A = None __A = prepare_image_inputs(self.image_processing_tester ,equal_resolution=A ) if with_segmentation_maps: __A = num_labels if is_instance_map: __A = list(range(A ) ) * 2 __A = dict(enumerate(A ) ) __A = [ np.random.randint(0 ,high * 2 ,(img.size[1], img.size[0]) ).astype(np.uinta ) for img in image_inputs ] if segmentation_type == "pil": __A = [Image.fromarray(A ) for annotation in annotations] __A = image_processor( A ,["semantic"] * len(A ) ,A ,return_tensors="pt" ,instance_id_to_semantic_id=A ,pad_and_return_pixel_mask=A ,) return inputs def UpperCamelCase_ ( self : int ): pass def UpperCamelCase_ ( self : Tuple ): def common(A : Optional[Any]=False ,A : str=None ): __A = self.comm_get_image_processor_inputs( with_segmentation_maps=A ,is_instance_map=A ,segmentation_type=A ) __A = inputs["mask_labels"] __A = inputs["class_labels"] __A = inputs["pixel_values"] __A = inputs["text_inputs"] # check the batch_size for mask_label, class_label, text_input in zip(A ,A ,A ): self.assertEqual(mask_label.shape[0] ,class_label.shape[0] ) # this ensure padding has happened self.assertEqual(mask_label.shape[1:] ,pixel_values.shape[2:] ) self.assertEqual(len(A ) ,self.image_processing_tester.num_text ) common() common(is_instance_map=A ) common(is_instance_map=A ,segmentation_type="pil" ) common(is_instance_map=A ,segmentation_type="pil" ) def UpperCamelCase_ ( self : List[Any] ): __A = np.zeros((20, 50) ) __A = 1 __A = 1 __A = 1 __A = binary_mask_to_rle(A ) self.assertEqual(len(A ) ,4 ) self.assertEqual(rle[0] ,21 ) self.assertEqual(rle[1] ,45 ) def UpperCamelCase_ ( self : Dict ): __A = self.image_processing_class( num_labels=self.image_processing_tester.num_classes ,max_seq_length=77 ,task_seq_length=77 ,class_info_file="ade20k_panoptic.json" ,num_text=self.image_processing_tester.num_text ,repo_path="shi-labs/oneformer_demo" ,) __A = self.image_processing_tester.get_fake_oneformer_outputs() __A = fature_extractor.post_process_semantic_segmentation(A ) self.assertEqual(len(A ) ,self.image_processing_tester.batch_size ) self.assertEqual( segmentation[0].shape ,( self.image_processing_tester.height, self.image_processing_tester.width, ) ,) __A = [(1, 4) for i in range(self.image_processing_tester.batch_size )] __A = fature_extractor.post_process_semantic_segmentation(A ,target_sizes=A ) self.assertEqual(segmentation[0].shape ,target_sizes[0] ) def UpperCamelCase_ ( self : int ): __A = self.image_processing_class( num_labels=self.image_processing_tester.num_classes ,max_seq_length=77 ,task_seq_length=77 ,class_info_file="ade20k_panoptic.json" ,num_text=self.image_processing_tester.num_text ,repo_path="shi-labs/oneformer_demo" ,) __A = self.image_processing_tester.get_fake_oneformer_outputs() __A = image_processor.post_process_instance_segmentation(A ,threshold=0 ) self.assertTrue(len(A ) == self.image_processing_tester.batch_size ) for el in segmentation: self.assertTrue("segmentation" in el ) self.assertTrue("segments_info" in el ) self.assertEqual(type(el["segments_info"] ) ,A ) self.assertEqual( el["segmentation"].shape ,(self.image_processing_tester.height, self.image_processing_tester.width) ) def UpperCamelCase_ ( self : Tuple ): __A = self.image_processing_class( num_labels=self.image_processing_tester.num_classes ,max_seq_length=77 ,task_seq_length=77 ,class_info_file="ade20k_panoptic.json" ,num_text=self.image_processing_tester.num_text ,repo_path="shi-labs/oneformer_demo" ,) __A = self.image_processing_tester.get_fake_oneformer_outputs() __A = image_processor.post_process_panoptic_segmentation(A ,threshold=0 ) self.assertTrue(len(A ) == self.image_processing_tester.batch_size ) for el in segmentation: self.assertTrue("segmentation" in el ) self.assertTrue("segments_info" in el ) self.assertEqual(type(el["segments_info"] ) ,A ) self.assertEqual( el["segmentation"].shape ,(self.image_processing_tester.height, self.image_processing_tester.width) )
55
SCREAMING_SNAKE_CASE :int = {str(digit): digit**5 for digit in range(10)} def UpperCAmelCase ( a_ ) -> int: """simple docstring""" return sum(DIGITS_FIFTH_POWER[digit] for digit in str(a_ ) ) def UpperCAmelCase ( ) -> int: """simple docstring""" return sum( number for number in range(1_0_0_0 , 1_0_0_0_0_0_0 ) if number == digits_fifth_powers_sum(a_ ) ) if __name__ == "__main__": print(solution())
55
1
import gc import unittest from diffusers import FlaxStableDiffusionInpaintPipeline from diffusers.utils import is_flax_available, load_image, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard @slow @require_flax class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase_ ( self : Tuple ): # clean up the VRAM after each test super().tearDown() gc.collect() def UpperCamelCase_ ( self : Optional[int] ): __A = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/sd2-inpaint/init_image.png" ) __A = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png" ) __A = "xvjiarui/stable-diffusion-2-inpainting" __A , __A = FlaxStableDiffusionInpaintPipeline.from_pretrained(A ,safety_checker=A ) __A = "Face of a yellow cat, high resolution, sitting on a park bench" __A = jax.random.PRNGKey(0 ) __A = 50 __A = jax.device_count() __A = num_samples * [prompt] __A = num_samples * [init_image] __A = num_samples * [mask_image] __A , __A , __A = pipeline.prepare_inputs(A ,A ,A ) # shard inputs and rng __A = replicate(A ) __A = jax.random.split(A ,jax.device_count() ) __A = shard(A ) __A = shard(A ) __A = shard(A ) __A = pipeline( A ,A ,A ,A ,A ,A ,jit=A ) __A = output.images.reshape(A ,5_12 ,5_12 ,3 ) __A = images[0, 2_53:2_56, 2_53:2_56, -1] __A = jnp.asarray(jax.device_get(image_slice.flatten() ) ) __A = jnp.array( [0.3_61_13_07, 0.37_64_97_36, 0.3_75_74_08, 0.38_21_39_53, 0.39_29_51_67, 0.3_84_16_31, 0.41_55_49_78, 0.4_13_74_75, 0.4_21_70_84] ) print(f'''output_slice: {output_slice}''' ) assert jnp.abs(output_slice - expected_slice ).max() < 1E-2
55
import inspect import unittest from transformers import MobileNetVaConfig 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 MobileNetVaForImageClassification, MobileNetVaModel from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileNetVaImageProcessor class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def UpperCamelCase_ ( self : Any ): __A = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(A ,"tf_padding" ) ) self.parent.assertTrue(hasattr(A ,"depth_multiplier" ) ) class UpperCAmelCase : '''simple docstring''' def __init__( self : Optional[Any] ,A : int ,A : List[Any]=13 ,A : int=3 ,A : Optional[Any]=32 ,A : Union[str, Any]=0.25 ,A : Tuple=8 ,A : Optional[int]=True ,A : Union[str, Any]=10_24 ,A : Any=32 ,A : Optional[int]="relu6" ,A : int=0.1 ,A : Optional[Any]=0.02 ,A : Optional[Any]=True ,A : List[str]=True ,A : str=10 ,A : str=None ,): __A = parent __A = batch_size __A = num_channels __A = image_size __A = depth_multiplier __A = min_depth __A = tf_padding __A = int(last_hidden_size * depth_multiplier ) __A = output_stride __A = hidden_act __A = classifier_dropout_prob __A = use_labels __A = is_training __A = num_labels __A = initializer_range __A = scope def UpperCamelCase_ ( self : Optional[int] ): __A = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __A = None __A = None if self.use_labels: __A = ids_tensor([self.batch_size] ,self.num_labels ) __A = ids_tensor([self.batch_size, self.image_size, self.image_size] ,self.num_labels ) __A = self.get_config() return config, pixel_values, labels, pixel_labels def UpperCamelCase_ ( self : Any ): return MobileNetVaConfig( num_channels=self.num_channels ,image_size=self.image_size ,depth_multiplier=self.depth_multiplier ,min_depth=self.min_depth ,tf_padding=self.tf_padding ,hidden_act=self.hidden_act ,classifier_dropout_prob=self.classifier_dropout_prob ,initializer_range=self.initializer_range ,) def UpperCamelCase_ ( self : Optional[int] ,A : str ,A : Tuple ,A : Optional[int] ,A : List[str] ): __A = MobileNetVaModel(config=A ) model.to(A ) model.eval() __A = model(A ) self.parent.assertEqual( result.last_hidden_state.shape ,( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) ,) def UpperCamelCase_ ( self : List[Any] ,A : Union[str, Any] ,A : List[Any] ,A : int ,A : Union[str, Any] ): __A = self.num_labels __A = MobileNetVaForImageClassification(A ) model.to(A ) model.eval() __A = model(A ,labels=A ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def UpperCamelCase_ ( self : Tuple ): __A = self.prepare_config_and_inputs() __A , __A , __A , __A = config_and_inputs __A = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = (MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else () snake_case_ = ( {"feature-extraction": MobileNetVaModel, "image-classification": MobileNetVaForImageClassification} if is_torch_available() else {} ) snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = False def UpperCamelCase_ ( self : Any ): __A = MobileNetVaModelTester(self ) __A = MobileNetVaConfigTester(self ,config_class=A ,has_text_modality=A ) def UpperCamelCase_ ( self : str ): self.config_tester.run_common_tests() @unittest.skip(reason="MobileNetV1 does not use inputs_embeds" ) def UpperCamelCase_ ( self : Union[str, Any] ): pass @unittest.skip(reason="MobileNetV1 does not support input and output embeddings" ) def UpperCamelCase_ ( self : Tuple ): pass @unittest.skip(reason="MobileNetV1 does not output attentions" ) def UpperCamelCase_ ( self : Any ): pass def UpperCamelCase_ ( self : Optional[int] ): __A , __A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __A = model_class(A ) __A = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __A = [*signature.parameters.keys()] __A = ["pixel_values"] self.assertListEqual(arg_names[:1] ,A ) def UpperCamelCase_ ( self : List[Any] ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A ) def UpperCamelCase_ ( self : Optional[int] ): def check_hidden_states_output(A : List[Any] ,A : List[Any] ,A : Optional[int] ): __A = model_class(A ) model.to(A ) model.eval() with torch.no_grad(): __A = model(**self._prepare_for_class(A ,A ) ) __A = outputs.hidden_states __A = 26 self.assertEqual(len(A ) ,A ) __A , __A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __A = True check_hidden_states_output(A ,A ,A ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __A = True check_hidden_states_output(A ,A ,A ) def UpperCamelCase_ ( self : Tuple ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*A ) @slow def UpperCamelCase_ ( self : Union[str, Any] ): for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __A = MobileNetVaModel.from_pretrained(A ) self.assertIsNotNone(A ) def UpperCAmelCase ( ) -> str: """simple docstring""" __A = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def UpperCamelCase_ ( self : List[str] ): return ( MobileNetVaImageProcessor.from_pretrained("google/mobilenet_v1_1.0_224" ) if is_vision_available() else None ) @slow def UpperCamelCase_ ( self : Optional[Any] ): __A = MobileNetVaForImageClassification.from_pretrained("google/mobilenet_v1_1.0_224" ).to(A ) __A = self.default_image_processor __A = prepare_img() __A = image_processor(images=A ,return_tensors="pt" ).to(A ) # forward pass with torch.no_grad(): __A = model(**A ) # verify the logits __A = torch.Size((1, 10_01) ) self.assertEqual(outputs.logits.shape ,A ) __A = torch.tensor([-4.17_39, -1.12_33, 3.12_05] ).to(A ) self.assertTrue(torch.allclose(outputs.logits[0, :3] ,A ,atol=1E-4 ) )
55
1
# DISCLAIMER: This file is strongly influenced by https://github.com/yang-song/score_sde_pytorch import math from typing import Union import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import randn_tensor from .scheduling_utils import SchedulerMixin class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = 1 @register_to_config def __init__( self : List[Any] ,A : str=20_00 ,A : str=0.1 ,A : List[str]=20 ,A : int=1E-3 ): __A = None __A = None __A = None def UpperCamelCase_ ( self : List[str] ,A : List[str] ,A : Union[str, torch.device] = None ): __A = torch.linspace(1 ,self.config.sampling_eps ,A ,device=A ) def UpperCamelCase_ ( self : Dict ,A : List[Any] ,A : Optional[Any] ,A : Union[str, Any] ,A : Union[str, Any]=None ): if self.timesteps is None: raise ValueError( "`self.timesteps` is not set, you need to run 'set_timesteps' after creating the scheduler" ) # TODO(Patrick) better comments + non-PyTorch # postprocess model score __A = ( -0.25 * t**2 * (self.config.beta_max - self.config.beta_min) - 0.5 * t * self.config.beta_min ) __A = torch.sqrt(1.0 - torch.exp(2.0 * log_mean_coeff ) ) __A = std.flatten() while len(std.shape ) < len(score.shape ): __A = std.unsqueeze(-1 ) __A = -score / std # compute __A = -1.0 / len(self.timesteps ) __A = self.config.beta_min + t * (self.config.beta_max - self.config.beta_min) __A = beta_t.flatten() while len(beta_t.shape ) < len(x.shape ): __A = beta_t.unsqueeze(-1 ) __A = -0.5 * beta_t * x __A = torch.sqrt(A ) __A = drift - diffusion**2 * score __A = x + drift * dt # add noise __A = randn_tensor(x.shape ,layout=x.layout ,generator=A ,device=x.device ,dtype=x.dtype ) __A = x_mean + diffusion * math.sqrt(-dt ) * noise return x, x_mean def __len__( self : Optional[Any] ): return self.config.num_train_timesteps
55
import copy import unittest from transformers.models.auto import get_values from transformers.testing_utils import require_torch, 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, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_MULTIPLE_CHOICE_MAPPING, MODEL_FOR_QUESTION_ANSWERING_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaModel, ) from transformers.models.layoutlmva.modeling_layoutlmva import LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class UpperCAmelCase : '''simple docstring''' def __init__( self : str ,A : int ,A : int=2 ,A : Optional[Any]=3 ,A : Dict=4 ,A : Optional[int]=2 ,A : Union[str, Any]=7 ,A : List[str]=True ,A : Union[str, Any]=True ,A : Optional[int]=True ,A : Optional[int]=True ,A : Tuple=99 ,A : Optional[int]=36 ,A : Dict=3 ,A : str=4 ,A : Optional[Any]=37 ,A : Dict="gelu" ,A : Dict=0.1 ,A : Union[str, Any]=0.1 ,A : Union[str, Any]=5_12 ,A : Any=16 ,A : Union[str, Any]=2 ,A : List[Any]=0.02 ,A : List[Any]=6 ,A : Optional[int]=6 ,A : List[Any]=3 ,A : Union[str, Any]=4 ,A : Tuple=None ,A : List[str]=10_00 ,): __A = parent __A = batch_size __A = num_channels __A = image_size __A = patch_size __A = text_seq_length __A = is_training __A = use_input_mask __A = use_token_type_ids __A = use_labels __A = vocab_size __A = hidden_size __A = num_hidden_layers __A = num_attention_heads __A = intermediate_size __A = hidden_act __A = hidden_dropout_prob __A = attention_probs_dropout_prob __A = max_position_embeddings __A = type_vocab_size __A = type_sequence_label_size __A = initializer_range __A = coordinate_size __A = shape_size __A = num_labels __A = num_choices __A = scope __A = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) __A = text_seq_length __A = (image_size // patch_size) ** 2 + 1 __A = self.text_seq_length + self.image_seq_length def UpperCamelCase_ ( self : int ): __A = ids_tensor([self.batch_size, self.text_seq_length] ,self.vocab_size ) __A = ids_tensor([self.batch_size, self.text_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]: __A = bbox[i, j, 3] __A = bbox[i, j, 1] __A = t if bbox[i, j, 2] < bbox[i, j, 0]: __A = bbox[i, j, 2] __A = bbox[i, j, 0] __A = t __A = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __A = None if self.use_input_mask: __A = random_attention_mask([self.batch_size, self.text_seq_length] ) __A = None if self.use_token_type_ids: __A = ids_tensor([self.batch_size, self.text_seq_length] ,self.type_vocab_size ) __A = None __A = None if self.use_labels: __A = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) __A = ids_tensor([self.batch_size, self.text_seq_length] ,self.num_labels ) __A = LayoutLMvaConfig( 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 ,coordinate_size=self.coordinate_size ,shape_size=self.shape_size ,input_size=self.image_size ,patch_size=self.patch_size ,) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def UpperCamelCase_ ( self : Optional[int] ,A : List[str] ,A : Any ,A : Dict ,A : List[Any] ,A : Optional[int] ,A : Any ,A : Dict ,A : List[Any] ): __A = LayoutLMvaModel(config=A ) model.to(A ) model.eval() # text + image __A = model(A ,pixel_values=A ) __A = model( A ,bbox=A ,pixel_values=A ,attention_mask=A ,token_type_ids=A ) __A = model(A ,bbox=A ,pixel_values=A ,token_type_ids=A ) __A = model(A ,bbox=A ,pixel_values=A ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) # text only __A = model(A ) self.parent.assertEqual( result.last_hidden_state.shape ,(self.batch_size, self.text_seq_length, self.hidden_size) ) # image only __A = model(pixel_values=A ) self.parent.assertEqual( result.last_hidden_state.shape ,(self.batch_size, self.image_seq_length, self.hidden_size) ) def UpperCamelCase_ ( self : Optional[int] ,A : Dict ,A : List[str] ,A : Any ,A : List[Any] ,A : Any ,A : Any ,A : Dict ,A : Optional[Any] ): __A = self.num_labels __A = LayoutLMvaForSequenceClassification(A ) model.to(A ) model.eval() __A = model( A ,bbox=A ,pixel_values=A ,attention_mask=A ,token_type_ids=A ,labels=A ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def UpperCamelCase_ ( self : str ,A : Optional[Any] ,A : Dict ,A : str ,A : Tuple ,A : Union[str, Any] ,A : List[Any] ,A : Any ,A : Union[str, Any] ): __A = self.num_labels __A = LayoutLMvaForTokenClassification(config=A ) model.to(A ) model.eval() __A = model( A ,bbox=A ,pixel_values=A ,attention_mask=A ,token_type_ids=A ,labels=A ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.text_seq_length, self.num_labels) ) def UpperCamelCase_ ( self : Optional[int] ,A : Optional[Any] ,A : int ,A : str ,A : List[str] ,A : int ,A : List[str] ,A : List[str] ,A : Dict ): __A = LayoutLMvaForQuestionAnswering(config=A ) model.to(A ) model.eval() __A = model( A ,bbox=A ,pixel_values=A ,attention_mask=A ,token_type_ids=A ,start_positions=A ,end_positions=A ,) self.parent.assertEqual(result.start_logits.shape ,(self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape ,(self.batch_size, self.seq_length) ) def UpperCamelCase_ ( self : str ): __A = self.prepare_config_and_inputs() ( ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ( __A ) , ) = config_and_inputs __A = { "input_ids": input_ids, "bbox": bbox, "pixel_values": pixel_values, "token_type_ids": token_type_ids, "attention_mask": input_mask, } return config, inputs_dict @require_torch class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = ( ( LayoutLMvaModel, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaForQuestionAnswering, ) if is_torch_available() else () ) snake_case_ = ( {"document-question-answering": LayoutLMvaForQuestionAnswering, "feature-extraction": LayoutLMvaModel} if is_torch_available() else {} ) def UpperCamelCase_ ( self : str ,A : Any ,A : Any ,A : Tuple ,A : List[Any] ,A : Optional[Any] ): # `DocumentQuestionAnsweringPipeline` is expected to work with this model, but it combines the text and visual # embedding along the sequence dimension (dim 1), which causes an error during post-processing as `p_mask` has # the sequence dimension of the text embedding only. # (see the line `embedding_output = torch.cat([embedding_output, visual_embeddings], dim=1)`) return True def UpperCamelCase_ ( self : Union[str, Any] ): __A = LayoutLMvaModelTester(self ) __A = ConfigTester(self ,config_class=A ,hidden_size=37 ) def UpperCamelCase_ ( self : List[Any] ,A : int ,A : List[str] ,A : Dict=False ): __A = copy.deepcopy(A ) if model_class in get_values(A ): __A = { k: v.unsqueeze(1 ).expand(-1 ,self.model_tester.num_choices ,-1 ).contiguous() if isinstance(A ,torch.Tensor ) and v.ndim > 1 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(A ): __A = torch.ones(self.model_tester.batch_size ,dtype=torch.long ,device=A ) elif model_class in get_values(A ): __A = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=A ) __A = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=A ) elif model_class in [ *get_values(A ), ]: __A = torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=A ) elif model_class in [ *get_values(A ), ]: __A = torch.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) ,dtype=torch.long ,device=A ,) return inputs_dict def UpperCamelCase_ ( self : List[Any] ): self.config_tester.run_common_tests() def UpperCamelCase_ ( self : Union[str, Any] ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A ) def UpperCamelCase_ ( self : str ): __A = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __A = type self.model_tester.create_and_check_model(*A ) def UpperCamelCase_ ( self : Optional[Any] ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*A ) def UpperCamelCase_ ( self : Optional[Any] ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*A ) def UpperCamelCase_ ( self : str ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*A ) @slow def UpperCamelCase_ ( self : Optional[int] ): for model_name in LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __A = LayoutLMvaModel.from_pretrained(A ) self.assertIsNotNone(A ) def UpperCAmelCase ( ) -> Dict: """simple docstring""" __A = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def UpperCamelCase_ ( self : Any ): return LayoutLMvaImageProcessor(apply_ocr=A ) if is_vision_available() else None @slow def UpperCamelCase_ ( self : Dict ): __A = LayoutLMvaModel.from_pretrained("microsoft/layoutlmv3-base" ).to(A ) __A = self.default_image_processor __A = prepare_img() __A = image_processor(images=A ,return_tensors="pt" ).pixel_values.to(A ) __A = torch.tensor([[1, 2]] ) __A = torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]] ).unsqueeze(0 ) # forward pass __A = model( input_ids=input_ids.to(A ) ,bbox=bbox.to(A ) ,pixel_values=pixel_values.to(A ) ,) # verify the logits __A = torch.Size((1, 1_99, 7_68) ) self.assertEqual(outputs.last_hidden_state.shape ,A ) __A = torch.tensor( [[-0.05_29, 0.36_18, 0.16_32], [-0.15_87, -0.16_67, -0.04_00], [-0.15_57, -0.16_71, -0.05_05]] ).to(A ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] ,A ,atol=1E-4 ) )
55
1
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging SCREAMING_SNAKE_CASE :Union[str, Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE :Dict = { 'kssteven/ibert-roberta-base': 'https://huggingface.co/kssteven/ibert-roberta-base/resolve/main/config.json', 'kssteven/ibert-roberta-large': 'https://huggingface.co/kssteven/ibert-roberta-large/resolve/main/config.json', 'kssteven/ibert-roberta-large-mnli': ( 'https://huggingface.co/kssteven/ibert-roberta-large-mnli/resolve/main/config.json' ), } class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = "ibert" def __init__( self : Union[str, Any] ,A : Tuple=3_05_22 ,A : Optional[Any]=7_68 ,A : List[Any]=12 ,A : Optional[Any]=12 ,A : List[str]=30_72 ,A : Union[str, Any]="gelu" ,A : str=0.1 ,A : int=0.1 ,A : Dict=5_12 ,A : str=2 ,A : Any=0.02 ,A : str=1E-12 ,A : List[str]=1 ,A : str=0 ,A : Optional[Any]=2 ,A : Union[str, Any]="absolute" ,A : Optional[int]=False ,A : Any="none" ,**A : str ,): super().__init__(pad_token_id=A ,bos_token_id=A ,eos_token_id=A ,**A ) __A = vocab_size __A = hidden_size __A = num_hidden_layers __A = num_attention_heads __A = hidden_act __A = intermediate_size __A = hidden_dropout_prob __A = attention_probs_dropout_prob __A = max_position_embeddings __A = type_vocab_size __A = initializer_range __A = layer_norm_eps __A = position_embedding_type __A = quant_mode __A = force_dequant class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' @property def UpperCamelCase_ ( self : Tuple ): if self.task == "multiple-choice": __A = {0: "batch", 1: "choice", 2: "sequence"} else: __A = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
55
import unittest import numpy as np from datasets import load_dataset 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 BeitImageProcessor class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self : Any ,A : List[str] ,A : str=7 ,A : Optional[Any]=3 ,A : Any=18 ,A : int=30 ,A : int=4_00 ,A : List[str]=True ,A : Union[str, Any]=None ,A : Union[str, Any]=True ,A : Tuple=None ,A : Tuple=True ,A : Union[str, Any]=[0.5, 0.5, 0.5] ,A : str=[0.5, 0.5, 0.5] ,A : List[Any]=False ,): __A = size if size is not None else {"height": 20, "width": 20} __A = crop_size if crop_size is not None else {"height": 18, "width": 18} __A = parent __A = batch_size __A = num_channels __A = image_size __A = min_resolution __A = max_resolution __A = do_resize __A = size __A = do_center_crop __A = crop_size __A = do_normalize __A = image_mean __A = image_std __A = do_reduce_labels def UpperCamelCase_ ( self : List[str] ): return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_reduce_labels": self.do_reduce_labels, } def UpperCAmelCase ( ) -> int: """simple docstring""" __A = load_dataset("hf-internal-testing/fixtures_ade20k" , split="test" ) __A = Image.open(dataset[0]["file"] ) __A = Image.open(dataset[1]["file"] ) return image, map def UpperCAmelCase ( ) -> Optional[int]: """simple docstring""" __A = load_dataset("hf-internal-testing/fixtures_ade20k" , split="test" ) __A = Image.open(ds[0]["file"] ) __A = Image.open(ds[1]["file"] ) __A = Image.open(ds[2]["file"] ) __A = Image.open(ds[3]["file"] ) return [imagea, imagea], [mapa, mapa] @require_torch @require_vision class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = BeitImageProcessor if is_vision_available() else None def UpperCamelCase_ ( self : List[Any] ): __A = BeitImageProcessingTester(self ) @property def UpperCamelCase_ ( self : List[Any] ): return self.image_processor_tester.prepare_image_processor_dict() def UpperCamelCase_ ( self : int ): __A = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(A ,"do_resize" ) ) self.assertTrue(hasattr(A ,"size" ) ) self.assertTrue(hasattr(A ,"do_center_crop" ) ) self.assertTrue(hasattr(A ,"center_crop" ) ) self.assertTrue(hasattr(A ,"do_normalize" ) ) self.assertTrue(hasattr(A ,"image_mean" ) ) self.assertTrue(hasattr(A ,"image_std" ) ) def UpperCamelCase_ ( self : List[str] ): __A = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size ,{"height": 20, "width": 20} ) self.assertEqual(image_processor.crop_size ,{"height": 18, "width": 18} ) self.assertEqual(image_processor.do_reduce_labels ,A ) __A = self.image_processing_class.from_dict( self.image_processor_dict ,size=42 ,crop_size=84 ,reduce_labels=A ) self.assertEqual(image_processor.size ,{"height": 42, "width": 42} ) self.assertEqual(image_processor.crop_size ,{"height": 84, "width": 84} ) self.assertEqual(image_processor.do_reduce_labels ,A ) def UpperCamelCase_ ( self : List[Any] ): pass def UpperCamelCase_ ( self : Optional[int] ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __A = prepare_image_inputs(self.image_processor_tester ,equal_resolution=A ) for image in image_inputs: self.assertIsInstance(A ,Image.Image ) # Test not batched input __A = 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 __A = image_processing(A ,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 UpperCamelCase_ ( self : List[str] ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __A = prepare_image_inputs(self.image_processor_tester ,equal_resolution=A ,numpify=A ) for image in image_inputs: self.assertIsInstance(A ,np.ndarray ) # Test not batched input __A = 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 __A = image_processing(A ,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 UpperCamelCase_ ( self : int ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A = prepare_image_inputs(self.image_processor_tester ,equal_resolution=A ,torchify=A ) for image in image_inputs: self.assertIsInstance(A ,torch.Tensor ) # Test not batched input __A = 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 __A = image_processing(A ,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 UpperCamelCase_ ( self : str ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A = prepare_image_inputs(self.image_processor_tester ,equal_resolution=A ,torchify=A ) __A = [] for image in image_inputs: self.assertIsInstance(A ,torch.Tensor ) maps.append(torch.zeros(image.shape[-2:] ).long() ) # Test not batched input __A = image_processing(image_inputs[0] ,maps[0] ,return_tensors="pt" ) self.assertEqual( encoding["pixel_values"].shape ,( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,) self.assertEqual( encoding["labels"].shape ,( 1, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,) self.assertEqual(encoding["labels"].dtype ,torch.long ) self.assertTrue(encoding["labels"].min().item() >= 0 ) self.assertTrue(encoding["labels"].max().item() <= 2_55 ) # Test batched __A = image_processing(A ,A ,return_tensors="pt" ) self.assertEqual( encoding["pixel_values"].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"], ) ,) self.assertEqual( encoding["labels"].shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,) self.assertEqual(encoding["labels"].dtype ,torch.long ) self.assertTrue(encoding["labels"].min().item() >= 0 ) self.assertTrue(encoding["labels"].max().item() <= 2_55 ) # Test not batched input (PIL images) __A , __A = prepare_semantic_single_inputs() __A = image_processing(A ,A ,return_tensors="pt" ) self.assertEqual( encoding["pixel_values"].shape ,( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,) self.assertEqual( encoding["labels"].shape ,( 1, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,) self.assertEqual(encoding["labels"].dtype ,torch.long ) self.assertTrue(encoding["labels"].min().item() >= 0 ) self.assertTrue(encoding["labels"].max().item() <= 2_55 ) # Test batched input (PIL images) __A , __A = prepare_semantic_batch_inputs() __A = image_processing(A ,A ,return_tensors="pt" ) self.assertEqual( encoding["pixel_values"].shape ,( 2, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,) self.assertEqual( encoding["labels"].shape ,( 2, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) ,) self.assertEqual(encoding["labels"].dtype ,torch.long ) self.assertTrue(encoding["labels"].min().item() >= 0 ) self.assertTrue(encoding["labels"].max().item() <= 2_55 ) def UpperCamelCase_ ( self : Dict ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # ADE20k has 150 classes, and the background is included, so labels should be between 0 and 150 __A , __A = prepare_semantic_single_inputs() __A = image_processing(A ,A ,return_tensors="pt" ) self.assertTrue(encoding["labels"].min().item() >= 0 ) self.assertTrue(encoding["labels"].max().item() <= 1_50 ) __A = True __A = image_processing(A ,A ,return_tensors="pt" ) self.assertTrue(encoding["labels"].min().item() >= 0 ) self.assertTrue(encoding["labels"].max().item() <= 2_55 )
55
1
import inspect import os import re from transformers.configuration_utils import PretrainedConfig from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_config_docstrings.py SCREAMING_SNAKE_CASE :Dict = 'src/transformers' # This is to make sure the transformers module imported is the one in the repo. SCREAMING_SNAKE_CASE :Optional[int] = direct_transformers_import(PATH_TO_TRANSFORMERS) SCREAMING_SNAKE_CASE :int = transformers.models.auto.configuration_auto.CONFIG_MAPPING SCREAMING_SNAKE_CASE :Union[str, Any] = { # used to compute the property `self.chunk_length` 'EncodecConfig': ['overlap'], # used as `self.bert_model = BertModel(config, ...)` 'DPRConfig': True, # not used in modeling files, but it's an important information 'FSMTConfig': ['langs'], # used internally in the configuration class file 'GPTNeoConfig': ['attention_types'], # used internally in the configuration class file 'EsmConfig': ['is_folding_model'], # used during training (despite we don't have training script for these models yet) 'Mask2FormerConfig': ['ignore_value'], # `ignore_value` used during training (despite we don't have training script for these models yet) # `norm` used in conversion script (despite not using in the modeling file) 'OneFormerConfig': ['ignore_value', 'norm'], # used during preprocessing and collation, see `collating_graphormer.py` 'GraphormerConfig': ['spatial_pos_max'], # used internally in the configuration class file 'T5Config': ['feed_forward_proj'], # used internally in the configuration class file # `tokenizer_class` get default value `T5Tokenizer` intentionally 'MT5Config': ['feed_forward_proj', 'tokenizer_class'], 'UMT5Config': ['feed_forward_proj', 'tokenizer_class'], # used internally in the configuration class file 'LongT5Config': ['feed_forward_proj'], # used internally in the configuration class file 'SwitchTransformersConfig': ['feed_forward_proj'], # having default values other than `1e-5` - we can't fix them without breaking 'BioGptConfig': ['layer_norm_eps'], # having default values other than `1e-5` - we can't fix them without breaking 'GLPNConfig': ['layer_norm_eps'], # having default values other than `1e-5` - we can't fix them without breaking 'SegformerConfig': ['layer_norm_eps'], # having default values other than `1e-5` - we can't fix them without breaking 'CvtConfig': ['layer_norm_eps'], # having default values other than `1e-5` - we can't fix them without breaking 'PerceiverConfig': ['layer_norm_eps'], # used internally to calculate the feature size 'InformerConfig': ['num_static_real_features', 'num_time_features'], # used internally to calculate the feature size 'TimeSeriesTransformerConfig': ['num_static_real_features', 'num_time_features'], # used internally to calculate the feature size 'AutoformerConfig': ['num_static_real_features', 'num_time_features'], # used internally to calculate `mlp_dim` 'SamVisionConfig': ['mlp_ratio'], # For (head) training, but so far not implemented 'ClapAudioConfig': ['num_classes'], # Not used, but providing useful information to users 'SpeechT5HifiGanConfig': ['sampling_rate'], } # TODO (ydshieh): Check the failing cases, try to fix them or move some cases to the above block once we are sure SPECIAL_CASES_TO_ALLOW.update( { 'CLIPSegConfig': True, 'DeformableDetrConfig': True, 'DetaConfig': True, 'DinatConfig': True, 'DonutSwinConfig': True, 'EfficientFormerConfig': True, 'FSMTConfig': True, 'JukeboxConfig': True, 'LayoutLMv2Config': True, 'MaskFormerSwinConfig': True, 'MT5Config': True, 'NatConfig': True, 'OneFormerConfig': True, 'PerceiverConfig': True, 'RagConfig': True, 'SpeechT5Config': True, 'SwinConfig': True, 'Swin2SRConfig': True, 'Swinv2Config': True, 'SwitchTransformersConfig': True, 'TableTransformerConfig': True, 'TapasConfig': True, 'TransfoXLConfig': True, 'UniSpeechConfig': True, 'UniSpeechSatConfig': True, 'WavLMConfig': True, 'WhisperConfig': True, # TODO: @Arthur (for `alignment_head` and `alignment_layer`) 'JukeboxPriorConfig': True, # TODO: @Younes (for `is_decoder`) 'Pix2StructTextConfig': True, } ) def UpperCAmelCase ( a_ , a_ , a_ , a_ ) -> str: """simple docstring""" __A = False for attribute in attributes: for modeling_source in source_strings: # check if we can find `config.xxx`, `getattr(config, "xxx", ...)` or `getattr(self.config, "xxx", ...)` if ( F'''config.{attribute}''' in modeling_source or F'''getattr(config, "{attribute}"''' in modeling_source or F'''getattr(self.config, "{attribute}"''' in modeling_source ): __A = True # Deal with multi-line cases elif ( re.search( rF'''getattr[ \t\v\n\r\f]*\([ \t\v\n\r\f]*(self\.)?config,[ \t\v\n\r\f]*"{attribute}"''' , a_ , ) is not None ): __A = True # `SequenceSummary` is called with `SequenceSummary(config)` elif attribute in [ "summary_type", "summary_use_proj", "summary_activation", "summary_last_dropout", "summary_proj_to_labels", "summary_first_dropout", ]: if "SequenceSummary" in modeling_source: __A = True if attribute_used: break if attribute_used: break # common and important attributes, even if they do not always appear in the modeling files __A = [ "bos_index", "eos_index", "pad_index", "unk_index", "mask_index", "image_size", "use_cache", "out_features", "out_indices", ] __A = ["encoder_no_repeat_ngram_size"] # Special cases to be allowed __A = True if not attribute_used: __A = False for attribute in attributes: # Allow if the default value in the configuration class is different from the one in `PretrainedConfig` if attribute in ["is_encoder_decoder"] and default_value is True: __A = True elif attribute in ["tie_word_embeddings"] and default_value is False: __A = True # Allow cases without checking the default value in the configuration class elif attribute in attributes_to_allow + attributes_used_in_generation: __A = True elif attribute.endswith("_token_id" ): __A = True # configuration class specific cases if not case_allowed: __A = SPECIAL_CASES_TO_ALLOW.get(config_class.__name__ , [] ) __A = allowed_cases is True or attribute in allowed_cases return attribute_used or case_allowed def UpperCAmelCase ( a_ ) -> Dict: """simple docstring""" __A = dict(inspect.signature(config_class.__init__ ).parameters ) __A = [x for x in list(signature.keys() ) if x not in ["self", "kwargs"]] __A = [signature[param].default for param in parameter_names] # If `attribute_map` exists, an attribute can have different names to be used in the modeling files, and as long # as one variant is used, the test should pass __A = {} if len(config_class.attribute_map ) > 0: __A = {v: k for k, v in config_class.attribute_map.items()} # Get the path to modeling source files __A = inspect.getsourcefile(a_ ) __A = os.path.dirname(a_ ) # Let's check against all frameworks: as long as one framework uses an attribute, we are good. __A = [os.path.join(a_ , a_ ) for fn in os.listdir(a_ ) if fn.startswith("modeling_" )] # Get the source code strings __A = [] for path in modeling_paths: if os.path.isfile(a_ ): with open(a_ ) as fp: modeling_sources.append(fp.read() ) __A = [] for config_param, default_value in zip(a_ , a_ ): # `attributes` here is all the variant names for `config_param` __A = [config_param] # some configuration classes have non-empty `attribute_map`, and both names could be used in the # corresponding modeling files. As long as one of them appears, it is fine. if config_param in reversed_attribute_map: attributes.append(reversed_attribute_map[config_param] ) if not check_attribute_being_used(a_ , a_ , a_ , a_ ): unused_attributes.append(attributes[0] ) return sorted(a_ ) def UpperCAmelCase ( ) -> Optional[Any]: """simple docstring""" __A = {} for _config_class in list(CONFIG_MAPPING.values() ): # Skip deprecated models if "models.deprecated" in _config_class.__module__: continue # Some config classes are not in `CONFIG_MAPPING` (e.g. `CLIPVisionConfig`, `Blip2VisionConfig`, etc.) __A = [ cls for name, cls in inspect.getmembers( inspect.getmodule(_config_class ) , lambda a_ : inspect.isclass(a_ ) and issubclass(a_ , a_ ) and inspect.getmodule(a_ ) == inspect.getmodule(_config_class ) , ) ] for config_class in config_classes_in_module: __A = check_config_attributes_being_used(a_ ) if len(a_ ) > 0: __A = unused_attributes if len(a_ ) > 0: __A = "The following configuration classes contain unused attributes in the corresponding modeling files:\n" for name, attributes in configs_with_unused_attributes.items(): error += F'''{name}: {attributes}\n''' raise ValueError(a_ ) if __name__ == "__main__": check_config_attributes()
55
from numpy import exp, pi, sqrt def UpperCAmelCase ( a_ , a_ = 0.0 , a_ = 1.0 ) -> int: """simple docstring""" return 1 / sqrt(2 * pi * sigma**2 ) * exp(-((x - mu) ** 2) / (2 * sigma**2) ) if __name__ == "__main__": import doctest doctest.testmod()
55
1
def UpperCAmelCase ( a_ ) -> list: """simple docstring""" if any(not isinstance(a_ , a_ ) or x < 0 for x in sequence ): raise TypeError("Sequence must be list of non-negative integers" ) for _ in range(len(a_ ) ): for i, (rod_upper, rod_lower) in enumerate(zip(a_ , 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]
55
import gc import unittest from diffusers import FlaxStableDiffusionInpaintPipeline from diffusers.utils import is_flax_available, load_image, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard @slow @require_flax class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase_ ( self : Tuple ): # clean up the VRAM after each test super().tearDown() gc.collect() def UpperCamelCase_ ( self : Optional[int] ): __A = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/sd2-inpaint/init_image.png" ) __A = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png" ) __A = "xvjiarui/stable-diffusion-2-inpainting" __A , __A = FlaxStableDiffusionInpaintPipeline.from_pretrained(A ,safety_checker=A ) __A = "Face of a yellow cat, high resolution, sitting on a park bench" __A = jax.random.PRNGKey(0 ) __A = 50 __A = jax.device_count() __A = num_samples * [prompt] __A = num_samples * [init_image] __A = num_samples * [mask_image] __A , __A , __A = pipeline.prepare_inputs(A ,A ,A ) # shard inputs and rng __A = replicate(A ) __A = jax.random.split(A ,jax.device_count() ) __A = shard(A ) __A = shard(A ) __A = shard(A ) __A = pipeline( A ,A ,A ,A ,A ,A ,jit=A ) __A = output.images.reshape(A ,5_12 ,5_12 ,3 ) __A = images[0, 2_53:2_56, 2_53:2_56, -1] __A = jnp.asarray(jax.device_get(image_slice.flatten() ) ) __A = jnp.array( [0.3_61_13_07, 0.37_64_97_36, 0.3_75_74_08, 0.38_21_39_53, 0.39_29_51_67, 0.3_84_16_31, 0.41_55_49_78, 0.4_13_74_75, 0.4_21_70_84] ) print(f'''output_slice: {output_slice}''' ) assert jnp.abs(output_slice - expected_slice ).max() < 1E-2
55
1
def UpperCAmelCase ( a_ ) -> list: """simple docstring""" if bit_count < 0: raise ValueError("The given input must be positive" ) # get the generated string sequence __A = gray_code_sequence_string(a_ ) # # convert them to integers for i in range(len(a_ ) ): __A = int(sequence[i] , 2 ) return sequence def UpperCAmelCase ( a_ ) -> list: """simple docstring""" if bit_count == 0: return ["0"] if bit_count == 1: return ["0", "1"] __A = 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 __A = gray_code_sequence_string(bit_count - 1 ) __A = [] # append 0 to first half of the smaller sequence generated for i in range(seq_len // 2 ): __A = "0" + smaller_sequence[i] sequence.append(a_ ) # append 1 to second half ... start from the end of the list for i in reversed(range(seq_len // 2 ) ): __A = "1" + smaller_sequence[i] sequence.append(a_ ) return sequence if __name__ == "__main__": import doctest doctest.testmod()
55
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 GLPNImageProcessor class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self : Any ,A : Optional[int] ,A : Optional[int]=7 ,A : Optional[Any]=3 ,A : List[str]=18 ,A : Any=30 ,A : Tuple=4_00 ,A : Union[str, Any]=True ,A : Optional[Any]=32 ,A : Union[str, Any]=True ,): __A = parent __A = batch_size __A = num_channels __A = image_size __A = min_resolution __A = max_resolution __A = do_resize __A = size_divisor __A = do_rescale def UpperCamelCase_ ( self : Union[str, Any] ): return { "do_resize": self.do_resize, "size_divisor": self.size_divisor, "do_rescale": self.do_rescale, } @require_torch @require_vision class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = GLPNImageProcessor if is_vision_available() else None def UpperCamelCase_ ( self : int ): __A = GLPNImageProcessingTester(self ) @property def UpperCamelCase_ ( self : Optional[Any] ): return self.image_processor_tester.prepare_image_processor_dict() def UpperCamelCase_ ( self : Any ): __A = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(A ,"do_resize" ) ) self.assertTrue(hasattr(A ,"size_divisor" ) ) self.assertTrue(hasattr(A ,"resample" ) ) self.assertTrue(hasattr(A ,"do_rescale" ) ) def UpperCamelCase_ ( self : str ): pass def UpperCamelCase_ ( self : Dict ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __A = prepare_image_inputs(self.image_processor_tester ,equal_resolution=A ) for image in image_inputs: self.assertIsInstance(A ,Image.Image ) # Test not batched input (GLPNImageProcessor doesn't support batching) __A = image_processing(image_inputs[0] ,return_tensors="pt" ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 ) def UpperCamelCase_ ( self : Optional[Any] ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __A = prepare_image_inputs(self.image_processor_tester ,equal_resolution=A ,numpify=A ) for image in image_inputs: self.assertIsInstance(A ,np.ndarray ) # Test not batched input (GLPNImageProcessor doesn't support batching) __A = image_processing(image_inputs[0] ,return_tensors="pt" ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 ) def UpperCamelCase_ ( self : int ): # Initialize image_processing __A = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A = prepare_image_inputs(self.image_processor_tester ,equal_resolution=A ,torchify=A ) for image in image_inputs: self.assertIsInstance(A ,torch.Tensor ) # Test not batched input (GLPNImageProcessor doesn't support batching) __A = image_processing(image_inputs[0] ,return_tensors="pt" ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 )
55
1
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Image from .base import TaskTemplate @dataclass(frozen=__SCREAMING_SNAKE_CASE ) class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = field(default="image-classification" , metadata={"include_in_asdict_even_if_is_default": True} ) snake_case_ = Features({"image": Image()} ) snake_case_ = Features({"labels": ClassLabel} ) snake_case_ = "image" snake_case_ = "labels" def UpperCamelCase_ ( self : Optional[Any] ,A : Tuple ): if self.label_column not in features: raise ValueError(f'''Column {self.label_column} is not present in features.''' ) if not isinstance(features[self.label_column] ,A ): raise ValueError(f'''Column {self.label_column} is not a ClassLabel.''' ) __A = copy.deepcopy(self ) __A = self.label_schema.copy() __A = features[self.label_column] __A = label_schema return task_template @property def UpperCamelCase_ ( self : Any ): return { self.image_column: "image", self.label_column: "labels", }
55
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Image from .base import TaskTemplate @dataclass(frozen=__SCREAMING_SNAKE_CASE ) class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = field(default="image-classification" , metadata={"include_in_asdict_even_if_is_default": True} ) snake_case_ = Features({"image": Image()} ) snake_case_ = Features({"labels": ClassLabel} ) snake_case_ = "image" snake_case_ = "labels" def UpperCamelCase_ ( self : Optional[Any] ,A : Tuple ): if self.label_column not in features: raise ValueError(f'''Column {self.label_column} is not present in features.''' ) if not isinstance(features[self.label_column] ,A ): raise ValueError(f'''Column {self.label_column} is not a ClassLabel.''' ) __A = copy.deepcopy(self ) __A = self.label_schema.copy() __A = features[self.label_column] __A = label_schema return task_template @property def UpperCamelCase_ ( self : Any ): return { self.image_column: "image", self.label_column: "labels", }
55
1
import os from typing import Dict, List, Tuple, TypeVar, Union SCREAMING_SNAKE_CASE :Optional[Any] = TypeVar('T') SCREAMING_SNAKE_CASE :Dict = Union[List[T], Tuple[T, ...]] SCREAMING_SNAKE_CASE :Optional[Any] = Union[T, List[T], Dict[str, T]] SCREAMING_SNAKE_CASE :Any = Union[str, bytes, os.PathLike]
55
from math import sqrt def UpperCAmelCase ( a_ ) -> bool: """simple docstring""" assert isinstance(a_ , a_ ) and ( number >= 0 ), "'number' must been an int and positive" __A = True # 0 and 1 are none primes. if number <= 1: __A = False for divisor in range(2 , int(round(sqrt(a_ ) ) ) + 1 ): # if 'number' divisible by 'divisor' then sets 'status' # of false and break up the loop. if number % divisor == 0: __A = False break # precondition assert isinstance(a_ , a_ ), "'status' must been from type bool" return status def UpperCAmelCase ( a_ ) -> Any: """simple docstring""" assert isinstance(a_ , a_ ) and (n > 2), "'N' must been an int and > 2" # beginList: contains all natural numbers from 2 up to N __A = list(range(2 , n + 1 ) ) __A = [] # this list will be returns. # actual sieve of erathostenes for i in range(len(a_ ) ): for j in range(i + 1 , len(a_ ) ): if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0): __A = 0 # filters actual prime numbers. __A = [x for x in begin_list if x != 0] # precondition assert isinstance(a_ , a_ ), "'ans' must been from type list" return ans def UpperCAmelCase ( a_ ) -> Optional[int]: """simple docstring""" assert isinstance(a_ , a_ ) and (n > 2), "'N' must been an int and > 2" __A = [] # iterates over all numbers between 2 up to N+1 # if a number is prime then appends to list 'ans' for number in range(2 , n + 1 ): if is_prime(a_ ): ans.append(a_ ) # precondition assert isinstance(a_ , a_ ), "'ans' must been from type list" return ans def UpperCAmelCase ( a_ ) -> Optional[int]: """simple docstring""" assert isinstance(a_ , a_ ) and number >= 0, "'number' must been an int and >= 0" __A = [] # this list will be returns of the function. # potential prime number factors. __A = 2 __A = number if number == 0 or number == 1: ans.append(a_ ) # if 'number' not prime then builds the prime factorization of 'number' elif not is_prime(a_ ): while quotient != 1: if is_prime(a_ ) and (quotient % factor == 0): ans.append(a_ ) quotient /= factor else: factor += 1 else: ans.append(a_ ) # precondition assert isinstance(a_ , a_ ), "'ans' must been from type list" return ans def UpperCAmelCase ( a_ ) -> Any: """simple docstring""" assert isinstance(a_ , a_ ) and ( number >= 0 ), "'number' bust been an int and >= 0" __A = 0 # prime factorization of 'number' __A = prime_factorization(a_ ) __A = max(a_ ) # precondition assert isinstance(a_ , a_ ), "'ans' must been from type int" return ans def UpperCAmelCase ( a_ ) -> Optional[Any]: """simple docstring""" assert isinstance(a_ , a_ ) and ( number >= 0 ), "'number' bust been an int and >= 0" __A = 0 # prime factorization of 'number' __A = prime_factorization(a_ ) __A = min(a_ ) # precondition assert isinstance(a_ , a_ ), "'ans' must been from type int" return ans def UpperCAmelCase ( a_ ) -> int: """simple docstring""" assert isinstance(a_ , a_ ), "'number' must been an int" assert isinstance(number % 2 == 0 , a_ ), "compare bust been from type bool" return number % 2 == 0 def UpperCAmelCase ( a_ ) -> List[Any]: """simple docstring""" assert isinstance(a_ , a_ ), "'number' must been an int" assert isinstance(number % 2 != 0 , a_ ), "compare bust been from type bool" return number % 2 != 0 def UpperCAmelCase ( a_ ) -> Optional[Any]: """simple docstring""" assert ( isinstance(a_ , a_ ) and (number > 2) and is_even(a_ ) ), "'number' must been an int, even and > 2" __A = [] # this list will returned # creates a list of prime numbers between 2 up to 'number' __A = get_prime_numbers(a_ ) __A = len(a_ ) # run variable for while-loops. __A = 0 __A = None # exit variable. for break up the loops __A = True while i < len_pn and loop: __A = i + 1 while j < len_pn and loop: if prime_numbers[i] + prime_numbers[j] == number: __A = False ans.append(prime_numbers[i] ) ans.append(prime_numbers[j] ) j += 1 i += 1 # precondition assert ( isinstance(a_ , a_ ) and (len(a_ ) == 2) and (ans[0] + ans[1] == number) and is_prime(ans[0] ) and is_prime(ans[1] ) ), "'ans' must contains two primes. And sum of elements must been eq 'number'" return ans def UpperCAmelCase ( a_ , a_ ) -> Optional[Any]: """simple docstring""" assert ( isinstance(a_ , a_ ) and isinstance(a_ , a_ ) and (numbera >= 0) and (numbera >= 0) ), "'number1' and 'number2' must been positive integer." __A = 0 while numbera != 0: __A = numbera % numbera __A = numbera __A = rest # precondition assert isinstance(a_ , a_ ) and ( numbera >= 0 ), "'number' must been from type int and positive" return numbera def UpperCAmelCase ( a_ , a_ ) -> List[str]: """simple docstring""" assert ( isinstance(a_ , a_ ) and isinstance(a_ , a_ ) and (numbera >= 1) and (numbera >= 1) ), "'number1' and 'number2' must been positive integer." __A = 1 # actual answer that will be return. # for kgV (x,1) if numbera > 1 and numbera > 1: # builds the prime factorization of 'number1' and 'number2' __A = prime_factorization(a_ ) __A = prime_factorization(a_ ) elif numbera == 1 or numbera == 1: __A = [] __A = [] __A = max(a_ , a_ ) __A = 0 __A = 0 __A = [] # captured numbers int both 'primeFac1' and 'primeFac2' # iterates through primeFac1 for n in prime_fac_a: if n not in done: if n in prime_fac_a: __A = prime_fac_a.count(a_ ) __A = prime_fac_a.count(a_ ) for _ in range(max(a_ , a_ ) ): ans *= n else: __A = prime_fac_a.count(a_ ) for _ in range(a_ ): ans *= n done.append(a_ ) # iterates through primeFac2 for n in prime_fac_a: if n not in done: __A = prime_fac_a.count(a_ ) for _ in range(a_ ): ans *= n done.append(a_ ) # precondition assert isinstance(a_ , a_ ) and ( ans >= 0 ), "'ans' must been from type int and positive" return ans def UpperCAmelCase ( a_ ) -> str: """simple docstring""" assert isinstance(a_ , a_ ) and (n >= 0), "'number' must been a positive int" __A = 0 __A = 2 # this variable holds the answer while index < n: index += 1 ans += 1 # counts to the next number # if ans not prime then # runs to the next prime number. while not is_prime(a_ ): ans += 1 # precondition assert isinstance(a_ , a_ ) and is_prime( a_ ), "'ans' must been a prime number and from type int" return ans def UpperCAmelCase ( a_ , a_ ) -> Tuple: """simple docstring""" assert ( is_prime(a_ ) and is_prime(a_ ) and (p_number_a < p_number_a) ), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'" __A = p_number_a + 1 # jump to the next number __A = [] # this list will be returns. # if number is not prime then # fetch the next prime number. while not is_prime(a_ ): number += 1 while number < p_number_a: ans.append(a_ ) number += 1 # fetch the next prime number. while not is_prime(a_ ): number += 1 # precondition assert ( isinstance(a_ , a_ ) and ans[0] != p_number_a and ans[len(a_ ) - 1] != p_number_a ), "'ans' must been a list without the arguments" # 'ans' contains not 'pNumber1' and 'pNumber2' ! return ans def UpperCAmelCase ( a_ ) -> str: """simple docstring""" assert isinstance(a_ , a_ ) and (n >= 1), "'n' must been int and >= 1" __A = [] # will be returned. for divisor in range(1 , n + 1 ): if n % divisor == 0: ans.append(a_ ) # precondition assert ans[0] == 1 and ans[len(a_ ) - 1] == n, "Error in function getDivisiors(...)" return ans def UpperCAmelCase ( a_ ) -> Dict: """simple docstring""" assert isinstance(a_ , a_ ) and ( number > 1 ), "'number' must been an int and >= 1" __A = get_divisors(a_ ) # precondition assert ( isinstance(a_ , a_ ) and (divisors[0] == 1) and (divisors[len(a_ ) - 1] == number) ), "Error in help-function getDivisiors(...)" # summed all divisors up to 'number' (exclusive), hence [:-1] return sum(divisors[:-1] ) == number def UpperCAmelCase ( a_ , a_ ) -> str: """simple docstring""" assert ( isinstance(a_ , a_ ) and isinstance(a_ , a_ ) and (denominator != 0) ), "The arguments must been from type int and 'denominator' != 0" # build the greatest common divisor of numerator and denominator. __A = gcd(abs(a_ ) , abs(a_ ) ) # precondition assert ( isinstance(a_ , a_ ) and (numerator % gcd_of_fraction == 0) and (denominator % gcd_of_fraction == 0) ), "Error in function gcd(...,...)" return (numerator // gcd_of_fraction, denominator // gcd_of_fraction) def UpperCAmelCase ( a_ ) -> Optional[int]: """simple docstring""" assert isinstance(a_ , a_ ) and (n >= 0), "'n' must been a int and >= 0" __A = 1 # this will be return. for factor in range(1 , n + 1 ): ans *= factor return ans def UpperCAmelCase ( a_ ) -> List[Any]: """simple docstring""" assert isinstance(a_ , a_ ) and (n >= 0), "'n' must been an int and >= 0" __A = 0 __A = 1 __A = 1 # this will be return for _ in range(n - 1 ): __A = ans ans += fiba __A = tmp return ans
55
1
import json import os from pathlib import Path from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple, Union import sentencepiece from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging SCREAMING_SNAKE_CASE :str = logging.get_logger(__name__) SCREAMING_SNAKE_CASE :List[str] = '▁' SCREAMING_SNAKE_CASE :int = { 'vocab_file': 'vocab.json', 'spm_file': 'sentencepiece.bpe.model', } SCREAMING_SNAKE_CASE :Optional[Any] = { 'vocab_file': { 'facebook/s2t-small-librispeech-asr': ( 'https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/vocab.json' ), }, 'spm_file': { 'facebook/s2t-small-librispeech-asr': ( 'https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/sentencepiece.bpe.model' ) }, } SCREAMING_SNAKE_CASE :Any = { 'facebook/s2t-small-librispeech-asr': 1024, } SCREAMING_SNAKE_CASE :List[Any] = ['pt', 'fr', 'ru', 'nl', 'ro', 'it', 'es', 'de'] SCREAMING_SNAKE_CASE :Optional[Any] = {'mustc': MUSTC_LANGS} class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = VOCAB_FILES_NAMES snake_case_ = PRETRAINED_VOCAB_FILES_MAP snake_case_ = MAX_MODEL_INPUT_SIZES snake_case_ = ["input_ids", "attention_mask"] snake_case_ = [] def __init__( self : Optional[Any] ,A : int ,A : Dict ,A : int="<s>" ,A : List[Any]="</s>" ,A : Dict="<pad>" ,A : List[str]="<unk>" ,A : List[Any]=False ,A : List[str]=False ,A : Union[str, Any]=None ,A : Dict=None ,A : Optional[Dict[str, Any]] = None ,**A : Optional[int] ,): __A = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=A ,eos_token=A ,unk_token=A ,pad_token=A ,do_upper_case=A ,do_lower_case=A ,tgt_lang=A ,lang_codes=A ,sp_model_kwargs=self.sp_model_kwargs ,**A ,) __A = do_upper_case __A = do_lower_case __A = load_json(A ) __A = {v: k for k, v in self.encoder.items()} __A = spm_file __A = load_spm(A ,self.sp_model_kwargs ) if lang_codes is not None: __A = lang_codes __A = LANGUAGES[lang_codes] __A = [f'''<lang:{lang}>''' for lang in self.langs] __A = {lang: self.sp_model.PieceToId(f'''<lang:{lang}>''' ) for lang in self.langs} __A = self.lang_tokens __A = tgt_lang if tgt_lang is not None else self.langs[0] self.set_tgt_lang_special_tokens(self._tgt_lang ) else: __A = {} @property def UpperCamelCase_ ( self : Optional[int] ): return len(self.encoder ) @property def UpperCamelCase_ ( self : List[Any] ): return self._tgt_lang @tgt_lang.setter def UpperCamelCase_ ( self : str ,A : Any ): __A = new_tgt_lang self.set_tgt_lang_special_tokens(A ) def UpperCamelCase_ ( self : List[str] ,A : str ): __A = self.lang_code_to_id[tgt_lang] __A = [lang_code_id] def UpperCamelCase_ ( self : Dict ,A : str ): return self.sp_model.encode(A ,out_type=A ) def UpperCamelCase_ ( self : List[str] ,A : Tuple ): return self.encoder.get(A ,self.encoder[self.unk_token] ) def UpperCamelCase_ ( self : Union[str, Any] ,A : int ): return self.decoder.get(A ,self.unk_token ) def UpperCamelCase_ ( self : Tuple ,A : List[str] ): __A = [] __A = "" for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: __A = self.sp_model.decode(A ) out_string += (decoded.upper() if self.do_upper_case else decoded) + token + " " __A = [] else: current_sub_tokens.append(A ) __A = self.sp_model.decode(A ) out_string += decoded.upper() if self.do_upper_case else decoded return out_string.strip() def UpperCamelCase_ ( self : Optional[int] ,A : int ,A : Union[str, Any]=None ): if token_ids_a is None: return self.prefix_tokens + token_ids_a + [self.eos_token_id] # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + [self.eos_token_id] def UpperCamelCase_ ( self : Dict ,A : List[int] ,A : Optional[List[int]] = None ,A : bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=A ,token_ids_a=A ,already_has_special_tokens=A ) __A = [1] * len(self.prefix_tokens ) __A = [1] if token_ids_a is None: return prefix_ones + ([0] * len(A )) + suffix_ones return prefix_ones + ([0] * len(A )) + ([0] * len(A )) + suffix_ones def UpperCamelCase_ ( self : List[Any] ): __A = self.encoder.copy() vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Optional[Any] ): __A = self.__dict__.copy() __A = None return state def __setstate__( self : Optional[int] ,A : Dict ): __A = d # for backward compatibility if not hasattr(self ,"sp_model_kwargs" ): __A = {} __A = load_spm(self.spm_file ,self.sp_model_kwargs ) def UpperCamelCase_ ( self : Union[str, Any] ,A : str ,A : Optional[str] = None ): __A = Path(A ) assert save_dir.is_dir(), f'''{save_directory} should be a directory''' __A = save_dir / ( (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["vocab_file"] ) __A = save_dir / ( (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["spm_file"] ) save_json(self.encoder ,A ) if os.path.abspath(self.spm_file ) != os.path.abspath(A ) and os.path.isfile(self.spm_file ): copyfile(self.spm_file ,A ) elif not os.path.isfile(self.spm_file ): with open(A ,"wb" ) as fi: __A = self.sp_model.serialized_model_proto() fi.write(A ) return (str(A ), str(A )) def UpperCAmelCase ( a_ , a_ ) -> sentencepiece.SentencePieceProcessor: """simple docstring""" __A = sentencepiece.SentencePieceProcessor(**a_ ) spm.Load(str(a_ ) ) return spm def UpperCAmelCase ( a_ ) -> Union[Dict, List]: """simple docstring""" with open(a_ , "r" ) as f: return json.load(a_ ) def UpperCAmelCase ( a_ , a_ ) -> None: """simple docstring""" with open(a_ , "w" ) as f: json.dump(a_ , a_ , indent=2 )
55
import os def UpperCAmelCase ( ) -> Any: """simple docstring""" __A = os.path.dirname(os.path.realpath(a_ ) ) __A = os.path.join(a_ , "triangle.txt" ) with open(a_ ) as f: __A = f.readlines() __A = [] for line in triangle: __A = [] for number in line.strip().split(" " ): numbers_from_line.append(int(a_ ) ) a.append(a_ ) for i in range(1 , len(a_ ) ): for j in range(len(a[i] ) ): __A = a[i - 1][j] if j != len(a[i - 1] ) else 0 __A = a[i - 1][j - 1] if j > 0 else 0 a[i][j] += max(a_ , a_ ) return max(a[-1] ) if __name__ == "__main__": print(solution())
55
1
from __future__ import annotations import math from collections.abc import Callable def UpperCAmelCase ( a_ , a_ , a_ , a_ = 1_0_0 , ) -> float: """simple docstring""" __A = x_start __A = fnc(a_ ) __A = 0.0 for _ in range(a_ ): # Approximates curve as a sequence of linear lines and sums their length __A = (x_end - x_start) / steps + xa __A = fnc(a_ ) length += math.hypot(xa - xa , fxa - fxa ) # Increment step __A = xa __A = fxa return length if __name__ == "__main__": def UpperCAmelCase ( a_ ) -> Optional[Any]: """simple docstring""" return math.sin(1_0 * x ) print('f(x) = sin(10 * x)') print('The length of the curve from x = -10 to x = 10 is:') SCREAMING_SNAKE_CASE :Union[str, Any] = 10 while i <= 10_0000: print(f'''With {i} steps: {line_length(f, -10, 10, i)}''') i *= 10
55
import re from flax.core.frozen_dict import freeze from flax.traverse_util import flatten_dict, unflatten_dict from jax.experimental import PartitionSpec as P # Sentinels SCREAMING_SNAKE_CASE :Union[str, Any] = object() # For specifying empty leaf dict `{}` SCREAMING_SNAKE_CASE :List[str] = object() def UpperCAmelCase ( a_ , a_ ) -> Tuple: """simple docstring""" __A = tuple((re.compile(x + "$" ) for x in qs) ) for i in range(len(a_ ) - len(a_ ) + 1 ): __A = [x.match(a_ ) for x, y in zip(a_ , ks[i:] )] if matches and all(a_ ): return True return False def UpperCAmelCase ( a_ ) -> Optional[int]: """simple docstring""" def replace(a_ , a_ ): for rule, replacement in rules: if _match(a_ , a_ ): return replacement return val return replace def UpperCAmelCase ( ) -> int: """simple docstring""" return [ # embeddings (("transformer", "wpe", "embedding"), P("mp" , a_ )), (("transformer", "wte", "embedding"), P("mp" , a_ )), # atention (("attention", "(q_proj|k_proj|v_proj)", "kernel"), P(a_ , "mp" )), (("attention", "out_proj", "kernel"), P("mp" , a_ )), (("attention", "out_proj", "bias"), None), # mlp (("mlp", "c_fc", "kernel"), P(a_ , "mp" )), (("mlp", "c_fc", "bias"), P("mp" )), (("mlp", "c_proj", "kernel"), P("mp" , a_ )), (("mlp", "c_proj", "bias"), None), # layer norms ((r"ln_\d+", "bias"), None), ((r"\d+", r"ln_\d+", "scale"), None), (("ln_f", "bias"), None), (("ln_f", "scale"), None), ] def UpperCAmelCase ( a_ ) -> List[Any]: """simple docstring""" __A = _get_partition_rules() __A = _replacement_rules(a_ ) __A = {k: _unmatched for k in flatten_dict(a_ )} __A = {k: replace(a_ , a_ ) for k, v in initd.items()} assert _unmatched not in result.values(), "Incomplete partition spec." return freeze(unflatten_dict(a_ ) )
55
1
import importlib import inspect import json import os import re import shutil import sys from pathlib import Path from typing import Dict, Optional, Union from urllib import request from huggingface_hub import HfFolder, cached_download, hf_hub_download, model_info from packaging import version from .. import __version__ from . import DIFFUSERS_DYNAMIC_MODULE_NAME, HF_MODULES_CACHE, logging SCREAMING_SNAKE_CASE :int = ( 'https://raw.githubusercontent.com/huggingface/diffusers/{revision}/examples/community/{pipeline}.py' ) SCREAMING_SNAKE_CASE :Tuple = logging.get_logger(__name__) # pylint: disable=invalid-name def UpperCAmelCase ( ) -> str: """simple docstring""" __A = "https://pypi.org/pypi/diffusers/json" __A = json.loads(request.urlopen(a_ ).read() )["releases"].keys() return sorted(a_ , key=lambda a_ : version.Version(a_ ) ) def UpperCAmelCase ( ) -> Tuple: """simple docstring""" if HF_MODULES_CACHE in sys.path: return sys.path.append(a_ ) os.makedirs(a_ , exist_ok=a_ ) __A = Path(a_ ) / "__init__.py" if not init_path.exists(): init_path.touch() def UpperCAmelCase ( a_ ) -> Optional[int]: """simple docstring""" init_hf_modules() __A = Path(a_ ) / name # If the parent module does not exist yet, recursively create it. if not dynamic_module_path.parent.exists(): create_dynamic_module(dynamic_module_path.parent ) os.makedirs(a_ , exist_ok=a_ ) __A = dynamic_module_path / "__init__.py" if not init_path.exists(): init_path.touch() def UpperCAmelCase ( a_ ) -> Dict: """simple docstring""" with open(a_ , "r" , encoding="utf-8" ) as f: __A = f.read() # Imports of the form `import .xxx` __A = re.findall("^\s*import\s+\.(\S+)\s*$" , a_ , flags=re.MULTILINE ) # Imports of the form `from .xxx import yyy` relative_imports += re.findall("^\s*from\s+\.(\S+)\s+import" , a_ , flags=re.MULTILINE ) # Unique-ify return list(set(a_ ) ) def UpperCAmelCase ( a_ ) -> List[Any]: """simple docstring""" __A = False __A = [module_file] __A = [] # Let's recurse through all relative imports while not no_change: __A = [] for f in files_to_check: new_imports.extend(get_relative_imports(a_ ) ) __A = Path(a_ ).parent __A = [str(module_path / m ) for m in new_imports] __A = [f for f in new_import_files if f not in all_relative_imports] __A = [F'''{f}.py''' for f in new_import_files] __A = len(a_ ) == 0 all_relative_imports.extend(a_ ) return all_relative_imports def UpperCAmelCase ( a_ ) -> List[Any]: """simple docstring""" with open(a_ , "r" , encoding="utf-8" ) as f: __A = f.read() # Imports of the form `import xxx` __A = re.findall("^\s*import\s+(\S+)\s*$" , a_ , flags=re.MULTILINE ) # Imports of the form `from xxx import yyy` imports += re.findall("^\s*from\s+(\S+)\s+import" , a_ , flags=re.MULTILINE ) # Only keep the top-level module __A = [imp.split("." )[0] for imp in imports if not imp.startswith("." )] # Unique-ify and test we got them all __A = list(set(a_ ) ) __A = [] for imp in imports: try: importlib.import_module(a_ ) except ImportError: missing_packages.append(a_ ) if len(a_ ) > 0: raise ImportError( "This modeling file requires the following packages that were not found in your environment: " F'''{', '.join(a_ )}. Run `pip install {' '.join(a_ )}`''' ) return get_relative_imports(a_ ) def UpperCAmelCase ( a_ , a_ ) -> Optional[int]: """simple docstring""" __A = module_path.replace(os.path.sep , "." ) __A = importlib.import_module(a_ ) if class_name is None: return find_pipeline_class(a_ ) return getattr(a_ , a_ ) def UpperCAmelCase ( a_ ) -> Optional[Any]: """simple docstring""" from ..pipelines import DiffusionPipeline __A = dict(inspect.getmembers(a_ , inspect.isclass ) ) __A = None for cls_name, cls in cls_members.items(): if ( cls_name != DiffusionPipeline.__name__ and issubclass(cls , a_ ) and cls.__module__.split("." )[0] != "diffusers" ): if pipeline_class is not None: raise ValueError( F'''Multiple classes that inherit from {DiffusionPipeline.__name__} have been found:''' F''' {pipeline_class.__name__}, and {cls_name}. Please make sure to define only one in''' F''' {loaded_module}.''' ) __A = cls return pipeline_class def UpperCAmelCase ( a_ , a_ , a_ = None , a_ = False , a_ = False , a_ = None , a_ = None , a_ = None , a_ = False , ) -> Optional[Any]: """simple docstring""" __A = str(a_ ) __A = os.path.join(a_ , a_ ) if os.path.isfile(a_ ): __A = module_file_or_url __A = "local" elif pretrained_model_name_or_path.count("/" ) == 0: __A = get_diffusers_versions() # cut ".dev0" __A = "v" + ".".join(__version__.split("." )[:3] ) # retrieve github version that matches if revision is None: __A = latest_version if latest_version[1:] in available_versions else "main" logger.info(F'''Defaulting to latest_version: {revision}.''' ) elif revision in available_versions: __A = F'''v{revision}''' elif revision == "main": __A = revision else: raise ValueError( F'''`custom_revision`: {revision} does not exist. Please make sure to choose one of''' F''' {', '.join(available_versions + ['main'] )}.''' ) # community pipeline on GitHub __A = COMMUNITY_PIPELINES_URL.format(revision=a_ , pipeline=a_ ) try: __A = cached_download( a_ , cache_dir=a_ , force_download=a_ , proxies=a_ , resume_download=a_ , local_files_only=a_ , use_auth_token=a_ , ) __A = "git" __A = pretrained_model_name_or_path + ".py" except EnvironmentError: logger.error(F'''Could not locate the {module_file} inside {pretrained_model_name_or_path}.''' ) raise else: try: # Load from URL or cache if already cached __A = hf_hub_download( a_ , a_ , cache_dir=a_ , force_download=a_ , proxies=a_ , resume_download=a_ , local_files_only=a_ , use_auth_token=a_ , ) __A = os.path.join("local" , "--".join(pretrained_model_name_or_path.split("/" ) ) ) except EnvironmentError: logger.error(F'''Could not locate the {module_file} inside {pretrained_model_name_or_path}.''' ) raise # Check we have all the requirements in our environment __A = check_imports(a_ ) # Now we move the module inside our cached dynamic modules. __A = DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule create_dynamic_module(a_ ) __A = Path(a_ ) / full_submodule if submodule == "local" or submodule == "git": # We always copy local files (we could hash the file to see if there was a change, and give them the name of # that hash, to only copy when there is a modification but it seems overkill for now). # The only reason we do the copy is to avoid putting too many folders in sys.path. shutil.copy(a_ , submodule_path / module_file ) for module_needed in modules_needed: __A = F'''{module_needed}.py''' shutil.copy(os.path.join(a_ , a_ ) , submodule_path / module_needed ) else: # Get the commit hash # TODO: we will get this info in the etag soon, so retrieve it from there and not here. if isinstance(a_ , a_ ): __A = use_auth_token elif use_auth_token is True: __A = HfFolder.get_token() else: __A = None __A = model_info(a_ , revision=a_ , token=a_ ).sha # The module file will end up being placed in a subfolder with the git hash of the repo. This way we get the # benefit of versioning. __A = submodule_path / commit_hash __A = full_submodule + os.path.sep + commit_hash create_dynamic_module(a_ ) if not (submodule_path / module_file).exists(): shutil.copy(a_ , submodule_path / module_file ) # Make sure we also have every file with relative for module_needed in modules_needed: if not (submodule_path / module_needed).exists(): get_cached_module_file( a_ , F'''{module_needed}.py''' , cache_dir=a_ , force_download=a_ , resume_download=a_ , proxies=a_ , use_auth_token=a_ , revision=a_ , local_files_only=a_ , ) return os.path.join(a_ , a_ ) def UpperCAmelCase ( a_ , a_ , a_ = None , a_ = None , a_ = False , a_ = False , a_ = None , a_ = None , a_ = None , a_ = False , **a_ , ) -> Any: """simple docstring""" __A = get_cached_module_file( a_ , a_ , cache_dir=a_ , force_download=a_ , resume_download=a_ , proxies=a_ , use_auth_token=a_ , revision=a_ , local_files_only=a_ , ) return get_class_in_module(a_ , final_module.replace(".py" , "" ) )
55
from __future__ import annotations import inspect import unittest import numpy as np from transformers import DeiTConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, TFDeiTModel, ) from transformers.models.deit.modeling_tf_deit import TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class UpperCAmelCase : '''simple docstring''' def __init__( self : List[Any] ,A : Union[str, Any] ,A : List[Any]=13 ,A : Optional[Any]=30 ,A : Union[str, Any]=2 ,A : Union[str, Any]=3 ,A : Any=True ,A : Dict=True ,A : str=32 ,A : Tuple=2 ,A : Optional[int]=4 ,A : Tuple=37 ,A : List[Any]="gelu" ,A : Dict=0.1 ,A : Optional[int]=0.1 ,A : List[Any]=10 ,A : Optional[Any]=0.02 ,A : Dict=3 ,A : Dict=None ,A : List[Any]=2 ,): __A = parent __A = batch_size __A = image_size __A = patch_size __A = num_channels __A = is_training __A = use_labels __A = hidden_size __A = num_hidden_layers __A = num_attention_heads __A = intermediate_size __A = hidden_act __A = hidden_dropout_prob __A = attention_probs_dropout_prob __A = type_sequence_label_size __A = initializer_range __A = scope __A = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) __A = (image_size // patch_size) ** 2 __A = num_patches + 2 def UpperCamelCase_ ( self : List[Any] ): __A = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __A = None if self.use_labels: __A = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) __A = self.get_config() return config, pixel_values, labels def UpperCamelCase_ ( self : Optional[int] ): return DeiTConfig( image_size=self.image_size ,patch_size=self.patch_size ,num_channels=self.num_channels ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,hidden_act=self.hidden_act ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,is_decoder=A ,initializer_range=self.initializer_range ,encoder_stride=self.encoder_stride ,) def UpperCamelCase_ ( self : List[str] ,A : List[Any] ,A : Optional[int] ,A : Union[str, Any] ): __A = TFDeiTModel(config=A ) __A = model(A ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase_ ( self : List[Any] ,A : List[Any] ,A : Optional[Any] ,A : Dict ): __A = TFDeiTForMaskedImageModeling(config=A ) __A = model(A ) self.parent.assertEqual( result.reconstruction.shape ,(self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images __A = 1 __A = TFDeiTForMaskedImageModeling(A ) __A = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __A = model(A ) self.parent.assertEqual(result.reconstruction.shape ,(self.batch_size, 1, self.image_size, self.image_size) ) def UpperCamelCase_ ( self : Optional[Any] ,A : Union[str, Any] ,A : Dict ,A : Union[str, Any] ): __A = self.type_sequence_label_size __A = TFDeiTForImageClassification(A ) __A = model(A ,labels=A ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) # test greyscale images __A = 1 __A = TFDeiTForImageClassification(A ) __A = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __A = model(A ,labels=A ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) def UpperCamelCase_ ( self : str ): __A = self.prepare_config_and_inputs() __A , __A , __A = config_and_inputs __A = {"pixel_values": pixel_values} return config, inputs_dict @require_tf class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = ( ( TFDeiTModel, TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, ) if is_tf_available() else () ) snake_case_ = ( { "feature-extraction": TFDeiTModel, "image-classification": (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher), } if is_tf_available() else {} ) snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = False def UpperCamelCase_ ( self : str ): __A = TFDeiTModelTester(self ) __A = ConfigTester(self ,config_class=A ,has_text_modality=A ,hidden_size=37 ) def UpperCamelCase_ ( self : Any ): self.config_tester.run_common_tests() @unittest.skip(reason="DeiT does not use inputs_embeds" ) def UpperCamelCase_ ( self : Union[str, Any] ): pass def UpperCamelCase_ ( self : List[Any] ): __A , __A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __A = model_class(A ) self.assertIsInstance(model.get_input_embeddings() ,(tf.keras.layers.Layer) ) __A = model.get_output_embeddings() self.assertTrue(x is None or isinstance(A ,tf.keras.layers.Dense ) ) def UpperCamelCase_ ( self : Union[str, Any] ): __A , __A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __A = model_class(A ) __A = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __A = [*signature.parameters.keys()] __A = ["pixel_values"] self.assertListEqual(arg_names[:1] ,A ) def UpperCamelCase_ ( self : Union[str, Any] ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A ) def UpperCamelCase_ ( self : Union[str, Any] ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*A ) def UpperCamelCase_ ( self : Optional[Any] ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*A ) def UpperCamelCase_ ( self : Optional[int] ,A : Union[str, Any] ,A : List[str] ,A : Optional[Any]=False ): __A = super()._prepare_for_class(A ,A ,return_labels=A ) if return_labels: if "labels" in inputs_dict and "labels" not in inspect.signature(model_class.call ).parameters: del inputs_dict["labels"] return inputs_dict @slow def UpperCamelCase_ ( self : Any ): for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __A = TFDeiTModel.from_pretrained(A ) self.assertIsNotNone(A ) def UpperCAmelCase ( ) -> str: """simple docstring""" __A = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_tf @require_vision class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def UpperCamelCase_ ( self : int ): return ( DeiTImageProcessor.from_pretrained("facebook/deit-base-distilled-patch16-224" ) if is_vision_available() else None ) @slow def UpperCamelCase_ ( self : Optional[int] ): __A = TFDeiTForImageClassificationWithTeacher.from_pretrained("facebook/deit-base-distilled-patch16-224" ) __A = self.default_image_processor __A = prepare_img() __A = image_processor(images=A ,return_tensors="tf" ) # forward pass __A = model(**A ) # verify the logits __A = tf.TensorShape((1, 10_00) ) self.assertEqual(outputs.logits.shape ,A ) __A = tf.constant([-1.02_66, 0.19_12, -1.28_61] ) self.assertTrue(np.allclose(outputs.logits[0, :3] ,A ,atol=1E-4 ) )
55
1