code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
'''simple docstring''' from math import ceil def UpperCAmelCase_ ( __lowercase : int , __lowercase : List[Any] ) -> List[str]: '''simple docstring''' _UpperCAmelCase = list(range(0 , lowerCamelCase__ ) ) _UpperCAmelCase = [item for sublist in list(device_map.values() ) for item in sublist] # Duplicate check _UpperCAmelCase = [] for i in device_map_blocks: if device_map_blocks.count(lowerCamelCase__ ) > 1 and i not in duplicate_blocks: duplicate_blocks.append(lowerCamelCase__ ) # Missing blocks _UpperCAmelCase = [i for i in blocks if i not in device_map_blocks] _UpperCAmelCase = [i for i in device_map_blocks if i not in blocks] if len(lowerCamelCase__ ) != 0: raise ValueError( "Duplicate attention blocks specified in device_map. Attention blocks must be specified to one device." " These attention blocks were specified more than once: " + str(lowerCamelCase__ ) ) if len(lowerCamelCase__ ) != 0: raise ValueError( "There are attention blocks for this model that are not specified in the device_map. Add these attention " "blocks to a device on the device_map: " + str(lowerCamelCase__ ) ) if len(lowerCamelCase__ ) != 0: raise ValueError( "The device_map contains more attention blocks than this model has. Remove these from the device_map:" + str(lowerCamelCase__ ) ) def UpperCAmelCase_ ( __lowercase : Dict , __lowercase : str ) -> Tuple: '''simple docstring''' _UpperCAmelCase = list(range(lowerCamelCase__ ) ) _UpperCAmelCase = int(ceil(n_layers / len(lowerCamelCase__ ) ) ) _UpperCAmelCase = [layers[i : i + n_blocks] for i in range(0 , lowerCamelCase__ , lowerCamelCase__ )] return dict(zip(lowerCamelCase__ , lowerCamelCase__ ) )
22
'''simple docstring''' from __future__ import annotations import math def a ( lowerCamelCase__ ): '''simple docstring''' if num <= 0: A_ : List[Any] = f'{num}: Invalid input, please enter a positive integer.' raise ValueError(lowerCamelCase__ ) A_ : Dict = [True] * (num + 1) A_ : List[Any] = [] A_ : Tuple = 2 A_ : Optional[int] = int(math.sqrt(lowerCamelCase__ ) ) while start <= end: # If start is a prime if sieve[start] is True: prime.append(lowerCamelCase__ ) # Set multiples of start be False for i in range(start * start , num + 1 , lowerCamelCase__ ): if sieve[i] is True: A_ : List[Any] = False start += 1 for j in range(end + 1 , num + 1 ): if sieve[j] is True: prime.append(lowerCamelCase__ ) return prime if __name__ == "__main__": print(prime_sieve(int(input('''Enter a positive integer: ''').strip())))
206
0
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_ = logging.get_logger(__name__) class a ( UpperCAmelCase ): _lowercase = ["pixel_values"] def __init__( self , A_ = True , A_ = None , A_ = PILImageResampling.BILINEAR , A_ = True , A_ = 1 / 255 , A_ = True , A_ = None , A_ = True , **A_ , ): '''simple docstring''' super().__init__(**A_ ) _UpperCAmelCase : Dict = size if size is not None else {"shortest_edge": 224} _UpperCAmelCase : int = get_size_dict(A_ , default_to_square=A_ ) _UpperCAmelCase : Optional[int] = crop_size if crop_size is not None else {"height": 256, "width": 256} _UpperCAmelCase : str = get_size_dict(A_ , param_name="crop_size" ) _UpperCAmelCase : int = do_resize _UpperCAmelCase : Optional[Any] = size _UpperCAmelCase : List[Any] = resample _UpperCAmelCase : Union[str, Any] = do_rescale _UpperCAmelCase : Tuple = rescale_factor _UpperCAmelCase : Dict = do_center_crop _UpperCAmelCase : Any = crop_size _UpperCAmelCase : List[Any] = do_flip_channel_order def _UpperCAmelCase ( self , A_ , A_ , A_ = PIL.Image.BILINEAR , A_ = None , **A_ , ): '''simple docstring''' _UpperCAmelCase : str = 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()}' ) _UpperCAmelCase : List[str] = 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 , A_ , A_ , A_ = None , **A_ , ): '''simple docstring''' _UpperCAmelCase : List[Any] = 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 , A_ , A_ , A_ = None , **A_ , ): '''simple docstring''' return rescale(A_ , scale=A_ , data_format=A_ , **A_ ) def _UpperCAmelCase ( self , A_ , A_ = None ): '''simple docstring''' return flip_channel_order(A_ , data_format=A_ ) def _UpperCAmelCase ( self , A_ , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = None , A_ = ChannelDimension.FIRST , **A_ , ): '''simple docstring''' _UpperCAmelCase : List[Any] = do_resize if do_resize is not None else self.do_resize _UpperCAmelCase : Optional[Any] = resample if resample is not None else self.resample _UpperCAmelCase : List[Any] = do_rescale if do_rescale is not None else self.do_rescale _UpperCAmelCase : str = rescale_factor if rescale_factor is not None else self.rescale_factor _UpperCAmelCase : int = do_center_crop if do_center_crop is not None else self.do_center_crop _UpperCAmelCase : List[str] = ( do_flip_channel_order if do_flip_channel_order is not None else self.do_flip_channel_order ) _UpperCAmelCase : str = size if size is not None else self.size _UpperCAmelCase : Dict = get_size_dict(A_ , default_to_square=A_ ) _UpperCAmelCase : int = crop_size if crop_size is not None else self.crop_size _UpperCAmelCase : Dict = get_size_dict(A_ , param_name="crop_size" ) _UpperCAmelCase : int = 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. _UpperCAmelCase : List[Any] = [to_numpy_array(A_ ) for image in images] if do_resize: _UpperCAmelCase : Union[str, Any] = [self.resize(image=A_ , size=A_ , resample=A_ ) for image in images] if do_center_crop: _UpperCAmelCase : Union[str, Any] = [self.center_crop(image=A_ , size=A_ ) for image in images] if do_rescale: _UpperCAmelCase : Dict = [self.rescale(image=A_ , scale=A_ ) for image in images] # the pretrained checkpoints assume images are BGR, not RGB if do_flip_channel_order: _UpperCAmelCase : Tuple = [self.flip_channel_order(image=A_ ) for image in images] _UpperCAmelCase : Union[str, Any] = [to_channel_dimension_format(A_ , A_ ) for image in images] _UpperCAmelCase : Optional[int] = {"pixel_values": images} return BatchFeature(data=A_ , tensor_type=A_ ) def _UpperCAmelCase ( self , A_ , A_ = None ): '''simple docstring''' _UpperCAmelCase : Any = 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_ ): _UpperCAmelCase : int = target_sizes.numpy() _UpperCAmelCase : Tuple = [] for idx in range(len(A_ ) ): _UpperCAmelCase : Optional[Any] = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode="bilinear" , align_corners=A_ ) _UpperCAmelCase : Any = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(A_ ) else: _UpperCAmelCase : Optional[int] = logits.argmax(dim=1 ) _UpperCAmelCase : List[str] = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
352
from __future__ import annotations from random import choice def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: Any ) -> Optional[int]: return choice(lowerCAmelCase ) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: list[int] , lowerCAmelCase: int ) -> int: _UpperCAmelCase : List[Any] = random_pivot(lowerCAmelCase ) # partition based on pivot # linear time _UpperCAmelCase : List[str] = [e for e in lst if e < pivot] _UpperCAmelCase : Any = [e for e in lst if e > pivot] # if we get lucky, pivot might be the element we want. # we can easily see this: # small (elements smaller than k) # + pivot (kth element) # + big (elements larger than k) if len(lowerCAmelCase ) == k - 1: return pivot # pivot is in elements bigger than k elif len(lowerCAmelCase ) < k - 1: return kth_number(lowerCAmelCase , k - len(lowerCAmelCase ) - 1 ) # pivot is in elements smaller than k else: return kth_number(lowerCAmelCase , lowerCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod()
189
0
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 ( lowerCamelCase__ , unittest.TestCase ): UpperCamelCase = LayoutLMTokenizer UpperCamelCase = LayoutLMTokenizerFast UpperCamelCase = True UpperCamelCase = True def __magic_name__ ( self : Any ): super().setUp() UpperCAmelCase : Dict = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] UpperCAmelCase : int = 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 __magic_name__ ( self : Union[str, Any], **__A : List[str] ): return LayoutLMTokenizer.from_pretrained(self.tmpdirname, **__A ) def __magic_name__ ( self : Optional[int], __A : int ): UpperCAmelCase : Optional[Any] = '''UNwant\u00E9d,running''' UpperCAmelCase : Optional[int] = '''unwanted, running''' return input_text, output_text def __magic_name__ ( self : Any ): UpperCAmelCase : Union[str, Any] = self.tokenizer_class(self.vocab_file ) UpperCAmelCase : Optional[Any] = tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(__A, ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ), [7, 4, 5, 1_0, 8, 9] ) def __magic_name__ ( self : Optional[int] ): pass
336
import inspect import unittest from transformers import ViTHybridConfig from transformers.testing_utils import require_accelerate, 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, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ViTHybridForImageClassification, ViTHybridImageProcessor, ViTHybridModel from transformers.models.vit_hybrid.modeling_vit_hybrid import VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image class __UpperCAmelCase : def __init__( self : List[Any], __A : List[str], __A : List[str]=1_3, __A : Any=6_4, __A : Optional[Any]=2, __A : str=3, __A : str=True, __A : str=True, __A : Optional[Any]=3_2, __A : List[str]=5, __A : int=4, __A : str=3_7, __A : str="gelu", __A : Dict=0.1, __A : List[Any]=0.1, __A : Dict=1_0, __A : int=0.0_2, __A : Any=[1, 1_6, 4, 4], __A : Optional[int]=None, ): UpperCAmelCase : Union[str, Any] = parent UpperCAmelCase : Any = batch_size UpperCAmelCase : List[str] = image_size UpperCAmelCase : List[str] = patch_size UpperCAmelCase : Dict = num_channels UpperCAmelCase : List[Any] = is_training UpperCAmelCase : Dict = use_labels UpperCAmelCase : Optional[int] = hidden_size UpperCAmelCase : Union[str, Any] = num_hidden_layers UpperCAmelCase : Optional[Any] = num_attention_heads UpperCAmelCase : Any = intermediate_size UpperCAmelCase : Any = hidden_act UpperCAmelCase : Any = hidden_dropout_prob UpperCAmelCase : Optional[int] = attention_probs_dropout_prob UpperCAmelCase : str = type_sequence_label_size UpperCAmelCase : Any = initializer_range UpperCAmelCase : int = scope UpperCAmelCase : List[str] = backbone_featmap_shape # in ViT hybrid, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) # the number of patches is based on the feature map of the backbone, which by default uses an output stride # of 32, which means that the feature map has a spatial resolution of 1/32 of the input image size UpperCAmelCase : str = (self.image_size // 3_2) ** 2 UpperCAmelCase : List[str] = num_patches + 1 def __magic_name__ ( self : List[str] ): UpperCAmelCase : List[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCAmelCase : str = None if self.use_labels: UpperCAmelCase : Any = ids_tensor([self.batch_size], self.type_sequence_label_size ) UpperCAmelCase : Optional[int] = self.get_config() return config, pixel_values, labels def __magic_name__ ( self : Any ): UpperCAmelCase : Dict = { '''global_padding''': '''same''', '''layer_type''': '''bottleneck''', '''depths''': [3, 4, 9], '''out_features''': ['''stage1''', '''stage2''', '''stage3'''], '''embedding_dynamic_padding''': True, '''hidden_sizes''': [4, 8, 1_6, 3_2], '''num_groups''': 2, } return ViTHybridConfig( 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, backbone_featmap_shape=self.backbone_featmap_shape, backbone_config=__A, ) def __magic_name__ ( self : Optional[int], __A : Optional[int], __A : int, __A : Tuple ): UpperCAmelCase : int = ViTHybridModel(config=__A ) model.to(__A ) model.eval() UpperCAmelCase : Tuple = model(__A ) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size) ) def __magic_name__ ( self : Tuple, __A : Dict, __A : str, __A : List[str] ): UpperCAmelCase : str = self.type_sequence_label_size UpperCAmelCase : List[Any] = ViTHybridForImageClassification(__A ) model.to(__A ) model.eval() UpperCAmelCase : Dict = model(__A, labels=__A ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size) ) def __magic_name__ ( self : int ): UpperCAmelCase : Union[str, Any] = self.prepare_config_and_inputs() UpperCAmelCase , UpperCAmelCase , UpperCAmelCase : List[str] = config_and_inputs UpperCAmelCase : int = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class __UpperCAmelCase ( lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ): UpperCamelCase = (ViTHybridModel, ViTHybridForImageClassification) if is_torch_available() else () UpperCamelCase = ( {"""feature-extraction""": ViTHybridModel, """image-classification""": ViTHybridForImageClassification} if is_torch_available() else {} ) UpperCamelCase = False UpperCamelCase = False UpperCamelCase = False def __magic_name__ ( self : Union[str, Any] ): UpperCAmelCase : Any = ViTHybridModelTester(self ) UpperCAmelCase : List[Any] = ConfigTester(self, config_class=__A, has_text_modality=__A, hidden_size=3_7 ) def __magic_name__ ( self : int ): self.config_tester.run_common_tests() @unittest.skip(reason='''ViT does not use inputs_embeds''' ) def __magic_name__ ( self : List[Any] ): pass def __magic_name__ ( self : int ): UpperCAmelCase , UpperCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase : Dict = model_class(__A ) self.assertIsInstance(model.get_input_embeddings(), (nn.Module) ) UpperCAmelCase : Optional[int] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__A, nn.Linear ) ) def __magic_name__ ( self : List[str] ): UpperCAmelCase , UpperCAmelCase : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase : List[Any] = model_class(__A ) UpperCAmelCase : Tuple = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCAmelCase : str = [*signature.parameters.keys()] UpperCAmelCase : Optional[Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1], __A ) def __magic_name__ ( self : Union[str, Any] ): UpperCAmelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__A ) def __magic_name__ ( self : Union[str, Any] ): UpperCAmelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__A ) def __magic_name__ ( self : List[str] ): UpperCAmelCase , UpperCAmelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase : Dict = _config_zero_init(__A ) for model_class in self.all_model_classes: UpperCAmelCase : Optional[Any] = model_class(config=__A ) # Skip the check for the backbone for name, module in model.named_modules(): if module.__class__.__name__ == "ViTHybridPatchEmbeddings": UpperCAmelCase : Union[str, Any] = [F'''{name}.{key}''' for key in module.state_dict().keys()] break for name, param in model.named_parameters(): if param.requires_grad: if name in backbone_params: continue self.assertIn( ((param.data.mean() * 1E9).round() / 1E9).item(), [0.0, 1.0], msg=F'''Parameter {name} of model {model_class} seems not properly initialized''', ) @slow def __magic_name__ ( self : List[str] ): for model_name in VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase : Union[str, Any] = ViTHybridModel.from_pretrained(__A ) self.assertIsNotNone(__A ) def a__ ( ) -> Tuple: UpperCAmelCase : Any = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class __UpperCAmelCase ( unittest.TestCase ): @cached_property def __magic_name__ ( self : str ): return ( ViTHybridImageProcessor.from_pretrained(VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def __magic_name__ ( self : List[str] ): UpperCAmelCase : int = ViTHybridForImageClassification.from_pretrained(VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to( __A ) UpperCAmelCase : Tuple = self.default_image_processor UpperCAmelCase : int = prepare_img() UpperCAmelCase : Union[str, Any] = image_processor(images=__A, return_tensors='''pt''' ).to(__A ) # forward pass with torch.no_grad(): UpperCAmelCase : Optional[Any] = model(**__A ) # verify the logits UpperCAmelCase : str = torch.Size((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape, __A ) UpperCAmelCase : Optional[Any] = torch.tensor([-1.9_0_9_0, -0.4_9_9_3, -0.2_3_8_9] ).to(__A ) self.assertTrue(torch.allclose(outputs.logits[0, :3], __A, atol=1E-4 ) ) @slow @require_accelerate def __magic_name__ ( self : Dict ): UpperCAmelCase : Union[str, Any] = ViTHybridImageProcessor.from_pretrained('''google/vit-hybrid-base-bit-384''' ) UpperCAmelCase : int = ViTHybridForImageClassification.from_pretrained('''google/vit-hybrid-base-bit-384''', device_map='''auto''' ) UpperCAmelCase : Tuple = prepare_img() UpperCAmelCase : Optional[int] = image_processor(images=__A, return_tensors='''pt''' ) UpperCAmelCase : Dict = model(**__A ) UpperCAmelCase : Any = outputs.logits # model predicts one of the 1000 ImageNet classes UpperCAmelCase : Dict = logits.argmax(-1 ).item() self.assertTrue(model.config.idalabel[predicted_class_idx], '''tabby, tabby cat''' )
336
1
"""simple docstring""" import logging import math import os from dataclasses import dataclass, field from glob import glob from typing import Optional from torch.utils.data import ConcatDataset import transformers from transformers import ( CONFIG_MAPPING, MODEL_WITH_LM_HEAD_MAPPING, AutoConfig, AutoModelWithLMHead, AutoTokenizer, DataCollatorForLanguageModeling, DataCollatorForPermutationLanguageModeling, DataCollatorForWholeWordMask, HfArgumentParser, LineByLineTextDataset, LineByLineWithRefDataset, PreTrainedTokenizer, TextDataset, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process A: Any = logging.getLogger(__name__) A: List[str] = list(MODEL_WITH_LM_HEAD_MAPPING.keys()) A: Dict = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class SCREAMING_SNAKE_CASE__ : __lowerCAmelCase : Optional[str] = field( default=UpperCAmelCase__ , metadata={ 'help': ( 'The model checkpoint for weights initialization. Leave None if you want to train a model from' ' scratch.' ) } , ) __lowerCAmelCase : Optional[str] = field( default=UpperCAmelCase__ , metadata={'help': 'If training from scratch, pass a model type from the list: ' + ', '.join(UpperCAmelCase__ )} , ) __lowerCAmelCase : Optional[str] = field( default=UpperCAmelCase__ , metadata={'help': 'Pretrained config name or path if not the same as model_name'} ) __lowerCAmelCase : Optional[str] = field( default=UpperCAmelCase__ , metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'} ) __lowerCAmelCase : Optional[str] = field( default=UpperCAmelCase__ , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'} , ) @dataclass class SCREAMING_SNAKE_CASE__ : __lowerCAmelCase : Optional[str] = field( default=UpperCAmelCase__ , metadata={'help': 'The input training data file (a text file).'} ) __lowerCAmelCase : Optional[str] = field( default=UpperCAmelCase__ , metadata={ 'help': ( 'The input training data files (multiple files in glob format). ' 'Very often splitting large files to smaller files can prevent tokenizer going out of memory' ) } , ) __lowerCAmelCase : Optional[str] = field( default=UpperCAmelCase__ , metadata={'help': 'An optional input evaluation data file to evaluate the perplexity on (a text file).'} , ) __lowerCAmelCase : Optional[str] = field( default=UpperCAmelCase__ , metadata={'help': 'An optional input train ref data file for whole word mask in Chinese.'} , ) __lowerCAmelCase : Optional[str] = field( default=UpperCAmelCase__ , metadata={'help': 'An optional input eval ref data file for whole word mask in Chinese.'} , ) __lowerCAmelCase : bool = field( default=UpperCAmelCase__ , metadata={'help': 'Whether distinct lines of text in the dataset are to be handled as distinct sequences.'} , ) __lowerCAmelCase : bool = field( default=UpperCAmelCase__ , metadata={'help': 'Train with masked-language modeling loss instead of language modeling.'} ) __lowerCAmelCase : bool = field(default=UpperCAmelCase__ , metadata={'help': 'Whether ot not to use whole word mask.'} ) __lowerCAmelCase : float = field( default=0.15 , metadata={'help': 'Ratio of tokens to mask for masked language modeling loss'} ) __lowerCAmelCase : float = field( default=1 / 6 , metadata={ 'help': ( 'Ratio of length of a span of masked tokens to surrounding context length for permutation language' ' modeling.' ) } , ) __lowerCAmelCase : int = field( default=5 , metadata={'help': 'Maximum length of a span of masked tokens for permutation language modeling.'} ) __lowerCAmelCase : int = field( default=-1 , metadata={ 'help': ( 'Optional input sequence length after tokenization.' 'The training dataset will be truncated in block of this size for training.' 'Default to the model max input length for single sentence inputs (take into account special tokens).' ) } , ) __lowerCAmelCase : bool = field( default=UpperCAmelCase__ , metadata={'help': 'Overwrite the cached training and evaluation sets'} ) def _snake_case ( UpperCamelCase : DataTrainingArguments , UpperCamelCase : PreTrainedTokenizer , UpperCamelCase : bool = False , UpperCamelCase : Optional[str] = None , ): def _dataset(UpperCamelCase : Optional[int] , UpperCamelCase : Optional[int]=None ): if args.line_by_line: if ref_path is not None: if not args.whole_word_mask or not args.mlm: raise ValueError("""You need to set world whole masking and mlm to True for Chinese Whole Word Mask""" ) return LineByLineWithRefDataset( tokenizer=UpperCamelCase , file_path=UpperCamelCase , block_size=args.block_size , ref_path=UpperCamelCase , ) return LineByLineTextDataset(tokenizer=UpperCamelCase , file_path=UpperCamelCase , block_size=args.block_size ) else: return TextDataset( tokenizer=UpperCamelCase , file_path=UpperCamelCase , block_size=args.block_size , overwrite_cache=args.overwrite_cache , cache_dir=UpperCamelCase , ) if evaluate: return _dataset(args.eval_data_file , args.eval_ref_file ) elif args.train_data_files: return ConcatDataset([_dataset(UpperCamelCase ) for f in glob(args.train_data_files )] ) else: return _dataset(args.train_data_file , args.train_ref_file ) def _snake_case ( ): # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. UpperCAmelCase : Any = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) UpperCAmelCase : List[str] = parser.parse_args_into_dataclasses() if data_args.eval_data_file is None and training_args.do_eval: raise ValueError( """Cannot do evaluation without an evaluation data file. Either supply a file to --eval_data_file """ """or remove the --do_eval argument.""" ) if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( F"Output directory ({training_args.output_dir}) already exists and is not empty. Use" """ --overwrite_output_dir to overcome.""" ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( """Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s""" , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info("""Training/evaluation parameters %s""" , UpperCamelCase ) # Set seed set_seed(training_args.seed ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. if model_args.config_name: UpperCAmelCase : Optional[int] = AutoConfig.from_pretrained(model_args.config_name , cache_dir=model_args.cache_dir ) elif model_args.model_name_or_path: UpperCAmelCase : Tuple = AutoConfig.from_pretrained(model_args.model_name_or_path , cache_dir=model_args.cache_dir ) else: UpperCAmelCase : Dict = CONFIG_MAPPING[model_args.model_type]() logger.warning("""You are instantiating a new config instance from scratch.""" ) if model_args.tokenizer_name: UpperCAmelCase : Any = AutoTokenizer.from_pretrained(model_args.tokenizer_name , cache_dir=model_args.cache_dir ) elif model_args.model_name_or_path: UpperCAmelCase : str = AutoTokenizer.from_pretrained(model_args.model_name_or_path , cache_dir=model_args.cache_dir ) else: raise ValueError( """You are instantiating a new tokenizer from scratch. This is not supported, but you can do it from another""" """ script, save it,and load it from here, using --tokenizer_name""" ) if model_args.model_name_or_path: UpperCAmelCase : List[str] = AutoModelWithLMHead.from_pretrained( model_args.model_name_or_path , from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) , config=UpperCamelCase , cache_dir=model_args.cache_dir , ) else: logger.info("""Training new model from scratch""" ) UpperCAmelCase : Optional[Any] = AutoModelWithLMHead.from_config(UpperCamelCase ) model.resize_token_embeddings(len(UpperCamelCase ) ) if config.model_type in ["bert", "roberta", "distilbert", "camembert"] and not data_args.mlm: raise ValueError( """BERT and RoBERTa-like models do not have LM heads but masked LM heads. They must be run using the""" """--mlm flag (masked language modeling).""" ) if data_args.block_size <= 0: UpperCAmelCase : Any = tokenizer.max_len # Our input block size will be the max possible for the model else: UpperCAmelCase : List[str] = min(data_args.block_size , tokenizer.max_len ) # Get datasets UpperCAmelCase : Optional[Any] = ( get_dataset(UpperCamelCase , tokenizer=UpperCamelCase , cache_dir=model_args.cache_dir ) if training_args.do_train else None ) UpperCAmelCase : Tuple = ( get_dataset(UpperCamelCase , tokenizer=UpperCamelCase , evaluate=UpperCamelCase , cache_dir=model_args.cache_dir ) if training_args.do_eval else None ) if config.model_type == "xlnet": UpperCAmelCase : Optional[int] = DataCollatorForPermutationLanguageModeling( tokenizer=UpperCamelCase , plm_probability=data_args.plm_probability , max_span_length=data_args.max_span_length , ) else: if data_args.mlm and data_args.whole_word_mask: UpperCAmelCase : List[str] = DataCollatorForWholeWordMask( tokenizer=UpperCamelCase , mlm_probability=data_args.mlm_probability ) else: UpperCAmelCase : int = DataCollatorForLanguageModeling( tokenizer=UpperCamelCase , mlm=data_args.mlm , mlm_probability=data_args.mlm_probability ) # Initialize our Trainer UpperCAmelCase : int = Trainer( model=UpperCamelCase , args=UpperCamelCase , data_collator=UpperCamelCase , train_dataset=UpperCamelCase , eval_dataset=UpperCamelCase , prediction_loss_only=UpperCamelCase , ) # Training if training_args.do_train: UpperCAmelCase : List[Any] = ( model_args.model_name_or_path if model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path ) else None ) trainer.train(model_path=UpperCamelCase ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_master(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation UpperCAmelCase : Any = {} if training_args.do_eval: logger.info("""*** Evaluate ***""" ) UpperCAmelCase : Tuple = trainer.evaluate() UpperCAmelCase : str = math.exp(eval_output["""eval_loss"""] ) UpperCAmelCase : Tuple = {"""perplexity""": perplexity} UpperCAmelCase : int = os.path.join(training_args.output_dir , """eval_results_lm.txt""" ) if trainer.is_world_master(): with open(UpperCamelCase , """w""" ) as writer: logger.info("""***** Eval results *****""" ) for key in sorted(result.keys() ): logger.info(""" %s = %s""" , UpperCamelCase , str(result[key] ) ) writer.write("""%s = %s\n""" % (key, str(result[key] )) ) results.update(UpperCamelCase ) return results def _snake_case ( UpperCamelCase : List[str] ): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
360
"""simple docstring""" from __future__ import annotations from decimal import Decimal from numpy import array def _snake_case ( UpperCamelCase : list[list[float]] ): UpperCAmelCase : int = Decimal # Check if the provided matrix has 2 rows and 2 columns # since this implementation only works for 2x2 matrices if len(UpperCamelCase ) == 2 and len(matrix[0] ) == 2 and len(matrix[1] ) == 2: # Calculate the determinant of the matrix UpperCAmelCase : Union[str, Any] = float( d(matrix[0][0] ) * d(matrix[1][1] ) - d(matrix[1][0] ) * d(matrix[0][1] ) ) if determinant == 0: raise ValueError("""This matrix has no inverse.""" ) # Creates a copy of the matrix with swapped positions of the elements UpperCAmelCase : Dict = [[0.0, 0.0], [0.0, 0.0]] UpperCAmelCase , UpperCAmelCase : Dict = matrix[1][1], matrix[0][0] UpperCAmelCase , UpperCAmelCase : Optional[Any] = -matrix[1][0], -matrix[0][1] # Calculate the inverse of the matrix return [ [(float(d(UpperCamelCase ) ) / determinant) or 0.0 for n in row] for row in swapped_matrix ] elif ( len(UpperCamelCase ) == 3 and len(matrix[0] ) == 3 and len(matrix[1] ) == 3 and len(matrix[2] ) == 3 ): # Calculate the determinant of the matrix using Sarrus rule UpperCAmelCase : Optional[int] = float( ( (d(matrix[0][0] ) * d(matrix[1][1] ) * d(matrix[2][2] )) + (d(matrix[0][1] ) * d(matrix[1][2] ) * d(matrix[2][0] )) + (d(matrix[0][2] ) * d(matrix[1][0] ) * d(matrix[2][1] )) ) - ( (d(matrix[0][2] ) * d(matrix[1][1] ) * d(matrix[2][0] )) + (d(matrix[0][1] ) * d(matrix[1][0] ) * d(matrix[2][2] )) + (d(matrix[0][0] ) * d(matrix[1][2] ) * d(matrix[2][1] )) ) ) if determinant == 0: raise ValueError("""This matrix has no inverse.""" ) # Creating cofactor matrix UpperCAmelCase : List[Any] = [ [d(0.0 ), d(0.0 ), d(0.0 )], [d(0.0 ), d(0.0 ), d(0.0 )], [d(0.0 ), d(0.0 ), d(0.0 )], ] UpperCAmelCase : Dict = (d(matrix[1][1] ) * d(matrix[2][2] )) - ( d(matrix[1][2] ) * d(matrix[2][1] ) ) UpperCAmelCase : List[Any] = -( (d(matrix[1][0] ) * d(matrix[2][2] )) - (d(matrix[1][2] ) * d(matrix[2][0] )) ) UpperCAmelCase : int = (d(matrix[1][0] ) * d(matrix[2][1] )) - ( d(matrix[1][1] ) * d(matrix[2][0] ) ) UpperCAmelCase : Dict = -( (d(matrix[0][1] ) * d(matrix[2][2] )) - (d(matrix[0][2] ) * d(matrix[2][1] )) ) UpperCAmelCase : Optional[int] = (d(matrix[0][0] ) * d(matrix[2][2] )) - ( d(matrix[0][2] ) * d(matrix[2][0] ) ) UpperCAmelCase : Optional[Any] = -( (d(matrix[0][0] ) * d(matrix[2][1] )) - (d(matrix[0][1] ) * d(matrix[2][0] )) ) UpperCAmelCase : Optional[Any] = (d(matrix[0][1] ) * d(matrix[1][2] )) - ( d(matrix[0][2] ) * d(matrix[1][1] ) ) UpperCAmelCase : str = -( (d(matrix[0][0] ) * d(matrix[1][2] )) - (d(matrix[0][2] ) * d(matrix[1][0] )) ) UpperCAmelCase : Optional[Any] = (d(matrix[0][0] ) * d(matrix[1][1] )) - ( d(matrix[0][1] ) * d(matrix[1][0] ) ) # Transpose the cofactor matrix (Adjoint matrix) UpperCAmelCase : Any = array(UpperCamelCase ) for i in range(3 ): for j in range(3 ): UpperCAmelCase : Optional[int] = cofactor_matrix[j][i] # Inverse of the matrix using the formula (1/determinant) * adjoint matrix UpperCAmelCase : int = array(UpperCamelCase ) for i in range(3 ): for j in range(3 ): inverse_matrix[i][j] /= d(UpperCamelCase ) # Calculate the inverse of the matrix return [[float(d(UpperCamelCase ) ) or 0.0 for n in row] for row in inverse_matrix] raise ValueError("""Please provide a matrix of size 2x2 or 3x3.""" )
76
0
from __future__ import annotations import inspect import unittest from typing import List, Tuple from transformers import RegNetConfig 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 TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class lowercase_ : '''simple docstring''' def __init__( self : Tuple , __UpperCAmelCase : List[Any] , __UpperCAmelCase : List[str]=3 , __UpperCAmelCase : Dict=32 , __UpperCAmelCase : int=3 , __UpperCAmelCase : Optional[Any]=10 , __UpperCAmelCase : str=[10, 20, 30, 40] , __UpperCAmelCase : Optional[int]=[1, 1, 2, 1] , __UpperCAmelCase : Optional[Any]=True , __UpperCAmelCase : Any=True , __UpperCAmelCase : int="relu" , __UpperCAmelCase : Dict=3 , __UpperCAmelCase : str=None , ) ->List[Any]: """simple docstring""" a = parent a = batch_size a = image_size a = num_channels a = embeddings_size a = hidden_sizes a = depths a = is_training a = use_labels a = hidden_act a = num_labels a = scope a = len(__UpperCAmelCase ) def __lowerCAmelCase ( self : Optional[Any] ) ->Tuple: """simple docstring""" 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.num_labels ) a = self.get_config() return config, pixel_values, labels def __lowerCAmelCase ( self : Optional[Any] ) ->str: """simple docstring""" return RegNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , ) def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : Tuple , __UpperCAmelCase : List[Any] , __UpperCAmelCase : Any ) ->List[Any]: """simple docstring""" a = TFRegNetModel(config=__UpperCAmelCase ) a = model(__UpperCAmelCase , training=__UpperCAmelCase ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : Any , __UpperCAmelCase : List[str] , __UpperCAmelCase : int ) ->Union[str, Any]: """simple docstring""" a = self.num_labels a = TFRegNetForImageClassification(__UpperCAmelCase ) a = model(__UpperCAmelCase , labels=__UpperCAmelCase , training=__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowerCAmelCase ( self : List[Any] ) ->Dict: """simple docstring""" a = self.prepare_config_and_inputs() a , a , a = config_and_inputs a = {'''pixel_values''': pixel_values} return config, inputs_dict @require_tf class lowercase_ ( lowercase , lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else () __snake_case = ( {'''feature-extraction''': TFRegNetModel, '''image-classification''': TFRegNetForImageClassification} if is_tf_available() else {} ) __snake_case = False __snake_case = False __snake_case = False __snake_case = False __snake_case = False def __lowerCAmelCase ( self : List[str] ) ->Union[str, Any]: """simple docstring""" a = TFRegNetModelTester(self ) a = ConfigTester(self , config_class=__UpperCAmelCase , has_text_modality=__UpperCAmelCase ) def __lowerCAmelCase ( self : Union[str, Any] ) ->Union[str, Any]: """simple docstring""" return @unittest.skip(reason='''RegNet does not use inputs_embeds''' ) def __lowerCAmelCase ( self : Tuple ) ->int: """simple docstring""" pass @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices('''GPU''' ) ) == 0 , reason='''TF does not support backprop for grouped convolutions on CPU.''' , ) @slow def __lowerCAmelCase ( self : List[Any] ) ->Any: """simple docstring""" super().test_keras_fit() @unittest.skip(reason='''RegNet does not support input and output embeddings''' ) def __lowerCAmelCase ( self : str ) ->Any: """simple docstring""" pass def __lowerCAmelCase ( self : int ) ->Union[str, Any]: """simple docstring""" a , a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a = model_class(__UpperCAmelCase ) 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] , __UpperCAmelCase ) def __lowerCAmelCase ( self : str ) ->str: """simple docstring""" a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__UpperCAmelCase ) def __lowerCAmelCase ( self : Dict ) ->Any: """simple docstring""" def check_hidden_states_output(__UpperCAmelCase : Dict , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Union[str, Any] ): a = model_class(__UpperCAmelCase ) a = model(**self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase ) , training=__UpperCAmelCase ) a = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states a = self.model_tester.num_stages self.assertEqual(len(__UpperCAmelCase ) , expected_num_stages + 1 ) # RegNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 2, self.model_tester.image_size // 2] , ) a , a = self.model_tester.prepare_config_and_inputs_for_common() a = ['''basic''', '''bottleneck'''] for model_class in self.all_model_classes: for layer_type in layers_type: a = layer_type a = True check_hidden_states_output(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] a = True check_hidden_states_output(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) def __lowerCAmelCase ( self : int ) ->List[str]: """simple docstring""" a , a = self.model_tester.prepare_config_and_inputs_for_common() def check_equivalence(__UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : str , __UpperCAmelCase : Tuple , __UpperCAmelCase : List[str]={} ): a = model(__UpperCAmelCase , return_dict=__UpperCAmelCase , **__UpperCAmelCase ) a = model(__UpperCAmelCase , return_dict=__UpperCAmelCase , **__UpperCAmelCase ).to_tuple() def recursive_check(__UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : int ): if isinstance(__UpperCAmelCase , (List, Tuple) ): for tuple_iterable_value, dict_iterable_value in zip(__UpperCAmelCase , __UpperCAmelCase ): recursive_check(__UpperCAmelCase , __UpperCAmelCase ) elif tuple_object is None: return else: self.assertTrue( all(tf.equal(__UpperCAmelCase , __UpperCAmelCase ) ) , msg=( '''Tuple and dict output are not equal. Difference:''' F""" {tf.math.reduce_max(tf.abs(tuple_object - dict_object ) )}""" ) , ) recursive_check(__UpperCAmelCase , __UpperCAmelCase ) for model_class in self.all_model_classes: a = model_class(__UpperCAmelCase ) a = self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase ) a = self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase ) check_equivalence(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) a = self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase , return_labels=__UpperCAmelCase ) a = self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase , return_labels=__UpperCAmelCase ) check_equivalence(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) a = self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase ) a = self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase ) check_equivalence(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , {'''output_hidden_states''': True} ) a = self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase , return_labels=__UpperCAmelCase ) a = self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase , return_labels=__UpperCAmelCase ) check_equivalence(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , {'''output_hidden_states''': True} ) def __lowerCAmelCase ( self : Tuple ) ->List[str]: """simple docstring""" a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__UpperCAmelCase ) @slow def __lowerCAmelCase ( self : Any ) ->Dict: """simple docstring""" for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a = TFRegNetModel.from_pretrained(__UpperCAmelCase ) self.assertIsNotNone(__UpperCAmelCase ) def _a ( ) -> Tuple: a = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_tf @require_vision class lowercase_ ( unittest.TestCase ): '''simple docstring''' @cached_property def __lowerCAmelCase ( self : Any ) ->Tuple: """simple docstring""" return ( AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def __lowerCAmelCase ( self : Optional[int] ) ->List[Any]: """simple docstring""" a = TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) a = self.default_image_processor a = prepare_img() a = image_processor(images=__UpperCAmelCase , return_tensors='''tf''' ) # forward pass a = model(**__UpperCAmelCase , training=__UpperCAmelCase ) # verify the logits a = tf.TensorShape((1, 1_000) ) self.assertEqual(outputs.logits.shape , __UpperCAmelCase ) a = tf.constant([-0.4180, -1.5051, -3.4836] ) tf.debugging.assert_near(outputs.logits[0, :3] , __UpperCAmelCase , atol=1e-4 )
0
def _a ( a :int = 100 ) -> int: a = n * (n + 1) * (2 * n + 1) / 6 a = (n * (n + 1) / 2) ** 2 return int(square_of_sum - sum_of_squares ) if __name__ == "__main__": print(f"""{solution() = }""")
0
1
"""simple docstring""" def a__ ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) -> Any: if index == r: for j in range(lowerCAmelCase ): print(data[j] , end=""" """ ) print(""" """ ) return # When no more elements are there to put in data[] if i >= n: return # current is included, put next at next location UpperCAmelCase__ : Tuple = arr[i] combination_util(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , index + 1 , lowerCAmelCase , i + 1 ) # current is excluded, replace it with # next (Note that i+1 is passed, but # index is not changed) combination_util(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , i + 1 ) # The main function that prints all combinations # of size r in arr[] of size n. This function # mainly uses combinationUtil() def a__ ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) -> Dict: # A temporary array to store all combination one by one UpperCAmelCase__ : Tuple = [0] * r # Print all combination using temporary array 'data[]' combination_util(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , 0 , lowerCAmelCase , 0 ) if __name__ == "__main__": # Driver code to check the function above _A = [10, 20, 30, 40, 50] print_combination(arr, len(arr), 3) # This code is contributed by Ambuj sahu
356
"""simple docstring""" import inspect import unittest import warnings from transformers import DeiTConfig from transformers.models.auto import get_values from transformers.testing_utils import ( require_accelerate, require_torch, require_torch_gpu, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_MAPPING, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, DeiTModel, ) from transformers.models.deit.modeling_deit import DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class lowerCamelCase : '''simple docstring''' def __init__(self , _lowerCamelCase , _lowerCamelCase=13 , _lowerCamelCase=30 , _lowerCamelCase=2 , _lowerCamelCase=3 , _lowerCamelCase=True , _lowerCamelCase=True , _lowerCamelCase=32 , _lowerCamelCase=5 , _lowerCamelCase=4 , _lowerCamelCase=37 , _lowerCamelCase="gelu" , _lowerCamelCase=0.1 , _lowerCamelCase=0.1 , _lowerCamelCase=10 , _lowerCamelCase=0.02 , _lowerCamelCase=3 , _lowerCamelCase=None , _lowerCamelCase=2 , ): """simple docstring""" UpperCAmelCase__ : Dict = parent UpperCAmelCase__ : str = batch_size UpperCAmelCase__ : Optional[int] = image_size UpperCAmelCase__ : Tuple = patch_size UpperCAmelCase__ : Any = num_channels UpperCAmelCase__ : Union[str, Any] = is_training UpperCAmelCase__ : Optional[int] = use_labels UpperCAmelCase__ : List[str] = hidden_size UpperCAmelCase__ : int = num_hidden_layers UpperCAmelCase__ : List[str] = num_attention_heads UpperCAmelCase__ : Dict = intermediate_size UpperCAmelCase__ : Optional[int] = hidden_act UpperCAmelCase__ : Any = hidden_dropout_prob UpperCAmelCase__ : Optional[Any] = attention_probs_dropout_prob UpperCAmelCase__ : Dict = type_sequence_label_size UpperCAmelCase__ : Optional[int] = initializer_range UpperCAmelCase__ : str = scope UpperCAmelCase__ : Optional[Any] = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) UpperCAmelCase__ : int = (image_size // patch_size) ** 2 UpperCAmelCase__ : Tuple = num_patches + 2 def _a (self ): """simple docstring""" UpperCAmelCase__ : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCAmelCase__ : Union[str, Any] = None if self.use_labels: UpperCAmelCase__ : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCAmelCase__ : int = self.get_config() return config, pixel_values, labels def _a (self ): """simple docstring""" 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=_lowerCamelCase , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def _a (self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): """simple docstring""" UpperCAmelCase__ : Tuple = DeiTModel(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() UpperCAmelCase__ : Union[str, Any] = model(_lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _a (self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): """simple docstring""" UpperCAmelCase__ : Optional[int] = DeiTForMaskedImageModeling(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() UpperCAmelCase__ : Optional[int] = model(_lowerCamelCase ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images UpperCAmelCase__ : str = 1 UpperCAmelCase__ : List[str] = DeiTForMaskedImageModeling(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() UpperCAmelCase__ : List[str] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) UpperCAmelCase__ : Dict = model(_lowerCamelCase ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def _a (self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): """simple docstring""" UpperCAmelCase__ : Optional[Any] = self.type_sequence_label_size UpperCAmelCase__ : List[str] = DeiTForImageClassification(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() UpperCAmelCase__ : str = model(_lowerCamelCase , labels=_lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images UpperCAmelCase__ : Union[str, Any] = 1 UpperCAmelCase__ : int = DeiTForImageClassification(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() UpperCAmelCase__ : Optional[int] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) UpperCAmelCase__ : Union[str, Any] = model(_lowerCamelCase , labels=_lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def _a (self ): """simple docstring""" UpperCAmelCase__ : List[Any] = self.prepare_config_and_inputs() ( ( UpperCAmelCase__ ) , ( UpperCAmelCase__ ) , ( UpperCAmelCase__ ) , ) : Tuple = config_and_inputs UpperCAmelCase__ : Optional[int] = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class lowerCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE = ( ( DeiTModel, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, ) if is_torch_available() else () ) SCREAMING_SNAKE_CASE = ( { 'feature-extraction': DeiTModel, 'image-classification': (DeiTForImageClassification, DeiTForImageClassificationWithTeacher), } if is_torch_available() else {} ) SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = False def _a (self ): """simple docstring""" UpperCAmelCase__ : Optional[int] = DeiTModelTester(self ) UpperCAmelCase__ : Optional[Any] = ConfigTester(self , config_class=_lowerCamelCase , has_text_modality=_lowerCamelCase , hidden_size=37 ) def _a (self ): """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason="""DeiT does not use inputs_embeds""" ) def _a (self ): """simple docstring""" pass def _a (self ): """simple docstring""" UpperCAmelCase__ , UpperCAmelCase__ : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase__ : Optional[Any] = model_class(_lowerCamelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) UpperCAmelCase__ : Optional[int] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_lowerCamelCase , nn.Linear ) ) def _a (self ): """simple docstring""" UpperCAmelCase__ , UpperCAmelCase__ : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase__ : Any = model_class(_lowerCamelCase ) UpperCAmelCase__ : Dict = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCAmelCase__ : Union[str, Any] = [*signature.parameters.keys()] UpperCAmelCase__ : str = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , _lowerCamelCase ) def _a (self ): """simple docstring""" UpperCAmelCase__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowerCamelCase ) def _a (self ): """simple docstring""" UpperCAmelCase__ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*_lowerCamelCase ) def _a (self ): """simple docstring""" UpperCAmelCase__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_lowerCamelCase ) def _a (self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase=False ): """simple docstring""" UpperCAmelCase__ : Optional[int] = super()._prepare_for_class(_lowerCamelCase , _lowerCamelCase , return_labels=_lowerCamelCase ) if return_labels: if model_class.__name__ == "DeiTForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def _a (self ): """simple docstring""" if not self.model_tester.is_training: return UpperCAmelCase__ , UpperCAmelCase__ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase__ : List[str] = True for model_class in self.all_model_classes: # DeiTForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(_lowerCamelCase ) or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue UpperCAmelCase__ : Dict = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.train() UpperCAmelCase__ : Any = self._prepare_for_class(_lowerCamelCase , _lowerCamelCase , return_labels=_lowerCamelCase ) UpperCAmelCase__ : int = model(**_lowerCamelCase ).loss loss.backward() def _a (self ): """simple docstring""" UpperCAmelCase__ , UpperCAmelCase__ : str = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return UpperCAmelCase__ : List[str] = False UpperCAmelCase__ : Optional[Any] = True for model_class in self.all_model_classes: if model_class in get_values(_lowerCamelCase ) or not model_class.supports_gradient_checkpointing: continue # DeiTForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "DeiTForImageClassificationWithTeacher": continue UpperCAmelCase__ : Optional[Any] = model_class(_lowerCamelCase ) model.gradient_checkpointing_enable() model.to(_lowerCamelCase ) model.train() UpperCAmelCase__ : Union[str, Any] = self._prepare_for_class(_lowerCamelCase , _lowerCamelCase , return_labels=_lowerCamelCase ) UpperCAmelCase__ : Tuple = model(**_lowerCamelCase ).loss loss.backward() def _a (self ): """simple docstring""" UpperCAmelCase__ , UpperCAmelCase__ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase__ : Optional[Any] = [ {"""title""": """multi_label_classification""", """num_labels""": 2, """dtype""": torch.float}, {"""title""": """single_label_classification""", """num_labels""": 1, """dtype""": torch.long}, {"""title""": """regression""", """num_labels""": 1, """dtype""": torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(_lowerCamelCase ), *get_values(_lowerCamelCase ), ] or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=F"""Testing {model_class} with {problem_type['title']}""" ): UpperCAmelCase__ : List[str] = problem_type["""title"""] UpperCAmelCase__ : List[Any] = problem_type["""num_labels"""] UpperCAmelCase__ : Optional[Any] = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.train() UpperCAmelCase__ : Any = self._prepare_for_class(_lowerCamelCase , _lowerCamelCase , return_labels=_lowerCamelCase ) if problem_type["num_labels"] > 1: UpperCAmelCase__ : Optional[int] = inputs["""labels"""].unsqueeze(1 ).repeat(1 , problem_type["""num_labels"""] ) UpperCAmelCase__ : str = inputs["""labels"""].to(problem_type["""dtype"""] ) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=_lowerCamelCase ) as warning_list: UpperCAmelCase__ : Any = model(**_lowerCamelCase ).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message ): raise ValueError( F"""Something is going wrong in the regression problem: intercepted {w.message}""" ) loss.backward() @slow def _a (self ): """simple docstring""" for model_name in DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase__ : int = DeiTModel.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) def a__ ( ) -> int: UpperCAmelCase__ : Optional[Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class lowerCamelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def _a (self ): """simple docstring""" return ( DeiTImageProcessor.from_pretrained("""facebook/deit-base-distilled-patch16-224""" ) if is_vision_available() else None ) @slow def _a (self ): """simple docstring""" UpperCAmelCase__ : int = DeiTForImageClassificationWithTeacher.from_pretrained("""facebook/deit-base-distilled-patch16-224""" ).to( _lowerCamelCase ) UpperCAmelCase__ : Union[str, Any] = self.default_image_processor UpperCAmelCase__ : Tuple = prepare_img() UpperCAmelCase__ : Tuple = image_processor(images=_lowerCamelCase , return_tensors="""pt""" ).to(_lowerCamelCase ) # forward pass with torch.no_grad(): UpperCAmelCase__ : Any = model(**_lowerCamelCase ) # verify the logits UpperCAmelCase__ : List[str] = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , _lowerCamelCase ) UpperCAmelCase__ : Dict = torch.tensor([-1.0_266, 0.1_912, -1.2_861] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _lowerCamelCase , atol=1e-4 ) ) @slow @require_accelerate @require_torch_gpu def _a (self ): """simple docstring""" UpperCAmelCase__ : List[str] = DeiTModel.from_pretrained( """facebook/deit-base-distilled-patch16-224""" , torch_dtype=torch.floataa , device_map="""auto""" ) UpperCAmelCase__ : Union[str, Any] = self.default_image_processor UpperCAmelCase__ : int = prepare_img() UpperCAmelCase__ : str = image_processor(images=_lowerCamelCase , return_tensors="""pt""" ) UpperCAmelCase__ : Dict = inputs.pixel_values.to(_lowerCamelCase ) # forward pass to make sure inference works in fp16 with torch.no_grad(): UpperCAmelCase__ : int = model(_lowerCamelCase )
166
0
"""simple docstring""" from importlib import import_module from .logging import get_logger lowercase_ = get_logger(__name__) class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a=None ): __a = attrs or [] if module is not None: for key in module.__dict__: if key in attrs or not key.startswith('''__''' ): setattr(self , _a , getattr(_a , _a ) ) __a = module._original_module if isinstance(_a , _PatchedModuleObj ) else module class __lowerCAmelCase : '''simple docstring''' __UpperCAmelCase : int = [] def __init__( self , _a , _a , _a , _a=None ): __a = obj __a = target __a = new __a = target.split('''.''' )[0] __a = {} __a = attrs or [] def __enter__( self ): *__a , __a = self.target.split('''.''' ) # Patch modules: # it's used to patch attributes of submodules like "os.path.join"; # in this case we need to patch "os" and "os.path" for i in range(len(_a ) ): try: __a = import_module('''.'''.join(submodules[: i + 1] ) ) except ModuleNotFoundError: continue # We iterate over all the globals in self.obj in case we find "os" or "os.path" for attr in self.obj.__dir__(): __a = getattr(self.obj , _a ) # We don't check for the name of the global, but rather if its value *is* "os" or "os.path". # This allows to patch renamed modules like "from os import path as ospath". if obj_attr is submodule or ( (isinstance(_a , _PatchedModuleObj ) and obj_attr._original_module is submodule) ): __a = obj_attr # patch at top level setattr(self.obj , _a , _PatchedModuleObj(_a , attrs=self.attrs ) ) __a = getattr(self.obj , _a ) # construct lower levels patches for key in submodules[i + 1 :]: setattr(_a , _a , _PatchedModuleObj(getattr(_a , _a , _a ) , attrs=self.attrs ) ) __a = getattr(_a , _a ) # finally set the target attribute setattr(_a , _a , self.new ) # Patch attribute itself: # it's used for builtins like "open", # and also to patch "os.path.join" we may also need to patch "join" # itself if it was imported as "from os.path import join". if submodules: # if it's an attribute of a submodule like "os.path.join" try: __a = getattr(import_module('''.'''.join(_a ) ) , _a ) except (AttributeError, ModuleNotFoundError): return # We iterate over all the globals in self.obj in case we find "os.path.join" for attr in self.obj.__dir__(): # We don't check for the name of the global, but rather if its value *is* "os.path.join". # This allows to patch renamed attributes like "from os.path import join as pjoin". if getattr(self.obj , _a ) is attr_value: __a = getattr(self.obj , _a ) setattr(self.obj , _a , self.new ) elif target_attr in globals()["__builtins__"]: # if it'a s builtin like "open" __a = globals()['''__builtins__'''][target_attr] setattr(self.obj , _a , self.new ) else: raise RuntimeError(f'''Tried to patch attribute {target_attr} instead of a submodule.''' ) def __exit__( self , *_a ): for attr in list(self.original ): setattr(self.obj , _a , self.original.pop(_a ) ) def __UpperCAmelCase ( self ): self.__enter__() self._active_patches.append(self ) def __UpperCAmelCase ( self ): try: self._active_patches.remove(self ) except ValueError: # If the patch hasn't been started this will fail return None return self.__exit__()
45
'''simple docstring''' def lowerCAmelCase_ ( snake_case_ : int , snake_case_ : int ) -> int: '''simple docstring''' return x if y == 0 else greatest_common_divisor(snake_case_ , x % y ) def lowerCAmelCase_ ( snake_case_ : int , snake_case_ : int ) -> int: '''simple docstring''' return (x * y) // greatest_common_divisor(snake_case_ , snake_case_ ) def lowerCAmelCase_ ( snake_case_ : int = 20 ) -> int: '''simple docstring''' UpperCAmelCase_ = 1 for i in range(1 , n + 1 ): UpperCAmelCase_ = lcm(snake_case_ , snake_case_ ) return g if __name__ == "__main__": print(f"{solution() = }")
1
0
import baseaa def __UpperCamelCase ( lowerCAmelCase__ : str ): return baseaa.baaencode(string.encode('''utf-8''' ) ) def __UpperCamelCase ( lowerCAmelCase__ : bytes ): return baseaa.baadecode(SCREAMING_SNAKE_CASE_ ).decode('''utf-8''' ) if __name__ == "__main__": lowercase__ ='Hello World!' lowercase__ =baseaa_encode(test) print(encoded) lowercase__ =baseaa_decode(encoded) print(decoded)
363
def __UpperCamelCase ( lowerCAmelCase__ : str , lowerCAmelCase__ : str ): __a : Any = len(lowerCAmelCase__ ) __a : Union[str, Any] = [] for i in range(len(lowerCAmelCase__ ) - pat_len + 1 ): __a : List[Any] = True for j in range(lowerCAmelCase__ ): if s[i + j] != pattern[j]: __a : Union[str, Any] = False break if match_found: position.append(lowerCAmelCase__ ) return position if __name__ == "__main__": assert naive_pattern_search('ABCDEFG', 'DE') == [3] print(naive_pattern_search('ABAAABCDBBABCDDEBCABC', 'ABC'))
90
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) lowerCAmelCase = { '''configuration_llama''': ['''LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''LlamaConfig'''], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase = ['''LlamaTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase = ['''LlamaTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase = [ '''LlamaForCausalLM''', '''LlamaModel''', '''LlamaPreTrainedModel''', '''LlamaForSequenceClassification''', ] if TYPE_CHECKING: from .configuration_llama import LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP, LlamaConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama import LlamaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama_fast import LlamaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_llama import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaPreTrainedModel else: import sys lowerCAmelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
110
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 lowerCamelCase : Any =logging.get_logger(__name__) class __a ( A__ ): _lowerCAmelCase : List[str] = ['''pixel_values'''] def __init__( self : List[str] , SCREAMING_SNAKE_CASE : bool = True , SCREAMING_SNAKE_CASE : Dict[str, int] = None , SCREAMING_SNAKE_CASE : PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE : bool = True , SCREAMING_SNAKE_CASE : Union[int, float] = 1 / 2_55 , SCREAMING_SNAKE_CASE : bool = True , SCREAMING_SNAKE_CASE : Dict[str, int] = None , SCREAMING_SNAKE_CASE : bool = True , **SCREAMING_SNAKE_CASE : Tuple , ): '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE ) UpperCamelCase__ : List[str] = size if size is not None else {"shortest_edge": 2_24} UpperCamelCase__ : Any = get_size_dict(SCREAMING_SNAKE_CASE , default_to_square=SCREAMING_SNAKE_CASE ) UpperCamelCase__ : List[Any] = crop_size if crop_size is not None else {"height": 2_56, "width": 2_56} UpperCamelCase__ : int = get_size_dict(SCREAMING_SNAKE_CASE , param_name="crop_size" ) UpperCamelCase__ : Dict = do_resize UpperCamelCase__ : List[str] = size UpperCamelCase__ : int = resample UpperCamelCase__ : Optional[int] = do_rescale UpperCamelCase__ : List[Any] = rescale_factor UpperCamelCase__ : Union[str, Any] = do_center_crop UpperCamelCase__ : int = crop_size UpperCamelCase__ : Optional[int] = do_flip_channel_order def __lowercase ( self : Optional[Any] , SCREAMING_SNAKE_CASE : np.ndarray , SCREAMING_SNAKE_CASE : Dict[str, int] , SCREAMING_SNAKE_CASE : PILImageResampling = PIL.Image.BILINEAR , SCREAMING_SNAKE_CASE : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE : Optional[Any] , ): '''simple docstring''' UpperCamelCase__ : Union[str, Any] = get_size_dict(SCREAMING_SNAKE_CASE , default_to_square=SCREAMING_SNAKE_CASE ) if "shortest_edge" not in size: raise ValueError(F'The `size` dictionary must contain the key `shortest_edge`. Got {size.keys()}' ) UpperCamelCase__ : Any = get_resize_output_image_size(SCREAMING_SNAKE_CASE , size=size["shortest_edge"] , default_to_square=SCREAMING_SNAKE_CASE ) return resize(SCREAMING_SNAKE_CASE , size=SCREAMING_SNAKE_CASE , resample=SCREAMING_SNAKE_CASE , data_format=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) def __lowercase ( self : Optional[int] , SCREAMING_SNAKE_CASE : np.ndarray , SCREAMING_SNAKE_CASE : Dict[str, int] , SCREAMING_SNAKE_CASE : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE : Optional[Any] , ): '''simple docstring''' UpperCamelCase__ : List[Any] = get_size_dict(SCREAMING_SNAKE_CASE ) 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(SCREAMING_SNAKE_CASE , size=(size["height"], size["width"]) , data_format=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) def __lowercase ( self : int , SCREAMING_SNAKE_CASE : np.ndarray , SCREAMING_SNAKE_CASE : Union[int, float] , SCREAMING_SNAKE_CASE : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE : Union[str, Any] , ): '''simple docstring''' return rescale(SCREAMING_SNAKE_CASE , scale=SCREAMING_SNAKE_CASE , data_format=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) def __lowercase ( self : Optional[int] , SCREAMING_SNAKE_CASE : np.ndarray , SCREAMING_SNAKE_CASE : Optional[Union[str, ChannelDimension]] = None ): '''simple docstring''' return flip_channel_order(SCREAMING_SNAKE_CASE , data_format=SCREAMING_SNAKE_CASE ) def __lowercase ( self : Optional[Any] , SCREAMING_SNAKE_CASE : ImageInput , SCREAMING_SNAKE_CASE : bool = None , SCREAMING_SNAKE_CASE : Dict[str, int] = None , SCREAMING_SNAKE_CASE : PILImageResampling = None , SCREAMING_SNAKE_CASE : bool = None , SCREAMING_SNAKE_CASE : float = None , SCREAMING_SNAKE_CASE : bool = None , SCREAMING_SNAKE_CASE : Dict[str, int] = None , SCREAMING_SNAKE_CASE : bool = None , SCREAMING_SNAKE_CASE : Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE : ChannelDimension = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE : Dict , ): '''simple docstring''' UpperCamelCase__ : List[str] = do_resize if do_resize is not None else self.do_resize UpperCamelCase__ : List[str] = resample if resample is not None else self.resample UpperCamelCase__ : Any = do_rescale if do_rescale is not None else self.do_rescale UpperCamelCase__ : Tuple = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCamelCase__ : Dict = do_center_crop if do_center_crop is not None else self.do_center_crop UpperCamelCase__ : Any = ( do_flip_channel_order if do_flip_channel_order is not None else self.do_flip_channel_order ) UpperCamelCase__ : Optional[int] = size if size is not None else self.size UpperCamelCase__ : List[str] = get_size_dict(SCREAMING_SNAKE_CASE , default_to_square=SCREAMING_SNAKE_CASE ) UpperCamelCase__ : Any = crop_size if crop_size is not None else self.crop_size UpperCamelCase__ : Union[str, Any] = get_size_dict(SCREAMING_SNAKE_CASE , param_name="crop_size" ) UpperCamelCase__ : int = make_list_of_images(SCREAMING_SNAKE_CASE ) if not valid_images(SCREAMING_SNAKE_CASE ): 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. UpperCamelCase__ : Tuple = [to_numpy_array(SCREAMING_SNAKE_CASE ) for image in images] if do_resize: UpperCamelCase__ : Optional[int] = [self.resize(image=SCREAMING_SNAKE_CASE , size=SCREAMING_SNAKE_CASE , resample=SCREAMING_SNAKE_CASE ) for image in images] if do_center_crop: UpperCamelCase__ : Any = [self.center_crop(image=SCREAMING_SNAKE_CASE , size=SCREAMING_SNAKE_CASE ) for image in images] if do_rescale: UpperCamelCase__ : str = [self.rescale(image=SCREAMING_SNAKE_CASE , scale=SCREAMING_SNAKE_CASE ) for image in images] # the pretrained checkpoints assume images are BGR, not RGB if do_flip_channel_order: UpperCamelCase__ : Any = [self.flip_channel_order(image=SCREAMING_SNAKE_CASE ) for image in images] UpperCamelCase__ : Optional[int] = [to_channel_dimension_format(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for image in images] UpperCamelCase__ : Optional[int] = {"pixel_values": images} return BatchFeature(data=SCREAMING_SNAKE_CASE , tensor_type=SCREAMING_SNAKE_CASE ) def __lowercase ( self : Dict , SCREAMING_SNAKE_CASE : List[Any] , SCREAMING_SNAKE_CASE : List[Tuple] = None ): '''simple docstring''' UpperCamelCase__ : Optional[int] = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(SCREAMING_SNAKE_CASE ) != len(SCREAMING_SNAKE_CASE ): raise ValueError( "Make sure that you pass in as many target sizes as the batch dimension of the logits" ) if is_torch_tensor(SCREAMING_SNAKE_CASE ): UpperCamelCase__ : Optional[Any] = target_sizes.numpy() UpperCamelCase__ : Any = [] for idx in range(len(SCREAMING_SNAKE_CASE ) ): UpperCamelCase__ : Optional[Any] = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode="bilinear" , align_corners=SCREAMING_SNAKE_CASE ) UpperCamelCase__ : List[str] = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(SCREAMING_SNAKE_CASE ) else: UpperCamelCase__ : List[str] = logits.argmax(dim=1 ) UpperCamelCase__ : Dict = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
189
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { # See all MEGATRON_BERT models at https://huggingface.co/models?filter=bert } class __snake_case ( _lowercase): snake_case__ : Tuple = "megatron-bert" def __init__( self : Dict , __lowerCAmelCase : Optional[Any]=2_9_0_5_6 , __lowerCAmelCase : str=1_0_2_4 , __lowerCAmelCase : Union[str, Any]=2_4 , __lowerCAmelCase : Tuple=1_6 , __lowerCAmelCase : List[Any]=4_0_9_6 , __lowerCAmelCase : Optional[int]="gelu" , __lowerCAmelCase : str=0.1 , __lowerCAmelCase : Dict=0.1 , __lowerCAmelCase : List[Any]=5_1_2 , __lowerCAmelCase : Dict=2 , __lowerCAmelCase : Any=0.02 , __lowerCAmelCase : Dict=1E-12 , __lowerCAmelCase : Optional[int]=0 , __lowerCAmelCase : Dict="absolute" , __lowerCAmelCase : Union[str, Any]=True , **__lowerCAmelCase : Tuple , ): """simple docstring""" super().__init__(pad_token_id=__lowerCAmelCase , **__lowerCAmelCase ) _lowerCamelCase : Optional[int] = vocab_size _lowerCamelCase : Union[str, Any] = hidden_size _lowerCamelCase : Any = num_hidden_layers _lowerCamelCase : Any = num_attention_heads _lowerCamelCase : Union[str, Any] = hidden_act _lowerCamelCase : List[str] = intermediate_size _lowerCamelCase : Any = hidden_dropout_prob _lowerCamelCase : List[str] = attention_probs_dropout_prob _lowerCamelCase : Union[str, Any] = max_position_embeddings _lowerCamelCase : int = type_vocab_size _lowerCamelCase : Dict = initializer_range _lowerCamelCase : int = layer_norm_eps _lowerCamelCase : Any = position_embedding_type _lowerCamelCase : Tuple = use_cache
175
"""simple docstring""" def snake_case_ ( A_ : list ): '''simple docstring''' _lowerCamelCase : Union[str, Any] = len(A_ ) for i in range(1, A_ ): _lowerCamelCase : Tuple = collection[i] _lowerCamelCase : Dict = 0 _lowerCamelCase : Any = i - 1 while low <= high: _lowerCamelCase : Optional[int] = (low + high) // 2 if val < collection[mid]: _lowerCamelCase : List[str] = mid - 1 else: _lowerCamelCase : Dict = mid + 1 for j in range(A_, A_, -1 ): _lowerCamelCase : Optional[int] = collection[j - 1] _lowerCamelCase : Tuple = val return collection if __name__ == "__main__": lowerCAmelCase__ = input('''Enter numbers separated by a comma:\n''').strip() lowerCAmelCase__ = [int(item) for item in user_input.split(''',''')] print(binary_insertion_sort(unsorted))
175
1
import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartaaTokenizer, MBartaaTokenizerFast, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, slow, ) from ...test_tokenization_common import TokenizerTesterMixin lowercase_ = get_tests_dir("fixtures/test_sentencepiece.model") if is_torch_available(): from transformers.models.mbart.modeling_mbart import shift_tokens_right lowercase_ = 250004 lowercase_ = 250020 @require_sentencepiece @require_tokenizers class A ( __A , unittest.TestCase ): """simple docstring""" lowerCamelCase = MBartaaTokenizer lowerCamelCase = MBartaaTokenizerFast lowerCamelCase = True lowerCamelCase = True def snake_case__ ( self : Any )-> int: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing A__ = MBartaaTokenizer(lowercase_,src_lang='en_XX',tgt_lang='ro_RO',keep_accents=lowercase_ ) tokenizer.save_pretrained(self.tmpdirname ) def snake_case__ ( self : Optional[Any] )-> List[str]: '''simple docstring''' A__ = "<s>" A__ = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowercase_ ),lowercase_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowercase_ ),lowercase_ ) def snake_case__ ( self : List[str] )-> Dict: '''simple docstring''' A__ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0],'<s>' ) self.assertEqual(vocab_keys[1],'<pad>' ) self.assertEqual(vocab_keys[-1],'<mask>' ) self.assertEqual(len(lowercase_ ),1_0_5_4 ) def snake_case__ ( self : Any )-> Tuple: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size,1_0_5_4 ) def snake_case__ ( self : List[str] )-> List[Any]: '''simple docstring''' A__ = MBartaaTokenizer(lowercase_,src_lang='en_XX',tgt_lang='ro_RO',keep_accents=lowercase_ ) A__ = tokenizer.tokenize('This is a test' ) self.assertListEqual(lowercase_,['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(lowercase_ ),[value + tokenizer.fairseq_offset for value in [2_8_5, 4_6, 1_0, 1_7_0, 3_8_2]],) A__ = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( lowercase_,[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(lowercase_ ) self.assertListEqual( lowercase_,[ value + tokenizer.fairseq_offset for value in [8, 2_1, 8_4, 5_5, 2_4, 1_9, 7, 2, 6_0_2, 3_4_7, 3_4_7, 3_4_7, 3, 1_2, 6_6, 4_6, 7_2, 8_0, 6, 2, 4] ],) A__ = tokenizer.convert_ids_to_tokens(lowercase_ ) self.assertListEqual( lowercase_,[SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.'],) @slow def snake_case__ ( self : Optional[Any] )-> Union[str, Any]: '''simple docstring''' A__ = {"input_ids": [[2_5_0_0_0_4, 1_1_0_6_2, 8_2_7_7_2, 7, 1_5, 8_2_7_7_2, 5_3_8, 5_1_5_2_9, 2_3_7, 1_7_1_9_8, 1_2_9_0, 2_0_6, 9, 2_1_5_1_7_5, 1_3_1_4, 1_3_6, 1_7_1_9_8, 1_2_9_0, 2_0_6, 9, 5_6_3_5_9, 4_2, 1_2_2_0_0_9, 9, 1_6_4_6_6, 1_6, 8_7_3_4_4, 4_5_3_7, 9, 4_7_1_7, 7_8_3_8_1, 6, 1_5_9_9_5_8, 7, 1_5, 2_4_4_8_0, 6_1_8, 4, 5_2_7, 2_2_6_9_3, 5_4_2_8, 4, 2_7_7_7, 2_4_4_8_0, 9_8_7_4, 4, 4_3_5_2_3, 5_9_4, 4, 8_0_3, 1_8_3_9_2, 3_3_1_8_9, 1_8, 4, 4_3_5_2_3, 2_4_4_4_7, 1_2_3_9_9, 1_0_0, 2_4_9_5_5, 8_3_6_5_8, 9_6_2_6, 1_4_4_0_5_7, 1_5, 8_3_9, 2_2_3_3_5, 1_6, 1_3_6, 2_4_9_5_5, 8_3_6_5_8, 8_3_4_7_9, 1_5, 3_9_1_0_2, 7_2_4, 1_6, 6_7_8, 6_4_5, 2_7_8_9, 1_3_2_8, 4_5_8_9, 4_2, 1_2_2_0_0_9, 1_1_5_7_7_4, 2_3, 8_0_5, 1_3_2_8, 4_6_8_7_6, 7, 1_3_6, 5_3_8_9_4, 1_9_4_0, 4_2_2_2_7, 4_1_1_5_9, 1_7_7_2_1, 8_2_3, 4_2_5, 4, 2_7_5_1_2, 9_8_7_2_2, 2_0_6, 1_3_6, 5_5_3_1, 4_9_7_0, 9_1_9, 1_7_3_3_6, 5, 2], [2_5_0_0_0_4, 2_0_0_8_0, 6_1_8, 8_3, 8_2_7_7_5, 4_7, 4_7_9, 9, 1_5_1_7, 7_3, 5_3_8_9_4, 3_3_3, 8_0_5_8_1, 1_1_0_1_1_7, 1_8_8_1_1, 5_2_5_6, 1_2_9_5, 5_1, 1_5_2_5_2_6, 2_9_7, 7_9_8_6, 3_9_0, 1_2_4_4_1_6, 5_3_8, 3_5_4_3_1, 2_1_4, 9_8, 1_5_0_4_4, 2_5_7_3_7, 1_3_6, 7_1_0_8, 4_3_7_0_1, 2_3, 7_5_6, 1_3_5_3_5_5, 7, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [2_5_0_0_0_4, 5_8_1, 6_3_7_7_3, 1_1_9_4_5_5, 6, 1_4_7_7_9_7, 8_8_2_0_3, 7, 6_4_5, 7_0, 2_1, 3_2_8_5, 1_0_2_6_9, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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=lowercase_,model_name='facebook/mbart-large-50',revision='d3913889c59cd5c9e456b269c376325eabad57e2',) def snake_case__ ( self : int )-> Optional[int]: '''simple docstring''' 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-mbart50", {}) 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(lowercase_,**lowercase_ ) A__ = self.tokenizer_class.from_pretrained(lowercase_,**lowercase_ ) A__ = tempfile.mkdtemp() A__ = tokenizer_r.save_pretrained(lowercase_ ) A__ = tokenizer_p.save_pretrained(lowercase_ ) # 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(lowercase_,lowercase_ ) # Checks everything loads correctly in the same way A__ = tokenizer_r.from_pretrained(lowercase_ ) A__ = tokenizer_p.from_pretrained(lowercase_ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(lowercase_,lowercase_ ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(lowercase_ ) # Save tokenizer rust, legacy_format=True A__ = tempfile.mkdtemp() A__ = tokenizer_r.save_pretrained(lowercase_,legacy_format=lowercase_ ) A__ = tokenizer_p.save_pretrained(lowercase_ ) # Checks it save with the same files self.assertSequenceEqual(lowercase_,lowercase_ ) # Checks everything loads correctly in the same way A__ = tokenizer_r.from_pretrained(lowercase_ ) A__ = tokenizer_p.from_pretrained(lowercase_ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(lowercase_,lowercase_ ) ) shutil.rmtree(lowercase_ ) # Save tokenizer rust, legacy_format=False A__ = tempfile.mkdtemp() A__ = tokenizer_r.save_pretrained(lowercase_,legacy_format=lowercase_ ) A__ = tokenizer_p.save_pretrained(lowercase_ ) # 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(lowercase_ ) A__ = tokenizer_p.from_pretrained(lowercase_ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(lowercase_,lowercase_ ) ) shutil.rmtree(lowercase_ ) @require_torch @require_sentencepiece @require_tokenizers class A ( unittest.TestCase ): """simple docstring""" lowerCamelCase = 'facebook/mbart-large-50-one-to-many-mmt' lowerCamelCase = [ ' 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.', ] lowerCamelCase = [ 'Ş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.', ] lowerCamelCase = [EN_CODE, 82_74, 12_78_73, 2_59_16, 7, 86_22, 20_71, 4_38, 6_74_85, 53, 18_78_95, 23, 5_17_12, 2] @classmethod def snake_case__ ( cls : Any )-> Dict: '''simple docstring''' A__ = MBartaaTokenizer.from_pretrained( cls.checkpoint_name,src_lang='en_XX',tgt_lang='ro_RO' ) A__ = 1 return cls def snake_case__ ( self : str )-> Optional[int]: '''simple docstring''' self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['ar_AR'],2_5_0_0_0_1 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['en_EN'],2_5_0_0_0_4 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['ro_RO'],2_5_0_0_2_0 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['mr_IN'],2_5_0_0_3_8 ) def snake_case__ ( self : Dict )-> Tuple: '''simple docstring''' A__ = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens,lowercase_ ) def snake_case__ ( self : Any )-> Optional[int]: '''simple docstring''' self.assertIn(lowercase_,self.tokenizer.all_special_ids ) A__ = [RO_CODE, 8_8_4, 9_0_1_9, 9_6, 9, 9_1_6, 8_6_7_9_2, 3_6, 1_8_7_4_3, 1_5_5_9_6, 5, 2] A__ = self.tokenizer.decode(lowercase_,skip_special_tokens=lowercase_ ) A__ = self.tokenizer.decode(generated_ids[1:],skip_special_tokens=lowercase_ ) self.assertEqual(lowercase_,lowercase_ ) self.assertNotIn(self.tokenizer.eos_token,lowercase_ ) def snake_case__ ( self : Union[str, Any] )-> List[str]: '''simple docstring''' A__ = ["this is gunna be a long sentence " * 2_0] assert isinstance(src_text[0],lowercase_ ) A__ = 1_0 A__ = self.tokenizer(lowercase_,max_length=lowercase_,truncation=lowercase_ ).input_ids[0] self.assertEqual(ids[0],lowercase_ ) self.assertEqual(ids[-1],2 ) self.assertEqual(len(lowercase_ ),lowercase_ ) def snake_case__ ( self : Optional[int] )-> Any: '''simple docstring''' self.assertListEqual(self.tokenizer.convert_tokens_to_ids(['<mask>', 'ar_AR'] ),[2_5_0_0_5_3, 2_5_0_0_0_1] ) def snake_case__ ( self : Tuple )-> List[Any]: '''simple docstring''' A__ = tempfile.mkdtemp() A__ = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(lowercase_ ) A__ = MBartaaTokenizer.from_pretrained(lowercase_ ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids,lowercase_ ) @require_torch def snake_case__ ( self : Dict )-> Union[str, Any]: '''simple docstring''' A__ = self.tokenizer(self.src_text,text_target=self.tgt_text,padding=lowercase_,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][0] == EN_CODE assert batch.input_ids[1][-1] == 2 assert batch.labels[1][0] == RO_CODE assert batch.labels[1][-1] == 2 assert batch.decoder_input_ids[1][:2].tolist() == [2, RO_CODE] @require_torch def snake_case__ ( self : List[Any] )-> Dict: '''simple docstring''' A__ = self.tokenizer( self.src_text,text_target=self.tgt_text,padding=lowercase_,truncation=lowercase_,max_length=len(self.expected_src_tokens ),return_tensors='pt',) A__ = shift_tokens_right(batch['labels'],self.tokenizer.pad_token_id ) self.assertIsInstance(lowercase_,lowercase_ ) self.assertEqual((2, 1_4),batch.input_ids.shape ) self.assertEqual((2, 1_4),batch.attention_mask.shape ) A__ = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens,lowercase_ ) self.assertEqual(2,batch.decoder_input_ids[0, 0] ) # decoder_start_token_id # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens,[EN_CODE] ) self.assertEqual(self.tokenizer.suffix_tokens,[self.tokenizer.eos_token_id] ) def snake_case__ ( self : int )-> Any: '''simple docstring''' A__ = self.tokenizer(self.src_text,padding=lowercase_,truncation=lowercase_,max_length=3,return_tensors='pt' ) A__ = self.tokenizer( text_target=self.tgt_text,padding=lowercase_,truncation=lowercase_,max_length=1_0,return_tensors='pt' ) A__ = targets["input_ids"] A__ = shift_tokens_right(lowercase_,self.tokenizer.pad_token_id ) self.assertEqual(batch.input_ids.shape[1],3 ) self.assertEqual(batch.decoder_input_ids.shape[1],1_0 ) @require_torch def snake_case__ ( self : int )-> str: '''simple docstring''' A__ = self.tokenizer._build_translation_inputs( 'A test',return_tensors='pt',src_lang='en_XX',tgt_lang='ar_AR' ) self.assertEqual( nested_simplify(lowercase_ ),{ # en_XX, A, test, EOS 'input_ids': [[2_5_0_0_0_4, 6_2, 3_0_3_4, 2]], 'attention_mask': [[1, 1, 1, 1]], # ar_AR 'forced_bos_token_id': 2_5_0_0_0_1, },)
7
from transformers import BertTokenizerFast from .custom_tokenization import CustomTokenizer class _UpperCamelCase ( __A ): '''simple docstring''' lowerCamelCase__ =CustomTokenizer pass
76
0
"""simple docstring""" import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing 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 # ######################################################################## __A = 16 __A = 32 def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 16 ) ->List[str]: """simple docstring""" lowerCAmelCase__ :Dict = AutoTokenizer.from_pretrained('bert-base-cased' ) lowerCAmelCase__ :Optional[int] = load_dataset('glue' , 'mrpc' ) def tokenize_function(_SCREAMING_SNAKE_CASE ): # max_length=None => use the model max length (it's actually the default) lowerCAmelCase__ :Optional[int] = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=_SCREAMING_SNAKE_CASE , max_length=_SCREAMING_SNAKE_CASE ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): lowerCAmelCase__ :Optional[Any] = datasets.map( _SCREAMING_SNAKE_CASE , batched=_SCREAMING_SNAKE_CASE , remove_columns=['idx', 'sentence1', 'sentence2'] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library lowerCAmelCase__ :Any = tokenized_datasets.rename_column('label' , 'labels' ) def collate_fn(_SCREAMING_SNAKE_CASE ): # On TPU it's best to pad everything to the same length or training will be very slow. lowerCAmelCase__ :Any = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": lowerCAmelCase__ :str = 16 elif accelerator.mixed_precision != "no": lowerCAmelCase__ :List[str] = 8 else: lowerCAmelCase__ :Union[str, Any] = None return tokenizer.pad( _SCREAMING_SNAKE_CASE , padding='longest' , max_length=_SCREAMING_SNAKE_CASE , pad_to_multiple_of=_SCREAMING_SNAKE_CASE , return_tensors='pt' , ) # Instantiate dataloaders. lowerCAmelCase__ :int = DataLoader( tokenized_datasets['train'] , shuffle=_SCREAMING_SNAKE_CASE , collate_fn=_SCREAMING_SNAKE_CASE , batch_size=_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Union[str, Any] = DataLoader( tokenized_datasets['validation'] , shuffle=_SCREAMING_SNAKE_CASE , collate_fn=_SCREAMING_SNAKE_CASE , batch_size=_SCREAMING_SNAKE_CASE ) return train_dataloader, eval_dataloader # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""", None) == "1": from accelerate.test_utils.training import mocked_dataloaders __A = mocked_dataloaders # noqa: F811 def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Optional[int]: """simple docstring""" if os.environ.get('TESTING_MOCKED_DATALOADERS' , _SCREAMING_SNAKE_CASE ) == "1": lowerCAmelCase__ :Tuple = 2 # Initialize accelerator lowerCAmelCase__ :int = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs lowerCAmelCase__ :Dict = config['lr'] lowerCAmelCase__ :Any = int(config['num_epochs'] ) lowerCAmelCase__ :Any = int(config['seed'] ) lowerCAmelCase__ :Optional[Any] = int(config['batch_size'] ) lowerCAmelCase__ :Dict = evaluate.load('glue' , 'mrpc' ) # If the batch size is too big we use gradient accumulation lowerCAmelCase__ :Optional[int] = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: lowerCAmelCase__ :Any = batch_size // MAX_GPU_BATCH_SIZE lowerCAmelCase__ :Dict = MAX_GPU_BATCH_SIZE set_seed(_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ , lowerCAmelCase__ :List[str] = get_dataloaders(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) lowerCAmelCase__ :Union[str, Any] = AutoModelForSequenceClassification.from_pretrained('bert-base-cased' , return_dict=_SCREAMING_SNAKE_CASE ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). lowerCAmelCase__ :Union[str, Any] = model.to(accelerator.device ) # Instantiate optimizer lowerCAmelCase__ :List[str] = AdamW(params=model.parameters() , lr=_SCREAMING_SNAKE_CASE ) # Instantiate scheduler lowerCAmelCase__ :Optional[Any] = get_linear_schedule_with_warmup( optimizer=_SCREAMING_SNAKE_CASE , num_warmup_steps=100 , num_training_steps=(len(_SCREAMING_SNAKE_CASE ) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Dict = accelerator.prepare( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Now we train the model for epoch in range(_SCREAMING_SNAKE_CASE ): model.train() for step, batch in enumerate(_SCREAMING_SNAKE_CASE ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) lowerCAmelCase__ :int = model(**_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Dict = outputs.loss lowerCAmelCase__ :Any = loss / gradient_accumulation_steps accelerator.backward(_SCREAMING_SNAKE_CASE ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() lowerCAmelCase__ :str = 0 for step, batch in enumerate(_SCREAMING_SNAKE_CASE ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): lowerCAmelCase__ :Optional[Any] = model(**_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ :Union[str, Any] = outputs.logits.argmax(dim=-1 ) lowerCAmelCase__ , lowerCAmelCase__ :Union[str, Any] = 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(_SCREAMING_SNAKE_CASE ) - 1: # Last batch needs to be truncated on distributed systems as it contains additional samples lowerCAmelCase__ :Tuple = predictions[: len(eval_dataloader.dataset ) - samples_seen] lowerCAmelCase__ :int = 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=_SCREAMING_SNAKE_CASE , references=_SCREAMING_SNAKE_CASE , ) lowerCAmelCase__ :Dict = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F"epoch {epoch}:" , _SCREAMING_SNAKE_CASE ) def __A () ->Optional[int]: """simple docstring""" lowerCAmelCase__ :List[str] = argparse.ArgumentParser(description='Simple example of training script.' ) parser.add_argument( '--mixed_precision' , type=_SCREAMING_SNAKE_CASE , default=_SCREAMING_SNAKE_CASE , choices=['no', 'fp16', 'bf16', 'fp8'] , help='Whether to use mixed precision. Choose' 'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.' 'and an Nvidia Ampere GPU.' , ) parser.add_argument('--cpu' , action='store_true' , help='If passed, will train on the CPU.' ) lowerCAmelCase__ :List[str] = parser.parse_args() lowerCAmelCase__ :Tuple = {'lr': 2e-5, 'num_epochs': 3, 'seed': 42, 'batch_size': 16} training_function(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
254
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer from .base import PipelineTool class _lowerCAmelCase ( a ): """simple docstring""" __magic_name__ :Tuple = """facebook/bart-large-mnli""" __magic_name__ :Any = ( """This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which """ """should be the text to classify, and `labels`, which should be the list of labels to use for classification. """ """It returns the most likely label in the list of provided `labels` for the input text.""" ) __magic_name__ :Optional[int] = """text_classifier""" __magic_name__ :List[Any] = AutoTokenizer __magic_name__ :str = AutoModelForSequenceClassification __magic_name__ :int = ["""text""", ["""text"""]] __magic_name__ :int = ["""text"""] def snake_case ( self ): '''simple docstring''' super().setup() lowerCAmelCase__ :Any = self.model.config lowerCAmelCase__ :Any = -1 for idx, label in config.idalabel.items(): if label.lower().startswith('entail' ): lowerCAmelCase__ :Optional[Any] = int(__UpperCAmelCase ) if self.entailment_id == -1: raise ValueError('Could not determine the entailment ID from the model config, please pass it at init.' ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Dict = labels return self.pre_processor( [text] * len(__UpperCAmelCase ) , [F"This example is {label}" for label in labels] , return_tensors='pt' , padding='max_length' , ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :List[str] = outputs.logits lowerCAmelCase__ :int = torch.argmax(logits[:, 2] ).item() return self._labels[label_id]
254
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) UpperCamelCase_ = {'''configuration_reformer''': ['''REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ReformerConfig''']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase_ = ['''ReformerTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase_ = ['''ReformerTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase_ = [ '''REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ReformerAttention''', '''ReformerForMaskedLM''', '''ReformerForQuestionAnswering''', '''ReformerForSequenceClassification''', '''ReformerLayer''', '''ReformerModel''', '''ReformerModelWithLMHead''', '''ReformerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_reformer import REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ReformerConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer import ReformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_reformer_fast import ReformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_reformer import ( REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ReformerAttention, ReformerForMaskedLM, ReformerForQuestionAnswering, ReformerForSequenceClassification, ReformerLayer, ReformerModel, ReformerModelWithLMHead, ReformerPreTrainedModel, ) else: import sys UpperCamelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
345
'''simple docstring''' import numpy as np from cva import COLOR_BGR2GRAY, CV_8UC3, cvtColor, filteraD, imread, imshow, waitKey def _A ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): """simple docstring""" if (ksize % 2) == 0: __lowercase =ksize + 1 __lowercase =np.zeros((ksize, ksize) , dtype=np.floataa ) # each value for y in range(_lowerCAmelCase ): for x in range(_lowerCAmelCase ): # distance from center __lowercase =x - ksize // 2 __lowercase =y - ksize // 2 # degree to radiant __lowercase =theta / 180 * np.pi __lowercase =np.cos(_theta ) __lowercase =np.sin(_theta ) # get kernel x __lowercase =cos_theta * px + sin_theta * py # get kernel y __lowercase =-sin_theta * px + cos_theta * py # fill kernel __lowercase =np.exp( -(_x**2 + gamma**2 * _y**2) / (2 * sigma**2) ) * np.cos(2 * np.pi * _x / lambd + psi ) return gabor if __name__ == "__main__": import doctest doctest.testmod() # read original image lowerCamelCase = imread("""../image_data/lena.jpg""") # turn image in gray scale value lowerCamelCase = cvtColor(img, COLOR_BGR2GRAY) # Apply multiple Kernel to detect edges lowerCamelCase = np.zeros(gray.shape[:2]) for theta in [0, 30, 60, 90, 120, 150]: lowerCamelCase = gabor_filter_kernel(10, 8, theta, 10, 0, 0) out += filteraD(gray, CV_8UC3, kernel_aa) lowerCamelCase = out / out.max() * 255 lowerCamelCase = out.astype(np.uinta) imshow("""Original""", gray) imshow("""Gabor filter with 20x20 mask and 6 directions""", out) waitKey(0)
166
0
'''simple docstring''' from __future__ import annotations import math def a ( __a , __a , __a , __a , __a ) -> int: '''simple docstring''' if depth < 0: raise ValueError('''Depth cannot be less than 0''' ) if not scores: raise ValueError('''Scores cannot be empty''' ) if depth == height: return scores[node_index] return ( max( minimax(depth + 1 , node_index * 2 , __a , __a , __a ) , minimax(depth + 1 , node_index * 2 + 1 , __a , __a , __a ) , ) if is_max else min( minimax(depth + 1 , node_index * 2 , __a , __a , __a ) , minimax(depth + 1 , node_index * 2 + 1 , __a , __a , __a ) , ) ) def a ( ) -> None: '''simple docstring''' UpperCamelCase__ :str = [90, 23, 6, 33, 21, 65, 123, 34423] UpperCamelCase__ :str = math.log(len(__a ) , 2 ) print(f'''Optimal value : {minimax(0 , 0 , __a , __a , __a )}''' ) if __name__ == "__main__": import doctest doctest.testmod() main()
368
'''simple docstring''' import collections import os from typing import List, Optional, Tuple from transformers.utils import is_jieba_available, requires_backends if is_jieba_available(): import jieba from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __snake_case = logging.get_logger(__name__) __snake_case = {'''vocab_file''': '''vocab.txt'''} __snake_case = { '''vocab_file''': { '''openbmb/cpm-ant-10b''': '''https://huggingface.co/openbmb/cpm-ant-10b/blob/main/vocab.txt''', }, } __snake_case = { '''openbmb/cpm-ant-10b''': 1024, } def a ( __a ) -> Tuple: '''simple docstring''' UpperCamelCase__ :List[str] = collections.OrderedDict() with open(__a , '''r''' , encoding='''utf-8''' ) as reader: UpperCamelCase__ :Dict = reader.readlines() for index, token in enumerate(__a ): UpperCamelCase__ :str = token.rstrip('''\n''' ) UpperCamelCase__ :Optional[int] = index return vocab class lowercase ( A__ ): """simple docstring""" def __init__( self , UpperCamelCase_ , UpperCamelCase_="<unk>" , UpperCamelCase_=200 ): '''simple docstring''' UpperCamelCase__ :Tuple = vocab UpperCamelCase__ :List[str] = unk_token UpperCamelCase__ :Tuple = max_input_chars_per_word def lowerCAmelCase__ ( self , UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ :Optional[int] = list(UpperCamelCase_ ) if len(UpperCamelCase_ ) > self.max_input_chars_per_word: return [self.unk_token] UpperCamelCase__ :List[Any] = 0 UpperCamelCase__ :str = [] while start < len(UpperCamelCase_ ): UpperCamelCase__ :int = len(UpperCamelCase_ ) UpperCamelCase__ :List[Any] = None while start < end: UpperCamelCase__ :int = ''''''.join(chars[start:end] ) if substr in self.vocab: UpperCamelCase__ :List[Any] = substr break end -= 1 if cur_substr is None: sub_tokens.append(self.unk_token ) start += 1 else: sub_tokens.append(UpperCamelCase_ ) UpperCamelCase__ :Any = end return sub_tokens class lowercase ( A__ ): """simple docstring""" _a = VOCAB_FILES_NAMES _a = PRETRAINED_VOCAB_FILES_MAP _a = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _a = ['input_ids', 'attention_mask'] _a = False def __init__( self , UpperCamelCase_ , UpperCamelCase_="<d>" , UpperCamelCase_="</d>" , UpperCamelCase_="<s>" , UpperCamelCase_="</s>" , UpperCamelCase_="<pad>" , UpperCamelCase_="<unk>" , UpperCamelCase_="</n>" , UpperCamelCase_="</_>" , UpperCamelCase_="left" , **UpperCamelCase_ , ): '''simple docstring''' requires_backends(self , ['''jieba'''] ) super().__init__( bod_token=UpperCamelCase_ , eod_token=UpperCamelCase_ , bos_token=UpperCamelCase_ , eos_token=UpperCamelCase_ , pad_token=UpperCamelCase_ , unk_token=UpperCamelCase_ , line_token=UpperCamelCase_ , space_token=UpperCamelCase_ , padding_side=UpperCamelCase_ , **UpperCamelCase_ , ) UpperCamelCase__ :Tuple = bod_token UpperCamelCase__ :Dict = eod_token UpperCamelCase__ :Optional[int] = load_vocab(UpperCamelCase_ ) UpperCamelCase__ :Tuple = self.encoder[space_token] UpperCamelCase__ :List[Any] = self.encoder[line_token] del self.encoder[space_token] del self.encoder[line_token] UpperCamelCase__ :Union[str, Any] = collections.OrderedDict(sorted(self.encoder.items() , key=lambda UpperCamelCase_ : x[1] ) ) UpperCamelCase__ :Union[str, Any] = {v: k for k, v in self.encoder.items()} UpperCamelCase__ :List[Any] = WordpieceTokenizer(vocab=self.encoder , unk_token=self.unk_token ) @property def lowerCAmelCase__ ( self ): '''simple docstring''' return self.encoder[self.bod_token] @property def lowerCAmelCase__ ( self ): '''simple docstring''' return self.encoder[self.eod_token] @property def lowerCAmelCase__ ( self ): '''simple docstring''' return self.encoder["\n"] @property def lowerCAmelCase__ ( self ): '''simple docstring''' return len(self.encoder ) def lowerCAmelCase__ ( self ): '''simple docstring''' return dict(self.encoder , **self.added_tokens_encoder ) def lowerCAmelCase__ ( self , UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ :List[Any] = [] for x in jieba.cut(UpperCamelCase_ , cut_all=UpperCamelCase_ ): output_tokens.extend(self.wordpiece_tokenizer.tokenize(UpperCamelCase_ ) ) return output_tokens def lowerCAmelCase__ ( self , UpperCamelCase_ , **UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ :List[Any] = [i for i in token_ids if i >= 0] UpperCamelCase__ :Optional[int] = [ x for x in token_ids if x != self.pad_token_id and x != self.eos_token_id and x != self.bos_token_id ] return super()._decode(UpperCamelCase_ , **UpperCamelCase_ ) def lowerCAmelCase__ ( self , UpperCamelCase_ ): '''simple docstring''' return token in self.encoder def lowerCAmelCase__ ( self , UpperCamelCase_ ): '''simple docstring''' return "".join(UpperCamelCase_ ) def lowerCAmelCase__ ( self , UpperCamelCase_ ): '''simple docstring''' return self.encoder.get(UpperCamelCase_ , self.encoder.get(self.unk_token ) ) def lowerCAmelCase__ ( self , UpperCamelCase_ ): '''simple docstring''' return self.decoder.get(UpperCamelCase_ , self.unk_token ) def lowerCAmelCase__ ( self , UpperCamelCase_ , UpperCamelCase_ = None ): '''simple docstring''' if os.path.isdir(UpperCamelCase_ ): UpperCamelCase__ :int = os.path.join( UpperCamelCase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) else: UpperCamelCase__ :str = (filename_prefix + '''-''' if filename_prefix else '''''') + save_directory UpperCamelCase__ :Any = 0 if " " in self.encoder: UpperCamelCase__ :Dict = self.encoder[''' '''] del self.encoder[" "] if "\n" in self.encoder: UpperCamelCase__ :List[str] = self.encoder['''\n'''] del self.encoder["\n"] UpperCamelCase__ :List[str] = collections.OrderedDict(sorted(self.encoder.items() , key=lambda UpperCamelCase_ : x[1] ) ) with open(UpperCamelCase_ , '''w''' , encoding='''utf-8''' ) as writer: for token, token_index in self.encoder.items(): if index != token_index: logger.warning( F'''Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive.''' ''' Please check that the vocabulary is not corrupted!''' ) UpperCamelCase__ :Any = token_index writer.write(token + '''\n''' ) index += 1 return (vocab_file,) def lowerCAmelCase__ ( self , UpperCamelCase_ , UpperCamelCase_ = None ): '''simple docstring''' if token_ids_a is None: return [self.bos_token_id] + token_ids_a return [self.bos_token_id] + token_ids_a + [self.bos_token_id] + token_ids_a def lowerCAmelCase__ ( self , UpperCamelCase_ , UpperCamelCase_ = None , UpperCamelCase_ = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=UpperCamelCase_ , token_ids_a=UpperCamelCase_ , already_has_special_tokens=UpperCamelCase_ ) if token_ids_a is not None: return [1] + ([0] * len(UpperCamelCase_ )) + [1] + ([0] * len(UpperCamelCase_ )) return [1] + ([0] * len(UpperCamelCase_ ))
219
0
"""simple docstring""" def _lowerCAmelCase ( UpperCamelCase_ ): __SCREAMING_SNAKE_CASE = int(UpperCamelCase_ ) if decimal in (0, 1): # Exit cases for the recursion return str(UpperCamelCase_ ) __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = divmod(UpperCamelCase_ , 2 ) return binary_recursive(UpperCamelCase_ ) + str(UpperCamelCase_ ) def _lowerCAmelCase ( UpperCamelCase_ ): __SCREAMING_SNAKE_CASE = str(UpperCamelCase_ ).strip() if not number: raise ValueError("""No input value was provided""" ) __SCREAMING_SNAKE_CASE = """-""" if number.startswith("""-""" ) else """""" __SCREAMING_SNAKE_CASE = number.lstrip("""-""" ) if not number.isnumeric(): raise ValueError("""Input value is not an integer""" ) return f"{negative}0b{binary_recursive(int(UpperCamelCase_ ) )}" if __name__ == "__main__": from doctest import testmod testmod()
100
from typing import List, Optional import numpy as np from ...processing_utils import ProcessorMixin from ...utils import to_numpy class __lowerCAmelCase ( __magic_name__ ): """simple docstring""" snake_case_ = '''EncodecFeatureExtractor''' snake_case_ = ('''T5Tokenizer''', '''T5TokenizerFast''') def __init__( self , lowerCamelCase__ , lowerCamelCase__ ) -> int: '''simple docstring''' super().__init__(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase = self.feature_extractor __lowerCamelCase = False def lowercase_ ( self , lowerCamelCase__=None , lowerCamelCase__=None , lowerCamelCase__=True ) -> List[Any]: '''simple docstring''' return self.tokenizer.get_decoder_prompt_ids(task=lowerCamelCase__ , language=lowerCamelCase__ , no_timestamps=lowerCamelCase__ ) def __call__( self , *lowerCamelCase__ , **lowerCamelCase__ ) -> Dict: '''simple docstring''' # For backward compatibility if self._in_target_context_manager: return self.current_processor(*lowerCamelCase__ , **lowerCamelCase__ ) __lowerCamelCase = kwargs.pop('audio' , lowerCamelCase__ ) __lowerCamelCase = kwargs.pop('sampling_rate' , lowerCamelCase__ ) __lowerCamelCase = kwargs.pop('text' , lowerCamelCase__ ) if len(lowerCamelCase__ ) > 0: __lowerCamelCase = args[0] __lowerCamelCase = args[1:] if audio is None and text is None: raise ValueError('You need to specify either an `audio` or `text` input to process.' ) if text is not None: __lowerCamelCase = self.tokenizer(lowerCamelCase__ , **lowerCamelCase__ ) if audio is not None: __lowerCamelCase = self.feature_extractor(lowerCamelCase__ , *lowerCamelCase__ , sampling_rate=lowerCamelCase__ , **lowerCamelCase__ ) if audio is None: return inputs elif text is None: return audio_inputs else: __lowerCamelCase = audio_inputs['input_values'] if "padding_mask" in audio_inputs: __lowerCamelCase = audio_inputs['padding_mask'] return inputs def lowercase_ ( self , *lowerCamelCase__ , **lowerCamelCase__ ) -> Union[str, Any]: '''simple docstring''' __lowerCamelCase = kwargs.pop('audio' , lowerCamelCase__ ) __lowerCamelCase = kwargs.pop('padding_mask' , lowerCamelCase__ ) if len(lowerCamelCase__ ) > 0: __lowerCamelCase = args[0] __lowerCamelCase = args[1:] if audio_values is not None: return self._decode_audio(lowerCamelCase__ , padding_mask=lowerCamelCase__ ) else: return self.tokenizer.batch_decode(*lowerCamelCase__ , **lowerCamelCase__ ) def lowercase_ ( self , *lowerCamelCase__ , **lowerCamelCase__ ) -> List[Any]: '''simple docstring''' return self.tokenizer.decode(*lowerCamelCase__ , **lowerCamelCase__ ) def lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__ = None ) -> List[np.ndarray]: '''simple docstring''' __lowerCamelCase = to_numpy(lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = audio_values.shape if padding_mask is None: return list(lowerCamelCase__ ) __lowerCamelCase = to_numpy(lowerCamelCase__ ) # match the sequence length of the padding mask to the generated audio arrays by padding with the **non-padding** # token (so that the generated audio values are **not** treated as padded tokens) __lowerCamelCase = seq_len - padding_mask.shape[-1] __lowerCamelCase = 1 - self.feature_extractor.padding_value __lowerCamelCase = np.pad(lowerCamelCase__ , ((0, 0), (0, difference)) , 'constant' , constant_values=lowerCamelCase__ ) __lowerCamelCase = audio_values.tolist() for i in range(lowerCamelCase__ ): __lowerCamelCase = np.asarray(audio_values[i] )[ padding_mask[i][None, :] != self.feature_extractor.padding_value ] __lowerCamelCase = sliced_audio.reshape(lowerCamelCase__ , -1 ) return audio_values
90
0
"""simple docstring""" from __future__ import annotations from typing import Dict from ...configuration_utils import PretrainedConfig _lowercase : int ={ "susnato/ernie-m-base_pytorch": "https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/config.json", "susnato/ernie-m-large_pytorch": "https://huggingface.co/susnato/ernie-m-large_pytorch/blob/main/config.json", } class snake_case__ (A__ ): """simple docstring""" __lowerCAmelCase :List[str] = "ernie_m" __lowerCAmelCase :Dict[str, str] = {"dropout": "classifier_dropout", "num_classes": "num_labels"} def __init__( self , __lowercase = 2_5_0_0_0_2 , __lowercase = 7_6_8 , __lowercase = 1_2 , __lowercase = 1_2 , __lowercase = 3_0_7_2 , __lowercase = "gelu" , __lowercase = 0.1 , __lowercase = 0.1 , __lowercase = 5_1_4 , __lowercase = 0.0_2 , __lowercase = 1 , __lowercase = 1E-05 , __lowercase=None , __lowercase=False , __lowercase=0.0 , **__lowercase , ) -> Any: """simple docstring""" super().__init__(pad_token_id=__lowercase , **__lowercase ) a__ : List[Any] = vocab_size a__ : int = hidden_size a__ : List[Any] = num_hidden_layers a__ : Tuple = num_attention_heads a__ : List[str] = intermediate_size a__ : Any = hidden_act a__ : str = hidden_dropout_prob a__ : Optional[int] = attention_probs_dropout_prob a__ : List[str] = max_position_embeddings a__ : List[Any] = initializer_range a__ : Union[str, Any] = layer_norm_eps a__ : Dict = classifier_dropout a__ : Dict = is_decoder a__ : Union[str, Any] = act_dropout
363
import argparse import json import os import torch from torch import nn from transformers import NllbMoeConfig, NllbMoeModel from transformers.modeling_utils import dtype_byte_size from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME def lowerCAmelCase_ ( _lowercase : List[str]) -> Union[str, Any]: """simple docstring""" a__ : List[str] = [ """encoder.version""", """decoder.version""", """model.encoder.version""", """model.decoder.version""", """decoder.output_projection.weight""", """_float_tensor""", """encoder.embed_positions._float_tensor""", """decoder.embed_positions._float_tensor""", ] for k in ignore_keys: state_dict.pop(_lowercase , _lowercase) def lowerCAmelCase_ ( _lowercase : List[Any]) -> Optional[Any]: """simple docstring""" a__ , a__ : Union[str, Any] = emb.weight.shape a__ : str = nn.Linear(_lowercase , _lowercase , bias=_lowercase) a__ : Any = emb.weight.data return lin_layer def lowerCAmelCase_ ( _lowercase : int , _lowercase : int=None) -> List[Any]: """simple docstring""" a__ : List[str] = {} for old_key in state_dict.keys(): a__ : Any = old_key if "moe_layer.experts." in key: if expert_idx is not None: a__ : Dict = key.replace("""moe_layer.experts.0""" , F'''ffn.experts.expert_{expert_idx}''') else: a__ : Optional[int] = key.replace("""moe_layer.experts.""" , """ffn.experts.expert_""") if "gate" in key: a__ : Tuple = key.replace(""".moe_layer.gate.wg""" , """.ffn.router.classifier""") if "fc2" and "experts" not in key: a__ : Optional[int] = key.replace(""".fc2.""" , """.ffn.fc2.""") if "fc1" and "experts" not in key: a__ : Optional[int] = key.replace(""".fc1.""" , """.ffn.fc1.""") if ".encoder_attn." in key: a__ : Tuple = key.replace(""".encoder_attn.""" , """.cross_attention.""") if "encoder_attn_layer_norm" in key: a__ : Optional[Any] = key.replace("""encoder_attn_layer_norm""" , """cross_attention_layer_norm""") if "final_layer_norm" in key: a__ : List[str] = key.replace("""final_layer_norm""" , """ff_layer_norm""") a__ : str = state_dict[old_key] return new_dict def lowerCAmelCase_ ( _lowercase : Tuple , _lowercase : Optional[int] , _lowercase : Any , _lowercase : Dict , _lowercase : str = WEIGHTS_NAME) -> Tuple: """simple docstring""" a__ : Tuple = [] a__ : Optional[Any] = 0 os.makedirs(_lowercase , exist_ok=_lowercase) for expert in range(_lowercase): a__ : str = switch_checkpoint_path + F'''-rank-{expert}.pt''' if os.path.isfile(_lowercase): a__ : List[str] = torch.load(_lowercase)["""model"""] remove_ignore_keys_(_lowercase) a__ : Tuple = rename_fairseq_keys(_lowercase , _lowercase) a__ : str = os.path.join( _lowercase , weights_name.replace(""".bin""" , F'''-{len(_lowercase)+1:05d}-of-???.bin''')) torch.save(_lowercase , _lowercase) sharded_state_dicts.append(expert_state.keys()) total_size += sum([value.numel() for key, value in expert_state.items()]) * dtype_byte_size( expert_state[list(_lowercase)[0]].dtype) # Add the last block a__ : int = os.path.join(_lowercase , weights_name.replace(""".bin""" , F'''-{len(_lowercase)+1:05d}-of-???.bin''')) a__ : Union[str, Any] = torch.load(switch_checkpoint_path + """-shared.pt""")["""model"""] remove_ignore_keys_(_lowercase) a__ : List[str] = rename_fairseq_keys(_lowercase , _lowercase) a__ : int = shared_weights["""decoder.embed_tokens.weight"""] sharded_state_dicts.append(shared_weights.keys()) # If we only have the shared weights (dummy model/experts saved on the same file) if len(_lowercase) == 1: a__ : Optional[int] = os.path.join(_lowercase , _lowercase) torch.save(_lowercase , _lowercase) return {weights_name: sharded_state_dicts[0]}, None else: torch.save(_lowercase , _lowercase) # Otherwise, let's build the index a__ : List[str] = {} for idx, shard in enumerate(_lowercase): a__ : Union[str, Any] = weights_name.replace(""".bin""" , F'''-{idx+1:05d}-of-{len(_lowercase):05d}.bin''') a__ : List[str] = os.path.join(_lowercase , weights_name.replace(""".bin""" , F'''-{idx+1:05d}-of-???.bin''')) os.rename(_lowercase , os.path.join(_lowercase , _lowercase)) for key in shard: a__ : Tuple = shard_file # Add the metadata a__ : Tuple = {"""total_size""": total_size} a__ : Optional[Any] = {"""metadata""": metadata, """weight_map""": weight_map} with open(os.path.join(_lowercase , _lowercase) , """w""" , encoding="""utf-8""") as f: a__ : Dict = json.dumps(_lowercase , indent=2 , sort_keys=_lowercase) + """\n""" f.write(_lowercase) return metadata, index if __name__ == "__main__": _lowercase : Any =argparse.ArgumentParser() # Required parameters parser.add_argument( "--nllb_moe_checkpoint_path", default="/home/arthur_huggingface_co/fairseq/weights/checkpoints/model_moe_54b/checkpoint_2_300000", type=str, required=False, help="Path to a directory containing a folder per layer. Follows the original Google format.", ) parser.add_argument("--dtype", default="float32", type=str, required=False, help="dtype of the saved model") parser.add_argument( "--pytorch_dump_folder_path", default="/home/arthur_huggingface_co/fairseq/weights/checkpoints/hf-converted-moe-54b", type=str, required=False, help="Path to the output pytorch model.", ) _lowercase : Tuple =parser.parse_args() _lowercase , _lowercase : List[Any] =shard_on_the_fly( args.nllb_moe_checkpoint_path, args.pytorch_dump_folder_path, 128, args.dtype, ) _lowercase : int =NllbMoeConfig.from_pretrained( "facebook/nllb-200-3.3B", encoder_sparse_step=4, decoder_sparse_step=4, num_experts=128 ) config.save_pretrained(args.pytorch_dump_folder_path) _lowercase : List[str] =NllbMoeModel.from_pretrained(args.pytorch_dump_folder_path) print("Done") model.save_pretrained(args.pytorch_dump_folder_path)
266
0
import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing the experiment tracking capability, # and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To help focus on the differences in the code, building `DataLoaders` # was refactored into its own function. # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## a_ = 16 a_ = 32 def __lowercase ( lowerCamelCase : Accelerator , lowerCamelCase : int = 16 ): UpperCamelCase_ : Tuple = AutoTokenizer.from_pretrained('bert-base-cased' ) UpperCamelCase_ : Tuple = load_dataset('glue' , 'mrpc' ) def tokenize_function(lowerCamelCase : List[Any] ): # max_length=None => use the model max length (it's actually the default) UpperCamelCase_ : int = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=lowerCamelCase , max_length=lowerCamelCase ) 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(): UpperCamelCase_ : Dict = datasets.map( lowerCamelCase , batched=lowerCamelCase , 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 UpperCamelCase_ : Union[str, Any] = tokenized_datasets.rename_column('label' , 'labels' ) def collate_fn(lowerCamelCase : Dict ): # On TPU it's best to pad everything to the same length or training will be very slow. UpperCamelCase_ : str = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": UpperCamelCase_ : Union[str, Any] = 16 elif accelerator.mixed_precision != "no": UpperCamelCase_ : Optional[Any] = 8 else: UpperCamelCase_ : List[Any] = None return tokenizer.pad( lowerCamelCase , padding='longest' , max_length=lowerCamelCase , pad_to_multiple_of=lowerCamelCase , return_tensors='pt' , ) # Instantiate dataloaders. UpperCamelCase_ : List[str] = DataLoader( tokenized_datasets['train'] , shuffle=lowerCamelCase , collate_fn=lowerCamelCase , batch_size=lowerCamelCase ) UpperCamelCase_ : Dict = DataLoader( tokenized_datasets['validation'] , shuffle=lowerCamelCase , collate_fn=lowerCamelCase , batch_size=lowerCamelCase ) 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 a_ = mocked_dataloaders # noqa: F811 def __lowercase ( lowerCamelCase : Any , lowerCamelCase : Union[str, Any] ): # For testing only if os.environ.get('TESTING_MOCKED_DATALOADERS' , lowerCamelCase ) == "1": UpperCamelCase_ : List[Any] = 2 # Initialize Accelerator # New Code # # We pass in "all" to `log_with` to grab all available trackers in the environment # Note: If using a custom `Tracker` class, should be passed in here such as: # >>> log_with = ["all", MyCustomTrackerClassInstance()] if args.with_tracking: UpperCamelCase_ : Tuple = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , log_with='all' , project_dir=args.project_dir ) else: UpperCamelCase_ : Optional[int] = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs UpperCamelCase_ : Union[str, Any] = config['lr'] UpperCamelCase_ : Optional[Any] = int(config['num_epochs'] ) UpperCamelCase_ : Optional[int] = int(config['seed'] ) UpperCamelCase_ : List[Any] = int(config['batch_size'] ) set_seed(lowerCamelCase ) UpperCamelCase_, UpperCamelCase_ : List[str] = get_dataloaders(lowerCamelCase , lowerCamelCase ) UpperCamelCase_ : Union[str, Any] = evaluate.load('glue' , 'mrpc' ) # If the batch size is too big we use gradient accumulation UpperCamelCase_ : Optional[int] = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: UpperCamelCase_ : Union[str, Any] = batch_size // MAX_GPU_BATCH_SIZE UpperCamelCase_ : Dict = MAX_GPU_BATCH_SIZE # Instantiate the model (we build the model here so that the seed also control new weights initialization) UpperCamelCase_ : Any = AutoModelForSequenceClassification.from_pretrained('bert-base-cased' , return_dict=lowerCamelCase ) # 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). UpperCamelCase_ : int = model.to(accelerator.device ) # Instantiate optimizer UpperCamelCase_ : List[str] = AdamW(params=model.parameters() , lr=lowerCamelCase ) # Instantiate scheduler UpperCamelCase_ : int = get_linear_schedule_with_warmup( optimizer=lowerCamelCase , num_warmup_steps=100 , num_training_steps=(len(lowerCamelCase ) * 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. UpperCamelCase_, UpperCamelCase_, UpperCamelCase_, UpperCamelCase_, UpperCamelCase_ : Dict = accelerator.prepare( lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ) # New Code # # We need to initialize the trackers we use. Overall configurations can also be stored if args.with_tracking: UpperCamelCase_ : Optional[Any] = os.path.split(lowerCamelCase )[-1].split('.' )[0] accelerator.init_trackers(lowerCamelCase , lowerCamelCase ) # Now we train the model for epoch in range(lowerCamelCase ): model.train() # New Code # # For our tracking example, we will log the total loss of each epoch if args.with_tracking: UpperCamelCase_ : Tuple = 0 for step, batch in enumerate(lowerCamelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) UpperCamelCase_ : str = model(**lowerCamelCase ) UpperCamelCase_ : Optional[Any] = outputs.loss # New Code # if args.with_tracking: total_loss += loss.detach().float() UpperCamelCase_ : Tuple = loss / gradient_accumulation_steps accelerator.backward(lowerCamelCase ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(lowerCamelCase ): # We could avoid this line since we set the accelerator with `device_placement=True` (the default). batch.to(accelerator.device ) with torch.no_grad(): UpperCamelCase_ : Any = model(**lowerCamelCase ) UpperCamelCase_ : int = outputs.logits.argmax(dim=-1 ) UpperCamelCase_, UpperCamelCase_ : Any = accelerator.gather_for_metrics((predictions, batch['labels']) ) metric.add_batch( predictions=lowerCamelCase , references=lowerCamelCase , ) UpperCamelCase_ : List[str] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F"epoch {epoch}:" , lowerCamelCase ) # New Code # # To actually log, we call `Accelerator.log` # The values passed can be of `str`, `int`, `float` or `dict` of `str` to `float`/`int` if args.with_tracking: accelerator.log( { 'accuracy': eval_metric['accuracy'], 'f1': eval_metric['f1'], 'train_loss': total_loss.item() / len(lowerCamelCase ), 'epoch': epoch, } , step=lowerCamelCase , ) # New Code # # When a run is finished, you should call `accelerator.end_training()` # to close all of the open trackers if args.with_tracking: accelerator.end_training() def __lowercase ( ): UpperCamelCase_ : str = argparse.ArgumentParser(description='Simple example of training script.' ) parser.add_argument( '--mixed_precision' , type=lowerCamelCase , default=lowerCamelCase , choices=['no', 'fp16', 'bf16', 'fp8'] , help='Whether to use mixed precision. Choose' 'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.' 'and an Nvidia Ampere GPU.' , ) parser.add_argument('--cpu' , action='store_true' , help='If passed, will train on the CPU.' ) parser.add_argument( '--with_tracking' , action='store_true' , help='Whether to load in all available experiment trackers from the environment and use them for logging.' , ) parser.add_argument( '--project_dir' , type=lowerCamelCase , default='logs' , help='Location on where to store experiment tracking logs` and relevent project information' , ) UpperCamelCase_ : Any = parser.parse_args() UpperCamelCase_ : Tuple = {'lr': 2e-5, 'num_epochs': 3, 'seed': 42, 'batch_size': 16} training_function(lowerCamelCase , lowerCamelCase ) if __name__ == "__main__": main()
175
import asyncio import os import shutil import subprocess import sys import tempfile import unittest from distutils.util import strtobool from functools import partial from pathlib import Path from typing import List, Union from unittest import mock import torch from ..state import AcceleratorState, PartialState from ..utils import ( gather, is_bnb_available, is_comet_ml_available, is_datasets_available, is_deepspeed_available, is_mps_available, is_safetensors_available, is_tensorboard_available, is_torch_version, is_tpu_available, is_transformers_available, is_wandb_available, is_xpu_available, ) def __lowercase ( lowerCamelCase : Dict , lowerCamelCase : int=False ): try: UpperCamelCase_ : Union[str, Any] = os.environ[key] except KeyError: # KEY isn't set, default to `default`. UpperCamelCase_ : List[str] = default else: # KEY is set, convert it to True or False. try: UpperCamelCase_ : Union[str, Any] = strtobool(lowerCamelCase ) except ValueError: # More values are supported, but let's keep the message simple. raise ValueError(F"If set, {key} must be yes or no." ) return _value a_ = parse_flag_from_env('RUN_SLOW', default=False) def __lowercase ( lowerCamelCase : List[Any] ): return unittest.skip('Test was skipped' )(lowerCamelCase ) def __lowercase ( lowerCamelCase : int ): return unittest.skipUnless(_run_slow_tests , 'test is slow' )(lowerCamelCase ) def __lowercase ( lowerCamelCase : str ): return unittest.skipUnless(not torch.cuda.is_available() , 'test requires only a CPU' )(lowerCamelCase ) def __lowercase ( lowerCamelCase : Optional[Any] ): return unittest.skipUnless(torch.cuda.is_available() , 'test requires a GPU' )(lowerCamelCase ) def __lowercase ( lowerCamelCase : Any ): return unittest.skipUnless(is_xpu_available() , 'test requires a XPU' )(lowerCamelCase ) def __lowercase ( lowerCamelCase : Any ): return unittest.skipUnless(is_mps_available() , 'test requires a `mps` backend support in `torch`' )(lowerCamelCase ) def __lowercase ( lowerCamelCase : str ): return unittest.skipUnless( is_transformers_available() and is_datasets_available() , 'test requires the Hugging Face suite' )(lowerCamelCase ) def __lowercase ( lowerCamelCase : List[str] ): return unittest.skipUnless(is_bnb_available() , 'test requires the bitsandbytes library' )(lowerCamelCase ) def __lowercase ( lowerCamelCase : str ): return unittest.skipUnless(is_tpu_available() , 'test requires TPU' )(lowerCamelCase ) def __lowercase ( lowerCamelCase : Tuple ): return unittest.skipUnless(torch.cuda.device_count() == 1 , 'test requires a GPU' )(lowerCamelCase ) def __lowercase ( lowerCamelCase : Tuple ): return unittest.skipUnless(torch.xpu.device_count() == 1 , 'test requires a XPU' )(lowerCamelCase ) def __lowercase ( lowerCamelCase : Optional[Any] ): return unittest.skipUnless(torch.cuda.device_count() > 1 , 'test requires multiple GPUs' )(lowerCamelCase ) def __lowercase ( lowerCamelCase : List[Any] ): return unittest.skipUnless(torch.xpu.device_count() > 1 , 'test requires multiple XPUs' )(lowerCamelCase ) def __lowercase ( lowerCamelCase : int ): return unittest.skipUnless(is_safetensors_available() , 'test requires safetensors' )(lowerCamelCase ) def __lowercase ( lowerCamelCase : Any ): return unittest.skipUnless(is_deepspeed_available() , 'test requires DeepSpeed' )(lowerCamelCase ) def __lowercase ( lowerCamelCase : Tuple ): return unittest.skipUnless(is_torch_version('>=' , '1.12.0' ) , 'test requires torch version >= 1.12.0' )(lowerCamelCase ) def __lowercase ( lowerCamelCase : List[Any]=None , lowerCamelCase : Optional[int]=None ): if test_case is None: return partial(lowerCamelCase , version=lowerCamelCase ) return unittest.skipUnless(is_torch_version('>=' , lowerCamelCase ) , F"test requires torch version >= {version}" )(lowerCamelCase ) def __lowercase ( lowerCamelCase : int ): return unittest.skipUnless(is_tensorboard_available() , 'test requires Tensorboard' )(lowerCamelCase ) def __lowercase ( lowerCamelCase : int ): return unittest.skipUnless(is_wandb_available() , 'test requires wandb' )(lowerCamelCase ) def __lowercase ( lowerCamelCase : Dict ): return unittest.skipUnless(is_comet_ml_available() , 'test requires comet_ml' )(lowerCamelCase ) a_ = ( any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available() ) def __lowercase ( lowerCamelCase : Dict ): return unittest.skipUnless( _atleast_one_tracker_available , 'test requires at least one tracker to be available and for `comet_ml` to not be installed' , )(lowerCamelCase ) class _lowercase ( unittest.TestCase ): lowercase = True @classmethod def SCREAMING_SNAKE_CASE__ ( cls : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" UpperCamelCase_ : str = tempfile.mkdtemp() @classmethod def SCREAMING_SNAKE_CASE__ ( cls : Any ) -> Union[str, Any]: """simple docstring""" if os.path.exists(cls.tmpdir ): shutil.rmtree(cls.tmpdir ) def SCREAMING_SNAKE_CASE__ ( self : str ) -> List[str]: """simple docstring""" if self.clear_on_setup: for path in Path(self.tmpdir ).glob('**/*' ): if path.is_file(): path.unlink() elif path.is_dir(): shutil.rmtree(snake_case ) class _lowercase ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> Any: """simple docstring""" super().tearDown() # Reset the state of the AcceleratorState singleton. AcceleratorState._reset_state() PartialState._reset_state() class _lowercase ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self : str , snake_case : Union[mock.Mock, List[mock.Mock]] ) -> Optional[int]: """simple docstring""" UpperCamelCase_ : str = mocks if isinstance(snake_case , (tuple, list) ) else [mocks] for m in self.mocks: m.start() self.addCleanup(m.stop ) def __lowercase ( lowerCamelCase : Optional[Any] ): UpperCamelCase_ : str = AcceleratorState() UpperCamelCase_ : str = tensor[None].clone().to(state.device ) UpperCamelCase_ : List[Any] = gather(lowerCamelCase ).cpu() UpperCamelCase_ : Tuple = tensor[0].cpu() for i in range(tensors.shape[0] ): if not torch.equal(tensors[i] , lowerCamelCase ): return False return True class _lowercase : def __init__( self : Optional[int] , snake_case : Any , snake_case : List[Any] , snake_case : int ) -> Optional[int]: """simple docstring""" UpperCamelCase_ : int = returncode UpperCamelCase_ : Optional[int] = stdout UpperCamelCase_ : Optional[int] = stderr async def __lowercase ( lowerCamelCase : Optional[Any] , lowerCamelCase : Tuple ): while True: UpperCamelCase_ : Tuple = await stream.readline() if line: callback(lowerCamelCase ) else: break async def __lowercase ( lowerCamelCase : Dict , lowerCamelCase : Dict=None , lowerCamelCase : Optional[Any]=None , lowerCamelCase : List[str]=None , lowerCamelCase : Dict=False , lowerCamelCase : Tuple=False ): if echo: print('\nRunning: ' , ' '.join(lowerCamelCase ) ) UpperCamelCase_ : Optional[int] = await asyncio.create_subprocess_exec( cmd[0] , *cmd[1:] , stdin=lowerCamelCase , stdout=asyncio.subprocess.PIPE , stderr=asyncio.subprocess.PIPE , env=lowerCamelCase , ) # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait # # If it starts hanging, will need to switch to the following code. The problem is that no data # will be seen until it's done and if it hangs for example there will be no debug info. # out, err = await p.communicate() # return _RunOutput(p.returncode, out, err) UpperCamelCase_ : str = [] UpperCamelCase_ : Union[str, Any] = [] def tee(lowerCamelCase : Tuple , lowerCamelCase : Optional[Any] , lowerCamelCase : Any , lowerCamelCase : List[str]="" ): UpperCamelCase_ : int = line.decode('utf-8' ).rstrip() sink.append(lowerCamelCase ) if not quiet: print(lowerCamelCase , lowerCamelCase , file=lowerCamelCase ) # XXX: the timeout doesn't seem to make any difference here await asyncio.wait( [ asyncio.create_task(_read_stream(p.stdout , lambda lowerCamelCase : tee(lowerCamelCase , lowerCamelCase , sys.stdout , label='stdout:' ) ) ), asyncio.create_task(_read_stream(p.stderr , lambda lowerCamelCase : tee(lowerCamelCase , lowerCamelCase , sys.stderr , label='stderr:' ) ) ), ] , timeout=lowerCamelCase , ) return _RunOutput(await p.wait() , lowerCamelCase , lowerCamelCase ) def __lowercase ( lowerCamelCase : List[Any] , lowerCamelCase : Optional[Any]=None , lowerCamelCase : int=None , lowerCamelCase : Any=180 , lowerCamelCase : Dict=False , lowerCamelCase : Optional[int]=True ): UpperCamelCase_ : str = asyncio.get_event_loop() UpperCamelCase_ : Union[str, Any] = loop.run_until_complete( _stream_subprocess(lowerCamelCase , env=lowerCamelCase , stdin=lowerCamelCase , timeout=lowerCamelCase , quiet=lowerCamelCase , echo=lowerCamelCase ) ) UpperCamelCase_ : int = ' '.join(lowerCamelCase ) if result.returncode > 0: UpperCamelCase_ : Dict = '\n'.join(result.stderr ) raise RuntimeError( F"'{cmd_str}' failed with returncode {result.returncode}\n\n" F"The combined stderr from workers follows:\n{stderr}" ) return result class _lowercase ( snake_case_ ): pass def __lowercase ( lowerCamelCase : List[str] , lowerCamelCase : Optional[int]=False ): try: UpperCamelCase_ : Any = subprocess.check_output(lowerCamelCase , stderr=subprocess.STDOUT ) if return_stdout: if hasattr(lowerCamelCase , 'decode' ): UpperCamelCase_ : Any = output.decode('utf-8' ) return output except subprocess.CalledProcessError as e: raise SubprocessCallException( F"Command `{' '.join(lowerCamelCase )}` failed with the following error:\n\n{e.output.decode()}" ) from e
175
1
"""simple docstring""" from __future__ import annotations from fractions import Fraction from math import gcd, sqrt def __UpperCAmelCase ( lowercase ): """simple docstring""" _UpperCAmelCase = int(number**0.5 ) return number == sq * sq def __UpperCAmelCase ( lowercase ,lowercase ,lowercase ,lowercase ,lowercase ,lowercase ): """simple docstring""" _UpperCAmelCase = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den _UpperCAmelCase = x_den * y_den * z_den _UpperCAmelCase = gcd(lowercase ,lowercase ) top //= hcf bottom //= hcf return top, bottom def __UpperCAmelCase ( lowercase = 35 ): """simple docstring""" _UpperCAmelCase = set() _UpperCAmelCase = 42 _UpperCAmelCase = Fraction(0 ) _UpperCAmelCase = 42 for x_num in range(1 ,order + 1 ): for x_den in range(x_num + 1 ,order + 1 ): for y_num in range(1 ,order + 1 ): for y_den in range(y_num + 1 ,order + 1 ): # n=1 _UpperCAmelCase = x_num * y_den + x_den * y_num _UpperCAmelCase = x_den * y_den _UpperCAmelCase = gcd(lowercase ,lowercase ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: _UpperCAmelCase = add_three( lowercase ,lowercase ,lowercase ,lowercase ,lowercase ,lowercase ) unique_s.add(lowercase ) # n=2 _UpperCAmelCase = ( x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num ) _UpperCAmelCase = x_den * x_den * y_den * y_den if is_sq(lowercase ) and is_sq(lowercase ): _UpperCAmelCase = int(sqrt(lowercase ) ) _UpperCAmelCase = int(sqrt(lowercase ) ) _UpperCAmelCase = gcd(lowercase ,lowercase ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: _UpperCAmelCase = add_three( lowercase ,lowercase ,lowercase ,lowercase ,lowercase ,lowercase ) unique_s.add(lowercase ) # n=-1 _UpperCAmelCase = x_num * y_num _UpperCAmelCase = x_den * y_num + x_num * y_den _UpperCAmelCase = gcd(lowercase ,lowercase ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: _UpperCAmelCase = add_three( lowercase ,lowercase ,lowercase ,lowercase ,lowercase ,lowercase ) unique_s.add(lowercase ) # n=2 _UpperCAmelCase = x_num * x_num * y_num * y_num _UpperCAmelCase = ( x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den ) if is_sq(lowercase ) and is_sq(lowercase ): _UpperCAmelCase = int(sqrt(lowercase ) ) _UpperCAmelCase = int(sqrt(lowercase ) ) _UpperCAmelCase = gcd(lowercase ,lowercase ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: _UpperCAmelCase = add_three( lowercase ,lowercase ,lowercase ,lowercase ,lowercase ,lowercase ) unique_s.add(lowercase ) for num, den in unique_s: total += Fraction(lowercase ,lowercase ) return total.denominator + total.numerator if __name__ == "__main__": print(F'''{solution() = }''')
30
"""simple docstring""" from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...utils import logging if TYPE_CHECKING: from ...processing_utils import ProcessorMixin from ...utils import TensorType UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = { """microsoft/layoutlmv3-base""": """https://huggingface.co/microsoft/layoutlmv3-base/resolve/main/config.json""", } class a ( lowerCAmelCase_ ): _snake_case : Any = 'layoutlmv3' def __init__( self : Optional[Any] , __lowerCAmelCase : Tuple=5_0265 , __lowerCAmelCase : Union[str, Any]=768 , __lowerCAmelCase : str=12 , __lowerCAmelCase : int=12 , __lowerCAmelCase : Any=3072 , __lowerCAmelCase : Any="gelu" , __lowerCAmelCase : Any=0.1 , __lowerCAmelCase : Tuple=0.1 , __lowerCAmelCase : Any=512 , __lowerCAmelCase : List[str]=2 , __lowerCAmelCase : Optional[Any]=0.02 , __lowerCAmelCase : Optional[int]=1e-5 , __lowerCAmelCase : int=1 , __lowerCAmelCase : Optional[Any]=0 , __lowerCAmelCase : Optional[Any]=2 , __lowerCAmelCase : List[str]=1024 , __lowerCAmelCase : Any=128 , __lowerCAmelCase : int=128 , __lowerCAmelCase : Tuple=True , __lowerCAmelCase : List[Any]=32 , __lowerCAmelCase : Any=128 , __lowerCAmelCase : int=64 , __lowerCAmelCase : List[str]=256 , __lowerCAmelCase : Union[str, Any]=True , __lowerCAmelCase : Any=True , __lowerCAmelCase : List[str]=True , __lowerCAmelCase : Optional[Any]=224 , __lowerCAmelCase : List[Any]=3 , __lowerCAmelCase : int=16 , __lowerCAmelCase : Optional[Any]=None , **__lowerCAmelCase : Union[str, Any] , ): super().__init__( vocab_size=__lowerCAmelCase , hidden_size=__lowerCAmelCase , num_hidden_layers=__lowerCAmelCase , num_attention_heads=__lowerCAmelCase , intermediate_size=__lowerCAmelCase , hidden_act=__lowerCAmelCase , hidden_dropout_prob=__lowerCAmelCase , attention_probs_dropout_prob=__lowerCAmelCase , max_position_embeddings=__lowerCAmelCase , type_vocab_size=__lowerCAmelCase , initializer_range=__lowerCAmelCase , layer_norm_eps=__lowerCAmelCase , pad_token_id=__lowerCAmelCase , bos_token_id=__lowerCAmelCase , eos_token_id=__lowerCAmelCase , **__lowerCAmelCase , ) _UpperCAmelCase = max_ad_position_embeddings _UpperCAmelCase = coordinate_size _UpperCAmelCase = shape_size _UpperCAmelCase = has_relative_attention_bias _UpperCAmelCase = rel_pos_bins _UpperCAmelCase = max_rel_pos _UpperCAmelCase = has_spatial_attention_bias _UpperCAmelCase = rel_ad_pos_bins _UpperCAmelCase = max_rel_ad_pos _UpperCAmelCase = text_embed _UpperCAmelCase = visual_embed _UpperCAmelCase = input_size _UpperCAmelCase = num_channels _UpperCAmelCase = patch_size _UpperCAmelCase = classifier_dropout class a ( lowerCAmelCase_ ): _snake_case : str = version.parse('1.12' ) @property def lowerCAmelCase_ ( self : Dict ): # The order of inputs is different for question answering and sequence classification if self.task in ["question-answering", "sequence-classification"]: return OrderedDict( [ ("""input_ids""", {0: """batch""", 1: """sequence"""}), ("""attention_mask""", {0: """batch""", 1: """sequence"""}), ("""bbox""", {0: """batch""", 1: """sequence"""}), ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) else: return OrderedDict( [ ("""input_ids""", {0: """batch""", 1: """sequence"""}), ("""bbox""", {0: """batch""", 1: """sequence"""}), ("""attention_mask""", {0: """batch""", 1: """sequence"""}), ("""pixel_values""", {0: """batch""", 1: """num_channels"""}), ] ) @property def lowerCAmelCase_ ( self : List[Any] ): return 1e-5 @property def lowerCAmelCase_ ( self : List[str] ): return 12 def lowerCAmelCase_ ( self : str , __lowerCAmelCase : "ProcessorMixin" , __lowerCAmelCase : int = -1 , __lowerCAmelCase : int = -1 , __lowerCAmelCase : bool = False , __lowerCAmelCase : Optional["TensorType"] = None , __lowerCAmelCase : int = 3 , __lowerCAmelCase : int = 40 , __lowerCAmelCase : int = 40 , ): setattr(processor.image_processor , """apply_ocr""" , __lowerCAmelCase ) # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX _UpperCAmelCase = compute_effective_axis_dimension( __lowerCAmelCase , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX _UpperCAmelCase = processor.tokenizer.num_special_tokens_to_add(__lowerCAmelCase ) _UpperCAmelCase = compute_effective_axis_dimension( __lowerCAmelCase , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=__lowerCAmelCase ) # Generate dummy inputs according to compute batch and sequence _UpperCAmelCase = [[""" """.join([processor.tokenizer.unk_token] ) * seq_length]] * batch_size # Generate dummy bounding boxes _UpperCAmelCase = [[[48, 84, 73, 128]]] * batch_size # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX # batch_size = compute_effective_axis_dimension(batch_size, fixed_dimension=OnnxConfig.default_fixed_batch) _UpperCAmelCase = self._generate_dummy_images(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) _UpperCAmelCase = dict( processor( __lowerCAmelCase , text=__lowerCAmelCase , boxes=__lowerCAmelCase , return_tensors=__lowerCAmelCase , ) ) return inputs
30
1
'''simple docstring''' from itertools import product def lowercase_ ( lowerCAmelCase__ : int , lowerCAmelCase__ : int ): """simple docstring""" __UpperCAmelCase : Optional[Any] = sides_number __UpperCAmelCase : int = max_face_number * dice_number __UpperCAmelCase : int = [0] * (max_total + 1) __UpperCAmelCase : Union[str, Any] = 1 __UpperCAmelCase : Any = range(lowerCAmelCase__ , max_face_number + 1 ) for dice_numbers in product(lowerCAmelCase__ , repeat=lowerCAmelCase__ ): __UpperCAmelCase : Optional[Any] = sum(lowerCAmelCase__ ) totals_frequencies[total] += 1 return totals_frequencies def lowercase_ ( ): """simple docstring""" __UpperCAmelCase : Dict = total_frequency_distribution( sides_number=4 , dice_number=9 ) __UpperCAmelCase : List[Any] = total_frequency_distribution( sides_number=6 , dice_number=6 ) __UpperCAmelCase : int = 0 __UpperCAmelCase : str = 9 __UpperCAmelCase : Dict = 4 * 9 __UpperCAmelCase : List[str] = 6 for peter_total in range(lowerCAmelCase__ , max_peter_total + 1 ): peter_wins_count += peter_totals_frequencies[peter_total] * sum( colin_totals_frequencies[min_colin_total:peter_total] ) __UpperCAmelCase : Optional[Any] = (4**9) * (6**6) __UpperCAmelCase : List[str] = peter_wins_count / total_games_number __UpperCAmelCase : List[str] = round(lowerCAmelCase__ , ndigits=7 ) return rounded_peter_win_probability if __name__ == "__main__": print(F'{solution() = }')
254
'''simple docstring''' from collections.abc import Sequence def lowercase_ ( lowerCAmelCase__ : Sequence[float] , lowerCAmelCase__ : float ): """simple docstring""" return sum(c * (x**i) for i, c in enumerate(lowerCAmelCase__ ) ) def lowercase_ ( lowerCAmelCase__ : Sequence[float] , lowerCAmelCase__ : float ): """simple docstring""" __UpperCAmelCase : Union[str, Any] = 0.0 for coeff in reversed(lowerCAmelCase__ ): __UpperCAmelCase : Union[str, Any] = result * x + coeff return result if __name__ == "__main__": _UpperCamelCase = (0.0, 0.0, 5.0, 9.3, 7.0) _UpperCamelCase = 10.0 print(evaluate_poly(poly, x)) print(horner(poly, x))
254
1
"""simple docstring""" from ....configuration_utils import PretrainedConfig from ....utils import logging __SCREAMING_SNAKE_CASE =logging.get_logger(__name__) # TODO: upload to AWS __SCREAMING_SNAKE_CASE ={ "yjernite/retribert-base-uncased": ( "https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/config.json" ), } class UpperCamelCase ( lowercase_ ): lowercase = 'retribert' def __init__( self ,__UpperCamelCase=3_0522 ,__UpperCamelCase=768 ,__UpperCamelCase=8 ,__UpperCamelCase=12 ,__UpperCamelCase=3072 ,__UpperCamelCase="gelu" ,__UpperCamelCase=0.1 ,__UpperCamelCase=0.1 ,__UpperCamelCase=512 ,__UpperCamelCase=2 ,__UpperCamelCase=0.02 ,__UpperCamelCase=1e-12 ,__UpperCamelCase=True ,__UpperCamelCase=128 ,__UpperCamelCase=0 ,**__UpperCamelCase ,) -> Dict: '''simple docstring''' super().__init__(pad_token_id=__UpperCamelCase ,**__UpperCamelCase ) lowercase_ : Optional[int] = vocab_size lowercase_ : Optional[int] = hidden_size lowercase_ : Any = num_hidden_layers lowercase_ : int = num_attention_heads lowercase_ : Optional[Any] = hidden_act lowercase_ : str = intermediate_size lowercase_ : Any = hidden_dropout_prob lowercase_ : Optional[int] = attention_probs_dropout_prob lowercase_ : Union[str, Any] = max_position_embeddings lowercase_ : Union[str, Any] = type_vocab_size lowercase_ : Optional[Any] = initializer_range lowercase_ : Optional[Any] = layer_norm_eps lowercase_ : Any = share_encoders lowercase_ : int = projection_dim
321
"""simple docstring""" import pickle import numpy as np from matplotlib import pyplot as plt class UpperCamelCase : def __init__( self ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase=0.2 ,__UpperCamelCase=0.2 ) -> Union[str, Any]: '''simple docstring''' lowercase_ : Optional[int] = bp_numa lowercase_ : Dict = bp_numa lowercase_ : Tuple = bp_numa lowercase_ : List[Any] = conva_get[:2] lowercase_ : int = conva_get[2] lowercase_ : Dict = size_pa lowercase_ : int = rate_w lowercase_ : Union[str, Any] = rate_t lowercase_ : Dict = [ np.mat(-1 * np.random.rand(self.conva[0] ,self.conva[0] ) + 0.5 ) for i in range(self.conva[1] ) ] lowercase_ : Union[str, Any] = np.mat(-1 * np.random.rand(self.num_bpa ,self.num_bpa ) + 0.5 ) lowercase_ : Union[str, Any] = np.mat(-1 * np.random.rand(self.num_bpa ,self.num_bpa ) + 0.5 ) lowercase_ : str = -2 * np.random.rand(self.conva[1] ) + 1 lowercase_ : Tuple = -2 * np.random.rand(self.num_bpa ) + 1 lowercase_ : Union[str, Any] = -2 * np.random.rand(self.num_bpa ) + 1 def _UpperCAmelCase ( self ,__UpperCamelCase ) -> Optional[int]: '''simple docstring''' lowercase_ : int = { 'num_bp1': self.num_bpa, 'num_bp2': self.num_bpa, 'num_bp3': self.num_bpa, 'conv1': self.conva, 'step_conv1': self.step_conva, 'size_pooling1': self.size_poolinga, 'rate_weight': self.rate_weight, 'rate_thre': self.rate_thre, 'w_conv1': self.w_conva, 'wkj': self.wkj, 'vji': self.vji, 'thre_conv1': self.thre_conva, 'thre_bp2': self.thre_bpa, 'thre_bp3': self.thre_bpa, } with open(__UpperCamelCase ,'wb' ) as f: pickle.dump(__UpperCamelCase ,__UpperCamelCase ) print(f'''Model saved: {save_path}''' ) @classmethod def _UpperCAmelCase ( cls ,__UpperCamelCase ) -> List[Any]: '''simple docstring''' with open(__UpperCamelCase ,'rb' ) as f: lowercase_ : Any = pickle.load(__UpperCamelCase ) # noqa: S301 lowercase_ : str = model_dic.get('conv1' ) conv_get.append(model_dic.get('step_conv1' ) ) lowercase_ : Union[str, Any] = model_dic.get('size_pooling1' ) lowercase_ : Optional[Any] = model_dic.get('num_bp1' ) lowercase_ : str = model_dic.get('num_bp2' ) lowercase_ : Optional[Any] = model_dic.get('num_bp3' ) lowercase_ : Union[str, Any] = model_dic.get('rate_weight' ) lowercase_ : Optional[int] = model_dic.get('rate_thre' ) # create model instance lowercase_ : Any = CNN(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) # modify model parameter lowercase_ : Optional[Any] = model_dic.get('w_conv1' ) lowercase_ : Tuple = model_dic.get('wkj' ) lowercase_ : Union[str, Any] = model_dic.get('vji' ) lowercase_ : Optional[Any] = model_dic.get('thre_conv1' ) lowercase_ : Dict = model_dic.get('thre_bp2' ) lowercase_ : Optional[int] = model_dic.get('thre_bp3' ) return conv_ins def _UpperCAmelCase ( self ,__UpperCamelCase ) -> Any: '''simple docstring''' return 1 / (1 + np.exp(-1 * x )) def _UpperCAmelCase ( self ,__UpperCamelCase ) -> Optional[int]: '''simple docstring''' return round(__UpperCamelCase ,3 ) def _UpperCAmelCase ( self ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> Tuple: '''simple docstring''' lowercase_ : Dict = convs[0] lowercase_ : Any = convs[1] lowercase_ : Optional[Any] = np.shape(__UpperCamelCase )[0] # get the data slice of original image data, data_focus lowercase_ : Tuple = [] for i_focus in range(0 ,size_data - size_conv + 1 ,__UpperCamelCase ): for j_focus in range(0 ,size_data - size_conv + 1 ,__UpperCamelCase ): lowercase_ : List[Any] = data[ i_focus : i_focus + size_conv, j_focus : j_focus + size_conv ] data_focus.append(__UpperCamelCase ) # calculate the feature map of every single kernel, and saved as list of matrix lowercase_ : Dict = [] lowercase_ : Dict = int((size_data - size_conv) / conv_step + 1 ) for i_map in range(__UpperCamelCase ): lowercase_ : Tuple = [] for i_focus in range(len(__UpperCamelCase ) ): lowercase_ : Optional[int] = ( np.sum(np.multiply(data_focus[i_focus] ,w_convs[i_map] ) ) - thre_convs[i_map] ) featuremap.append(self.sig(__UpperCamelCase ) ) lowercase_ : Optional[int] = np.asmatrix(__UpperCamelCase ).reshape( __UpperCamelCase ,__UpperCamelCase ) data_featuremap.append(__UpperCamelCase ) # expanding the data slice to One dimenssion lowercase_ : Optional[int] = [] for each_focus in data_focus: focusa_list.extend(self.Expand_Mat(__UpperCamelCase ) ) lowercase_ : str = np.asarray(__UpperCamelCase ) return focus_list, data_featuremap def _UpperCAmelCase ( self ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase="average_pool" ) -> Tuple: '''simple docstring''' lowercase_ : Union[str, Any] = len(featuremaps[0] ) lowercase_ : str = int(size_map / size_pooling ) lowercase_ : Optional[int] = [] for i_map in range(len(__UpperCamelCase ) ): lowercase_ : int = featuremaps[i_map] lowercase_ : List[str] = [] for i_focus in range(0 ,__UpperCamelCase ,__UpperCamelCase ): for j_focus in range(0 ,__UpperCamelCase ,__UpperCamelCase ): lowercase_ : List[str] = feature_map[ i_focus : i_focus + size_pooling, j_focus : j_focus + size_pooling, ] if pooling_type == "average_pool": # average pooling map_pooled.append(np.average(__UpperCamelCase ) ) elif pooling_type == "max_pooling": # max pooling map_pooled.append(np.max(__UpperCamelCase ) ) lowercase_ : Dict = np.asmatrix(__UpperCamelCase ).reshape(__UpperCamelCase ,__UpperCamelCase ) featuremap_pooled.append(__UpperCamelCase ) return featuremap_pooled def _UpperCAmelCase ( self ,__UpperCamelCase ) -> Any: '''simple docstring''' lowercase_ : Tuple = [] for i in range(len(__UpperCamelCase ) ): lowercase_ : Optional[Any] = np.shape(data[i] ) lowercase_ : List[str] = data[i].reshape(1 ,shapes[0] * shapes[1] ) lowercase_ : List[str] = data_listed.getA().tolist()[0] data_expanded.extend(__UpperCamelCase ) lowercase_ : int = np.asarray(__UpperCamelCase ) return data_expanded def _UpperCAmelCase ( self ,__UpperCamelCase ) -> int: '''simple docstring''' lowercase_ : Any = np.asarray(__UpperCamelCase ) lowercase_ : Any = np.shape(__UpperCamelCase ) lowercase_ : Optional[Any] = data_mat.reshape(1 ,shapes[0] * shapes[1] ) return data_expanded def _UpperCAmelCase ( self ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) -> str: '''simple docstring''' lowercase_ : Any = [] lowercase_ : List[Any] = 0 for i_map in range(__UpperCamelCase ): lowercase_ : List[str] = np.ones((size_map, size_map) ) for i in range(0 ,__UpperCamelCase ,__UpperCamelCase ): for j in range(0 ,__UpperCamelCase ,__UpperCamelCase ): lowercase_ : List[Any] = pd_pool[ i_pool ] lowercase_ : Any = i_pool + 1 lowercase_ : Optional[int] = np.multiply( __UpperCamelCase ,np.multiply(out_map[i_map] ,(1 - out_map[i_map]) ) ) pd_all.append(__UpperCamelCase ) return pd_all def _UpperCAmelCase ( self ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase=bool ) -> Optional[int]: '''simple docstring''' print('----------------------Start Training-------------------------' ) print((' - - Shape: Train_Data ', np.shape(__UpperCamelCase )) ) print((' - - Shape: Teach_Data ', np.shape(__UpperCamelCase )) ) lowercase_ : int = 0 lowercase_ : Tuple = [] lowercase_ : Tuple = 1_0000 while rp < n_repeat and mse >= error_accuracy: lowercase_ : List[str] = 0 print(f'''-------------Learning Time {rp}--------------''' ) for p in range(len(__UpperCamelCase ) ): # print('------------Learning Image: %d--------------'%p) lowercase_ : int = np.asmatrix(datas_train[p] ) lowercase_ : Any = np.asarray(datas_teach[p] ) lowercase_ , lowercase_ : Tuple = self.convolute( __UpperCamelCase ,self.conva ,self.w_conva ,self.thre_conva ,conv_step=self.step_conva ,) lowercase_ : Any = self.pooling(__UpperCamelCase ,self.size_poolinga ) lowercase_ : Optional[int] = np.shape(__UpperCamelCase ) lowercase_ : Optional[int] = self._expand(__UpperCamelCase ) lowercase_ : int = data_bp_input lowercase_ : Tuple = np.dot(__UpperCamelCase ,self.vji.T ) - self.thre_bpa lowercase_ : Dict = self.sig(__UpperCamelCase ) lowercase_ : int = np.dot(__UpperCamelCase ,self.wkj.T ) - self.thre_bpa lowercase_ : int = self.sig(__UpperCamelCase ) # --------------Model Leaning ------------------------ # calculate error and gradient--------------- lowercase_ : str = np.multiply( (data_teach - bp_outa) ,np.multiply(__UpperCamelCase ,(1 - bp_outa) ) ) lowercase_ : Optional[int] = np.multiply( np.dot(__UpperCamelCase ,self.wkj ) ,np.multiply(__UpperCamelCase ,(1 - bp_outa) ) ) lowercase_ : Any = np.dot(__UpperCamelCase ,self.vji ) lowercase_ : str = pd_i_all / (self.size_poolinga * self.size_poolinga) lowercase_ : Dict = pd_conva_pooled.T.getA().tolist() lowercase_ : List[Any] = self._calculate_gradient_from_pool( __UpperCamelCase ,__UpperCamelCase ,shape_featuremapa[0] ,shape_featuremapa[1] ,self.size_poolinga ,) # weight and threshold learning process--------- # convolution layer for k_conv in range(self.conva[1] ): lowercase_ : Optional[Any] = self._expand_mat(pd_conva_all[k_conv] ) lowercase_ : Dict = self.rate_weight * np.dot(__UpperCamelCase ,__UpperCamelCase ) lowercase_ : List[Any] = self.w_conva[k_conv] + delta_w.reshape( (self.conva[0], self.conva[0]) ) lowercase_ : Dict = ( self.thre_conva[k_conv] - np.sum(pd_conva_all[k_conv] ) * self.rate_thre ) # all connected layer lowercase_ : Optional[int] = self.wkj + pd_k_all.T * bp_outa * self.rate_weight lowercase_ : Any = self.vji + pd_j_all.T * bp_outa * self.rate_weight lowercase_ : str = self.thre_bpa - pd_k_all * self.rate_thre lowercase_ : Any = self.thre_bpa - pd_j_all * self.rate_thre # calculate the sum error of all single image lowercase_ : List[Any] = np.sum(abs(data_teach - bp_outa ) ) error_count += errors # print(' ----Teach ',data_teach) # print(' ----BP_output ',bp_out3) lowercase_ : int = rp + 1 lowercase_ : Union[str, Any] = error_count / patterns all_mse.append(__UpperCamelCase ) def draw_error(): lowercase_ : str = [error_accuracy for i in range(int(n_repeat * 1.2 ) )] plt.plot(__UpperCamelCase ,'+-' ) plt.plot(__UpperCamelCase ,'r--' ) plt.xlabel('Learning Times' ) plt.ylabel('All_mse' ) plt.grid(__UpperCamelCase ,alpha=0.5 ) plt.show() print('------------------Training Complished---------------------' ) print((' - - Training epoch: ', rp, f''' - - Mse: {mse:.6f}''') ) if draw_e: draw_error() return mse def _UpperCAmelCase ( self ,__UpperCamelCase ) -> Optional[int]: '''simple docstring''' lowercase_ : Union[str, Any] = [] print('-------------------Start Testing-------------------------' ) print((' - - Shape: Test_Data ', np.shape(__UpperCamelCase )) ) for p in range(len(__UpperCamelCase ) ): lowercase_ : List[Any] = np.asmatrix(datas_test[p] ) lowercase_ , lowercase_ : Optional[Any] = self.convolute( __UpperCamelCase ,self.conva ,self.w_conva ,self.thre_conva ,conv_step=self.step_conva ,) lowercase_ : List[Any] = self.pooling(__UpperCamelCase ,self.size_poolinga ) lowercase_ : List[str] = self._expand(__UpperCamelCase ) lowercase_ : Any = data_bp_input lowercase_ : Optional[Any] = bp_outa * self.vji.T - self.thre_bpa lowercase_ : str = self.sig(__UpperCamelCase ) lowercase_ : List[str] = bp_outa * self.wkj.T - self.thre_bpa lowercase_ : Optional[int] = self.sig(__UpperCamelCase ) produce_out.extend(bp_outa.getA().tolist() ) lowercase_ : List[str] = [list(map(self.do_round ,__UpperCamelCase ) ) for each in produce_out] return np.asarray(__UpperCamelCase ) def _UpperCAmelCase ( self ,__UpperCamelCase ) -> Optional[Any]: '''simple docstring''' lowercase_ : Optional[int] = np.asmatrix(__UpperCamelCase ) lowercase_ , lowercase_ : Union[str, Any] = self.convolute( __UpperCamelCase ,self.conva ,self.w_conva ,self.thre_conva ,conv_step=self.step_conva ,) lowercase_ : Optional[int] = self.pooling(__UpperCamelCase ,self.size_poolinga ) return data_conveda, data_pooleda if __name__ == "__main__": pass
321
1
from __future__ import annotations def A ( _lowercase , _lowercase = None , _lowercase = None , _lowercase = False , ): SCREAMING_SNAKE_CASE : Dict = cipher_alphabet or [chr(__UpperCamelCase ) for i in range(97 , 123 )] # If the argument is None or the user provided an empty dictionary if not frequencies_dict: # Frequencies of letters in the english language (how much they show up) SCREAMING_SNAKE_CASE : Dict = { '''a''': 0.0_8497, '''b''': 0.0_1492, '''c''': 0.0_2202, '''d''': 0.0_4253, '''e''': 0.1_1162, '''f''': 0.0_2228, '''g''': 0.0_2015, '''h''': 0.0_6094, '''i''': 0.0_7546, '''j''': 0.0_0153, '''k''': 0.0_1292, '''l''': 0.0_4025, '''m''': 0.0_2406, '''n''': 0.0_6749, '''o''': 0.0_7507, '''p''': 0.0_1929, '''q''': 0.0_0095, '''r''': 0.0_7587, '''s''': 0.0_6327, '''t''': 0.0_9356, '''u''': 0.0_2758, '''v''': 0.0_0978, '''w''': 0.0_2560, '''x''': 0.0_0150, '''y''': 0.0_1994, '''z''': 0.0_0077, } else: # Custom frequencies dictionary SCREAMING_SNAKE_CASE : Dict = frequencies_dict if not case_sensitive: SCREAMING_SNAKE_CASE : List[str] = ciphertext.lower() # Chi squared statistic values SCREAMING_SNAKE_CASE : Optional[int] = {} # cycle through all of the shifts for shift in range(len(__UpperCamelCase ) ): SCREAMING_SNAKE_CASE : str = '''''' # decrypt the message with the shift for letter in ciphertext: try: # Try to index the letter in the alphabet SCREAMING_SNAKE_CASE : Optional[int] = (alphabet_letters.index(letter.lower() ) - shift) % len( __UpperCamelCase ) decrypted_with_shift += ( alphabet_letters[new_key].upper() if case_sensitive and letter.isupper() else alphabet_letters[new_key] ) except ValueError: # Append the character if it isn't in the alphabet decrypted_with_shift += letter SCREAMING_SNAKE_CASE : Optional[Any] = 0.0 # Loop through each letter in the decoded message with the shift for letter in decrypted_with_shift: if case_sensitive: SCREAMING_SNAKE_CASE : Tuple = letter.lower() if letter in frequencies: # Get the amount of times the letter occurs in the message SCREAMING_SNAKE_CASE : Optional[int] = decrypted_with_shift.lower().count(__UpperCamelCase ) # Get the excepcted amount of times the letter should appear based # on letter frequencies SCREAMING_SNAKE_CASE : str = frequencies[letter] * occurrences # Complete the chi squared statistic formula SCREAMING_SNAKE_CASE : Optional[Any] = ((occurrences - expected) ** 2) / expected # Add the margin of error to the total chi squared statistic chi_squared_statistic += chi_letter_value else: if letter.lower() in frequencies: # Get the amount of times the letter occurs in the message SCREAMING_SNAKE_CASE : List[Any] = decrypted_with_shift.count(__UpperCamelCase ) # Get the excepcted amount of times the letter should appear based # on letter frequencies SCREAMING_SNAKE_CASE : Union[str, Any] = frequencies[letter] * occurrences # Complete the chi squared statistic formula SCREAMING_SNAKE_CASE : Any = ((occurrences - expected) ** 2) / expected # Add the margin of error to the total chi squared statistic chi_squared_statistic += chi_letter_value # Add the data to the chi_squared_statistic_values dictionary SCREAMING_SNAKE_CASE : Optional[Any] = ( chi_squared_statistic, decrypted_with_shift, ) # Get the most likely cipher by finding the cipher with the smallest chi squared # statistic def chi_squared_statistic_values_sorting_key(_lowercase ) -> tuple[float, str]: return chi_squared_statistic_values[key] SCREAMING_SNAKE_CASE : Dict = min( __UpperCamelCase , key=__UpperCamelCase , ) # Get all the data from the most likely cipher (key, decoded message) ( ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ) : List[Any] = chi_squared_statistic_values[most_likely_cipher] # Return the data on the most likely shift return ( most_likely_cipher, most_likely_cipher_chi_squared_value, decoded_most_likely_cipher, )
182
import gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaImgaImgPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class __snake_case ( lowerCamelCase_ , unittest.TestCase ): lowerCAmelCase_ = KandinskyVaaImgaImgPipeline lowerCAmelCase_ = ["image_embeds", "negative_image_embeds", "image"] lowerCAmelCase_ = [ "image_embeds", "negative_image_embeds", "image", ] lowerCAmelCase_ = [ "generator", "height", "width", "strength", "guidance_scale", "num_inference_steps", "return_dict", "guidance_scale", "num_images_per_prompt", "output_type", "return_dict", ] lowerCAmelCase_ = False @property def __a ( self : Union[str, Any] ): """simple docstring""" return 32 @property def __a ( self : Union[str, Any] ): """simple docstring""" return 32 @property def __a ( self : Optional[Any] ): """simple docstring""" return self.time_input_dim @property def __a ( self : Optional[int] ): """simple docstring""" return self.time_input_dim * 4 @property def __a ( self : List[str] ): """simple docstring""" return 1_00 @property def __a ( self : Union[str, Any] ): """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ = { """in_channels""": 4, # Out channels is double in channels because predicts mean and variance """out_channels""": 8, """addition_embed_type""": """image""", """down_block_types""": ("""ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D"""), """up_block_types""": ("""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""), """mid_block_type""": """UNetMidBlock2DSimpleCrossAttn""", """block_out_channels""": (self.block_out_channels_a, self.block_out_channels_a * 2), """layers_per_block""": 1, """encoder_hid_dim""": self.text_embedder_hidden_size, """encoder_hid_dim_type""": """image_proj""", """cross_attention_dim""": self.cross_attention_dim, """attention_head_dim""": 4, """resnet_time_scale_shift""": """scale_shift""", """class_embed_type""": None, } SCREAMING_SNAKE_CASE__ = UNetaDConditionModel(**_lowercase ) return model @property def __a ( self : str ): """simple docstring""" return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def __a ( self : Union[str, Any] ): """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ = VQModel(**self.dummy_movq_kwargs ) return model def __a ( self : Tuple ): """simple docstring""" SCREAMING_SNAKE_CASE__ = self.dummy_unet SCREAMING_SNAKE_CASE__ = self.dummy_movq SCREAMING_SNAKE_CASE__ = { """num_train_timesteps""": 10_00, """beta_schedule""": """linear""", """beta_start""": 0.0_00_85, """beta_end""": 0.0_12, """clip_sample""": False, """set_alpha_to_one""": False, """steps_offset""": 0, """prediction_type""": """epsilon""", """thresholding""": False, } SCREAMING_SNAKE_CASE__ = DDIMScheduler(**_lowercase ) SCREAMING_SNAKE_CASE__ = { """unet""": unet, """scheduler""": scheduler, """movq""": movq, } return components def __a ( self : Optional[Any] , _lowercase : Any , _lowercase : Tuple=0 ): """simple docstring""" SCREAMING_SNAKE_CASE__ = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(_lowercase ) ).to(_lowercase ) SCREAMING_SNAKE_CASE__ = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( _lowercase ) # create init_image SCREAMING_SNAKE_CASE__ = floats_tensor((1, 3, 64, 64) , rng=random.Random(_lowercase ) ).to(_lowercase ) SCREAMING_SNAKE_CASE__ = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE__ = Image.fromarray(np.uinta(_lowercase ) ).convert("""RGB""" ).resize((2_56, 2_56) ) if str(_lowercase ).startswith("""mps""" ): SCREAMING_SNAKE_CASE__ = torch.manual_seed(_lowercase ) else: SCREAMING_SNAKE_CASE__ = torch.Generator(device=_lowercase ).manual_seed(_lowercase ) SCREAMING_SNAKE_CASE__ = { """image""": init_image, """image_embeds""": image_embeds, """negative_image_embeds""": negative_image_embeds, """generator""": generator, """height""": 64, """width""": 64, """num_inference_steps""": 10, """guidance_scale""": 7.0, """strength""": 0.2, """output_type""": """np""", } return inputs def __a ( self : Optional[int] ): """simple docstring""" SCREAMING_SNAKE_CASE__ = """cpu""" SCREAMING_SNAKE_CASE__ = self.get_dummy_components() SCREAMING_SNAKE_CASE__ = self.pipeline_class(**_lowercase ) SCREAMING_SNAKE_CASE__ = pipe.to(_lowercase ) pipe.set_progress_bar_config(disable=_lowercase ) SCREAMING_SNAKE_CASE__ = pipe(**self.get_dummy_inputs(_lowercase ) ) SCREAMING_SNAKE_CASE__ = output.images SCREAMING_SNAKE_CASE__ = pipe( **self.get_dummy_inputs(_lowercase ) , return_dict=_lowercase , )[0] SCREAMING_SNAKE_CASE__ = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE__ = np.array( [0.6_19_97_78, 0.63_98_44_06, 0.46_14_57_85, 0.62_94_49_84, 0.5_62_22_15, 0.47_30_61_32, 0.47_44_14_56, 0.4_60_76_06, 0.48_71_92_63] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 ), f""" expected_slice {expected_slice}, but got {image_slice.flatten()}""" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 ), f""" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}""" @slow @require_torch_gpu class __snake_case ( unittest.TestCase ): def __a ( self : Optional[int] ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __a ( self : Optional[int] ): """simple docstring""" SCREAMING_SNAKE_CASE__ = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinskyv22/kandinskyv22_img2img_frog.npy""" ) SCREAMING_SNAKE_CASE__ = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/cat.png""" ) SCREAMING_SNAKE_CASE__ = """A red cartoon frog, 4k""" SCREAMING_SNAKE_CASE__ = KandinskyVaaPriorPipeline.from_pretrained( """kandinsky-community/kandinsky-2-2-prior""" , torch_dtype=torch.floataa ) pipe_prior.to(_lowercase ) SCREAMING_SNAKE_CASE__ = KandinskyVaaImgaImgPipeline.from_pretrained( """kandinsky-community/kandinsky-2-2-decoder""" , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ = pipeline.to(_lowercase ) pipeline.set_progress_bar_config(disable=_lowercase ) SCREAMING_SNAKE_CASE__ = torch.Generator(device="""cpu""" ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = pipe_prior( _lowercase , generator=_lowercase , num_inference_steps=5 , negative_prompt="""""" , ).to_tuple() SCREAMING_SNAKE_CASE__ = pipeline( image=_lowercase , image_embeds=_lowercase , negative_image_embeds=_lowercase , generator=_lowercase , num_inference_steps=1_00 , height=7_68 , width=7_68 , strength=0.2 , output_type="""np""" , ) SCREAMING_SNAKE_CASE__ = output.images[0] assert image.shape == (7_68, 7_68, 3) assert_mean_pixel_difference(_lowercase , _lowercase )
219
0
'''simple docstring''' 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 __magic_name__ ( __UpperCAmelCase ) -> int: '''simple docstring''' return 1.0 / (1.0 + np.exp(-_outputs )) def __magic_name__ ( __UpperCAmelCase ) -> List[Any]: '''simple docstring''' snake_case_ = np.max(_outputs, axis=-1, keepdims=__a ) snake_case_ = np.exp(_outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1, keepdims=__a ) class a ( __lowercase ): snake_case_ = "sigmoid" snake_case_ = "softmax" snake_case_ = "none" @add_end_docstrings( __lowercase , 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 a ( __lowercase ): snake_case_ = False snake_case_ = ClassificationFunction.NONE def __init__( self : Union[str, Any] , **lowercase_ : 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 A_ ( self : Any , lowercase_ : Dict=None , lowercase_ : Optional[Any]=None , lowercase_ : Optional[Any]="" , **lowercase_ : Optional[int] ): # Using "" as default argument because we're going to use `top_k=None` in user code to declare # "No top_k" snake_case_ = tokenizer_kwargs snake_case_ = {} if hasattr(self.model.config , '''return_all_scores''' ) and return_all_scores is None: snake_case_ = self.model.config.return_all_scores if isinstance(_a , _a ) or top_k is None: snake_case_ = top_k snake_case_ = 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: snake_case_ = None else: snake_case_ = 1 if isinstance(_a , _a ): snake_case_ = ClassificationFunction[function_to_apply.upper()] if function_to_apply is not None: snake_case_ = function_to_apply return preprocess_params, {}, postprocess_params def __call__( self : Union[str, Any] , *lowercase_ : Union[str, Any] , **lowercase_ : Any ): snake_case_ = super().__call__(*_a , **_a ) # TODO try and retrieve it in a nicer way from _sanitize_parameters. snake_case_ = '''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 A_ ( self : Dict , lowercase_ : int , **lowercase_ : List[Any] ): snake_case_ = 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 A_ ( self : Optional[Any] , lowercase_ : List[Any] ): return self.model(**_a ) def A_ ( self : int , lowercase_ : Union[str, Any] , lowercase_ : Union[str, Any]=None , lowercase_ : str=1 , lowercase_ : Union[str, Any]=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: snake_case_ = ClassificationFunction.SIGMOID elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1: snake_case_ = ClassificationFunction.SOFTMAX elif hasattr(self.model.config , '''function_to_apply''' ) and function_to_apply is None: snake_case_ = self.model.config.function_to_apply else: snake_case_ = ClassificationFunction.NONE snake_case_ = model_outputs['''logits'''][0] snake_case_ = outputs.numpy() if function_to_apply == ClassificationFunction.SIGMOID: snake_case_ = sigmoid(_a ) elif function_to_apply == ClassificationFunction.SOFTMAX: snake_case_ = softmax(_a ) elif function_to_apply == ClassificationFunction.NONE: snake_case_ = 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()} snake_case_ = [ {'''label''': self.model.config.idalabel[i], '''score''': score.item()} for i, score in enumerate(_a ) ] if not _legacy: dict_scores.sort(key=lambda lowercase_ : x["score"] , reverse=_a ) if top_k is not None: snake_case_ = dict_scores[:top_k] return dict_scores
350
'''simple docstring''' import pytest import datasets # Import fixture modules as plugins a : int = ['tests.fixtures.files', 'tests.fixtures.hub', 'tests.fixtures.fsspec'] def __magic_name__ ( __UpperCAmelCase, __UpperCAmelCase ) -> Tuple: '''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 __magic_name__ ( __UpperCAmelCase ) -> Union[str, Any]: '''simple docstring''' config.addinivalue_line('''markers''', '''torchaudio_latest: mark test to run with torchaudio>=0.12''' ) @pytest.fixture(autouse=__UpperCAmelCase ) def __magic_name__ ( __UpperCAmelCase, __UpperCAmelCase ) -> List[Any]: '''simple docstring''' snake_case_ = tmp_path_factory.getbasetemp() / '''cache''' snake_case_ = test_hf_cache_home / '''datasets''' snake_case_ = test_hf_cache_home / '''metrics''' snake_case_ = test_hf_cache_home / '''modules''' monkeypatch.setattr('''datasets.config.HF_DATASETS_CACHE''', str(__UpperCAmelCase ) ) monkeypatch.setattr('''datasets.config.HF_METRICS_CACHE''', str(__UpperCAmelCase ) ) monkeypatch.setattr('''datasets.config.HF_MODULES_CACHE''', str(__UpperCAmelCase ) ) snake_case_ = test_hf_datasets_cache / '''downloads''' monkeypatch.setattr('''datasets.config.DOWNLOADED_DATASETS_PATH''', str(__UpperCAmelCase ) ) snake_case_ = test_hf_datasets_cache / '''downloads''' / '''extracted''' monkeypatch.setattr('''datasets.config.EXTRACTED_DATASETS_PATH''', str(__UpperCAmelCase ) ) @pytest.fixture(autouse=__UpperCAmelCase, scope='''session''' ) def __magic_name__ ( ) -> List[Any]: '''simple docstring''' datasets.disable_progress_bar() @pytest.fixture(autouse=__UpperCAmelCase ) def __magic_name__ ( __UpperCAmelCase ) -> Optional[int]: '''simple docstring''' monkeypatch.setattr('''datasets.config.HF_UPDATE_DOWNLOAD_COUNTS''', __UpperCAmelCase ) @pytest.fixture def __magic_name__ ( __UpperCAmelCase ) -> Union[str, Any]: '''simple docstring''' monkeypatch.setattr('''sqlalchemy.util.deprecations.SILENCE_UBER_WARNING''', __UpperCAmelCase )
72
0
'''simple docstring''' import argparse import requests import torch from PIL import Image from torchvision.transforms import Compose, Normalize, Resize, ToTensor from transformers import SwinaSRConfig, SwinaSRForImageSuperResolution, SwinaSRImageProcessor def __lowerCamelCase ( A__ ) -> Tuple: """simple docstring""" UpperCamelCase = SwinaSRConfig() if "Swin2SR_ClassicalSR_X4_64" in checkpoint_url: UpperCamelCase = 4 elif "Swin2SR_CompressedSR_X4_48" in checkpoint_url: UpperCamelCase = 4 UpperCamelCase = 48 UpperCamelCase = 'pixelshuffle_aux' elif "Swin2SR_Lightweight_X2_64" in checkpoint_url: UpperCamelCase = [6, 6, 6, 6] UpperCamelCase = 60 UpperCamelCase = [6, 6, 6, 6] UpperCamelCase = 'pixelshuffledirect' elif "Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR" in checkpoint_url: UpperCamelCase = 4 UpperCamelCase = 'nearest+conv' elif "Swin2SR_Jpeg_dynamic" in checkpoint_url: UpperCamelCase = 1 UpperCamelCase = 1 UpperCamelCase = 126 UpperCamelCase = 7 UpperCamelCase = 255.0 UpperCamelCase = '' return config def __lowerCamelCase ( A__ , A__ ) -> Optional[Any]: """simple docstring""" if "patch_embed.proj" in name and "layers" not in name: UpperCamelCase = name.replace('patch_embed.proj' , 'embeddings.patch_embeddings.projection' ) if "patch_embed.norm" in name: UpperCamelCase = name.replace('patch_embed.norm' , 'embeddings.patch_embeddings.layernorm' ) if "layers" in name: UpperCamelCase = name.replace('layers' , 'encoder.stages' ) if "residual_group.blocks" in name: UpperCamelCase = name.replace('residual_group.blocks' , 'layers' ) if "attn.proj" in name: UpperCamelCase = name.replace('attn.proj' , 'attention.output.dense' ) if "attn" in name: UpperCamelCase = name.replace('attn' , 'attention.self' ) if "norm1" in name: UpperCamelCase = name.replace('norm1' , 'layernorm_before' ) if "norm2" in name: UpperCamelCase = name.replace('norm2' , 'layernorm_after' ) if "mlp.fc1" in name: UpperCamelCase = name.replace('mlp.fc1' , 'intermediate.dense' ) if "mlp.fc2" in name: UpperCamelCase = name.replace('mlp.fc2' , 'output.dense' ) if "q_bias" in name: UpperCamelCase = name.replace('q_bias' , 'query.bias' ) if "k_bias" in name: UpperCamelCase = name.replace('k_bias' , 'key.bias' ) if "v_bias" in name: UpperCamelCase = name.replace('v_bias' , 'value.bias' ) if "cpb_mlp" in name: UpperCamelCase = name.replace('cpb_mlp' , 'continuous_position_bias_mlp' ) if "patch_embed.proj" in name: UpperCamelCase = name.replace('patch_embed.proj' , 'patch_embed.projection' ) if name == "norm.weight": UpperCamelCase = 'layernorm.weight' if name == "norm.bias": UpperCamelCase = 'layernorm.bias' if "conv_first" in name: UpperCamelCase = name.replace('conv_first' , 'first_convolution' ) if ( "upsample" in name or "conv_before_upsample" in name or "conv_bicubic" in name or "conv_up" in name or "conv_hr" in name or "conv_last" in name or "aux" in name ): # heads if "conv_last" in name: UpperCamelCase = name.replace('conv_last' , 'final_convolution' ) if config.upsampler in ["pixelshuffle", "pixelshuffle_aux", "nearest+conv"]: if "conv_before_upsample.0" in name: UpperCamelCase = name.replace('conv_before_upsample.0' , 'conv_before_upsample' ) if "upsample.0" in name: UpperCamelCase = name.replace('upsample.0' , 'upsample.convolution_0' ) if "upsample.2" in name: UpperCamelCase = name.replace('upsample.2' , 'upsample.convolution_1' ) UpperCamelCase = 'upsample.' + name elif config.upsampler == "pixelshuffledirect": UpperCamelCase = name.replace('upsample.0.weight' , 'upsample.conv.weight' ) UpperCamelCase = name.replace('upsample.0.bias' , 'upsample.conv.bias' ) else: pass else: UpperCamelCase = 'swin2sr.' + name return name def __lowerCamelCase ( A__ , A__ ) -> Dict: """simple docstring""" for key in orig_state_dict.copy().keys(): UpperCamelCase = orig_state_dict.pop(__UpperCamelCase ) if "qkv" in key: UpperCamelCase = key.split('.' ) UpperCamelCase = int(key_split[1] ) UpperCamelCase = int(key_split[4] ) UpperCamelCase = config.embed_dim if "weight" in key: UpperCamelCase = val[:dim, :] UpperCamelCase = val[dim : dim * 2, :] UpperCamelCase = val[-dim:, :] else: UpperCamelCase = val[:dim] UpperCamelCase = val[dim : dim * 2] UpperCamelCase = val[-dim:] pass else: UpperCamelCase = val return orig_state_dict def __lowerCamelCase ( A__ , A__ , A__ ) -> List[str]: """simple docstring""" UpperCamelCase = get_config(__UpperCamelCase ) UpperCamelCase = SwinaSRForImageSuperResolution(__UpperCamelCase ) model.eval() UpperCamelCase = torch.hub.load_state_dict_from_url(__UpperCamelCase , map_location='cpu' ) UpperCamelCase = convert_state_dict(__UpperCamelCase , __UpperCamelCase ) UpperCamelCase , UpperCamelCase = model.load_state_dict(__UpperCamelCase , strict=__UpperCamelCase ) if len(__UpperCamelCase ) > 0: raise ValueError('Missing keys when converting: {}'.format(__UpperCamelCase ) ) for key in unexpected_keys: if not ("relative_position_index" in key or "relative_coords_table" in key or "self_mask" in key): raise ValueError(F"""Unexpected key {key} in state_dict""" ) # verify values UpperCamelCase = 'https://github.com/mv-lab/swin2sr/blob/main/testsets/real-inputs/shanghai.jpg?raw=true' UpperCamelCase = Image.open(requests.get(__UpperCamelCase , stream=__UpperCamelCase ).raw ).convert('RGB' ) UpperCamelCase = SwinaSRImageProcessor() # pixel_values = processor(image, return_tensors="pt").pixel_values UpperCamelCase = 126 if 'Jpeg' in checkpoint_url else 256 UpperCamelCase = Compose( [ Resize((image_size, image_size) ), ToTensor(), Normalize(mean=[0.485, 0.456, 0.406] , std=[0.229, 0.224, 0.225] ), ] ) UpperCamelCase = transforms(__UpperCamelCase ).unsqueeze(0 ) if config.num_channels == 1: UpperCamelCase = pixel_values[:, 0, :, :].unsqueeze(1 ) UpperCamelCase = model(__UpperCamelCase ) # assert values if "Swin2SR_ClassicalSR_X2_64" in checkpoint_url: UpperCamelCase = torch.Size([1, 3, 512, 512] ) UpperCamelCase = torch.tensor( [[-0.7_087, -0.7_138, -0.6_721], [-0.8_340, -0.8_095, -0.7_298], [-0.9_149, -0.8_414, -0.7_940]] ) elif "Swin2SR_ClassicalSR_X4_64" in checkpoint_url: UpperCamelCase = torch.Size([1, 3, 1_024, 1_024] ) UpperCamelCase = torch.tensor( [[-0.7_775, -0.8_105, -0.8_933], [-0.7_764, -0.8_356, -0.9_225], [-0.7_976, -0.8_686, -0.9_579]] ) elif "Swin2SR_CompressedSR_X4_48" in checkpoint_url: # TODO values didn't match exactly here UpperCamelCase = torch.Size([1, 3, 1_024, 1_024] ) UpperCamelCase = torch.tensor( [[-0.8_035, -0.7_504, -0.7_491], [-0.8_538, -0.8_124, -0.7_782], [-0.8_804, -0.8_651, -0.8_493]] ) elif "Swin2SR_Lightweight_X2_64" in checkpoint_url: UpperCamelCase = torch.Size([1, 3, 512, 512] ) UpperCamelCase = torch.tensor( [[-0.7_669, -0.8_662, -0.8_767], [-0.8_810, -0.9_962, -0.9_820], [-0.9_340, -1.0_322, -1.1_149]] ) elif "Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR" in checkpoint_url: UpperCamelCase = torch.Size([1, 3, 1_024, 1_024] ) UpperCamelCase = torch.tensor( [[-0.5_238, -0.5_557, -0.6_321], [-0.6_016, -0.5_903, -0.6_391], [-0.6_244, -0.6_334, -0.6_889]] ) assert ( outputs.reconstruction.shape == expected_shape ), F"""Shape of reconstruction should be {expected_shape}, but is {outputs.reconstruction.shape}""" assert torch.allclose(outputs.reconstruction[0, 0, :3, :3] , __UpperCamelCase , atol=1e-3 ) print('Looks ok!' ) UpperCamelCase = { 'https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_ClassicalSR_X2_64.pth': ( 'swin2SR-classical-sr-x2-64' ), 'https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_ClassicalSR_X4_64.pth': ( 'swin2SR-classical-sr-x4-64' ), 'https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_CompressedSR_X4_48.pth': ( 'swin2SR-compressed-sr-x4-48' ), 'https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_Lightweight_X2_64.pth': ( 'swin2SR-lightweight-x2-64' ), 'https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR.pth': ( 'swin2SR-realworld-sr-x4-64-bsrgan-psnr' ), } UpperCamelCase = url_to_name[checkpoint_url] if pytorch_dump_folder_path is not None: print(F"""Saving model {model_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(__UpperCamelCase ) print(F"""Saving image processor to {pytorch_dump_folder_path}""" ) processor.save_pretrained(__UpperCamelCase ) if push_to_hub: model.push_to_hub(F"""caidas/{model_name}""" ) processor.push_to_hub(F"""caidas/{model_name}""" ) if __name__ == "__main__": _lowerCamelCase : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( "--checkpoint_url", default="https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_ClassicalSR_X2_64.pth", type=str, help="URL of the original Swin2SR checkpoint you\'d like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) parser.add_argument("--push_to_hub", action="store_true", help="Whether to push the converted model to the hub.") _lowerCamelCase : int = parser.parse_args() convert_swinasr_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
28
"""simple docstring""" import re def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" return [char.split() for char in re.split(r'''[^ a-z A-Z 0-9 \s]''' , str_ )] def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" __A = split_input(str_ ) return "".join( [''''''.join([char.capitalize() for char in sub_str] ) for sub_str in string_split] ) def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ): """simple docstring""" try: __A = split_input(__UpperCamelCase ) if upper: __A = ''''''.join( [ separator.join([char.upper() for char in sub_str] ) for sub_str in string_split ] ) else: __A = ''''''.join( [ separator.join([char.lower() for char in sub_str] ) for sub_str in string_split ] ) return res_str except IndexError: return "not valid string" def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" return to_simple_case(__UpperCamelCase ) def lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" try: __A = to_simple_case(__UpperCamelCase ) return res_str[0].lower() + res_str[1:] except IndexError: return "not valid string" def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase ): """simple docstring""" return to_complex_case(__UpperCamelCase , __UpperCamelCase , '''_''' ) def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase ): """simple docstring""" return to_complex_case(__UpperCamelCase , __UpperCamelCase , '''-''' ) if __name__ == "__main__": __import__('doctest').testmod()
266
0
import json import logging import os import re import sys from dataclasses import dataclass, field from typing import Any, Dict, List, Optional, Union import datasets import numpy as np import torch import torchaudio from packaging import version from torch import nn import transformers from transformers import ( HfArgumentParser, Trainer, TrainingArguments, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaForCTC, WavaVecaProcessor, is_apex_available, set_seed, ) from transformers.trainer_utils import get_last_checkpoint, is_main_process if is_apex_available(): from apex import amp if version.parse(version.parse(torch.__version__).base_version) >= version.parse('''1.6'''): snake_case : Tuple = True from torch.cuda.amp import autocast snake_case : Optional[int] = logging.getLogger(__name__) def __lowerCamelCase ( UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : List[Any]=None ): """simple docstring""" return field(default_factory=lambda: default , metadata=UpperCAmelCase_ ) @dataclass class _snake_case : SCREAMING_SNAKE_CASE__ = field( metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'} ) SCREAMING_SNAKE_CASE__ = field( default=_snake_case , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'} , ) SCREAMING_SNAKE_CASE__ = field( default=_snake_case , metadata={'help': 'Whether to freeze the feature extractor layers of the model.'} ) SCREAMING_SNAKE_CASE__ = field( default=0.1 , metadata={'help': 'The dropout ratio for the attention probabilities.'} ) SCREAMING_SNAKE_CASE__ = field( default=0.1 , metadata={'help': 'The dropout ratio for activations inside the fully connected layer.'} ) SCREAMING_SNAKE_CASE__ = field( default=0.1 , metadata={ 'help': 'The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.' } , ) SCREAMING_SNAKE_CASE__ = field( default=0.1 , metadata={'help': 'The dropout probabilitiy for all 1D convolutional layers in feature extractor.'} , ) SCREAMING_SNAKE_CASE__ = field( default=0.05 , metadata={ 'help': ( 'Propability of each feature vector along the time axis to be chosen as the start of the vector' 'span to be masked. Approximately ``mask_time_prob * sequence_length // mask_time_length`` feature' 'vectors will be masked along the time axis. This is only relevant if ``apply_spec_augment is True``.' ) } , ) SCREAMING_SNAKE_CASE__ = field(default=0.0 , metadata={'help': 'The LayerDrop probability.'} ) @dataclass class _snake_case : SCREAMING_SNAKE_CASE__ = field( default=_snake_case , metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'} ) SCREAMING_SNAKE_CASE__ = field( default='train+validation' , metadata={ 'help': 'The name of the training data set split to use (via the datasets library). Defaults to \'train\'' } , ) SCREAMING_SNAKE_CASE__ = field( default=_snake_case , metadata={'help': 'Overwrite the cached preprocessed datasets or not.'} ) SCREAMING_SNAKE_CASE__ = field( default=_snake_case , metadata={'help': 'The number of processes to use for the preprocessing.'} , ) SCREAMING_SNAKE_CASE__ = field( default=_snake_case , metadata={ 'help': ( 'For debugging purposes or quicker training, truncate the number of training examples to this ' 'value if set.' ) } , ) SCREAMING_SNAKE_CASE__ = field( default=_snake_case , metadata={ 'help': ( 'For debugging purposes or quicker training, truncate the number of validation examples to this ' 'value if set.' ) } , ) SCREAMING_SNAKE_CASE__ = list_field( default=[',', '?', '.', '!', '-', ';', ':', '""', '%', '\'', '"', '�'] , metadata={'help': 'A list of characters to remove from the transcripts.'} , ) @dataclass class _snake_case : SCREAMING_SNAKE_CASE__ = 42 SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None def __call__( self , _lowerCamelCase ): # split inputs and labels since they have to be of different lenghts and need # different padding methods a :Any = [{'''input_values''': feature['''input_values''']} for feature in features] a :List[str] = [{'''input_ids''': feature['''labels''']} for feature in features] a :Dict = self.processor.pad( _lowerCamelCase , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors='''pt''' , ) a :Union[str, Any] = self.processor.pad( labels=_lowerCamelCase , padding=self.padding , max_length=self.max_length_labels , pad_to_multiple_of=self.pad_to_multiple_of_labels , return_tensors='''pt''' , ) # replace padding with -100 to ignore loss correctly a :Any = labels_batch['''input_ids'''].masked_fill(labels_batch.attention_mask.ne(1 ) , -100 ) a :Optional[Any] = labels return batch class _snake_case ( _snake_case ): def SCREAMING_SNAKE_CASE__ ( self , _lowerCamelCase , _lowerCamelCase ): model.train() a :Union[str, Any] = self._prepare_inputs(_lowerCamelCase ) if self.use_amp: with autocast(): a :Any = self.compute_loss(_lowerCamelCase , _lowerCamelCase ) else: a :List[Any] = self.compute_loss(_lowerCamelCase , _lowerCamelCase ) if self.args.n_gpu > 1: if model.module.config.ctc_loss_reduction == "mean": a :Optional[int] = loss.mean() elif model.module.config.ctc_loss_reduction == "sum": a :Optional[Any] = loss.sum() / (inputs['''labels'''] >= 0).sum() else: raise ValueError(F'''{model.config.ctc_loss_reduction} is not valid. Choose one of [\'mean\', \'sum\']''' ) if self.args.gradient_accumulation_steps > 1: a :Union[str, Any] = loss / self.args.gradient_accumulation_steps if self.use_amp: self.scaler.scale(_lowerCamelCase ).backward() elif self.use_apex: with amp.scale_loss(_lowerCamelCase , self.optimizer ) as scaled_loss: scaled_loss.backward() elif self.deepspeed: self.deepspeed.backward(_lowerCamelCase ) else: loss.backward() return loss.detach() def __lowerCamelCase ( ): """simple docstring""" a :str = 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 :List[str] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: a , a , a :Tuple = parser.parse_args_into_dataclasses() # Detecting last checkpoint. a :int = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: a :Union[str, Any] = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F'''Output directory ({training_args.output_dir}) already exists and is not empty. ''' '''Use --overwrite_output_dir to overcome.''' ) elif last_checkpoint is not None: logger.info( F'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ''' '''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.''' ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , handlers=[logging.StreamHandler(sys.stdout )] , ) logger.setLevel(logging.INFO if is_main_process(training_args.local_rank ) else logging.WARN ) # Log on each process the small summary: logger.warning( F'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}''' + F'''distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}''' ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() logger.info('''Training/evaluation parameters %s''' , UpperCAmelCase_ ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: a :List[Any] = datasets.load_dataset( '''common_voice''' , data_args.dataset_config_name , split=data_args.train_split_name ) a :Union[str, Any] = datasets.load_dataset('''common_voice''' , data_args.dataset_config_name , split='''test''' ) # Create and save tokenizer a :Any = F'''[{''.join(data_args.chars_to_ignore )}]''' def remove_special_characters(UpperCAmelCase_ : Tuple ): a :Union[str, Any] = re.sub(UpperCAmelCase_ , '''''' , batch['''sentence'''] ).lower() + ''' ''' return batch a :Dict = train_dataset.map(UpperCAmelCase_ , remove_columns=['''sentence'''] ) a :str = eval_dataset.map(UpperCAmelCase_ , remove_columns=['''sentence'''] ) def extract_all_chars(UpperCAmelCase_ : Optional[int] ): a :List[Any] = ''' '''.join(batch['''text'''] ) a :int = list(set(UpperCAmelCase_ ) ) return {"vocab": [vocab], "all_text": [all_text]} a :Tuple = train_dataset.map( UpperCAmelCase_ , batched=UpperCAmelCase_ , batch_size=-1 , keep_in_memory=UpperCAmelCase_ , remove_columns=train_dataset.column_names , ) a :Optional[int] = train_dataset.map( UpperCAmelCase_ , batched=UpperCAmelCase_ , batch_size=-1 , keep_in_memory=UpperCAmelCase_ , remove_columns=eval_dataset.column_names , ) a :Dict = list(set(vocab_train['''vocab'''][0] ) | set(vocab_test['''vocab'''][0] ) ) a :List[Any] = {v: k for k, v in enumerate(UpperCAmelCase_ )} a :Dict = vocab_dict[''' '''] del vocab_dict[" "] a :str = len(UpperCAmelCase_ ) a :Dict = len(UpperCAmelCase_ ) with open('''vocab.json''' , '''w''' ) as vocab_file: json.dump(UpperCAmelCase_ , UpperCAmelCase_ ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. a :Optional[Any] = WavaVecaCTCTokenizer( '''vocab.json''' , unk_token='''[UNK]''' , pad_token='''[PAD]''' , word_delimiter_token='''|''' , ) a :str = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6000 , padding_value=0.0 , do_normalize=UpperCAmelCase_ , return_attention_mask=UpperCAmelCase_ ) a :Dict = WavaVecaProcessor(feature_extractor=UpperCAmelCase_ , tokenizer=UpperCAmelCase_ ) a :Optional[int] = WavaVecaForCTC.from_pretrained( model_args.model_name_or_path , cache_dir=model_args.cache_dir , activation_dropout=model_args.activation_dropout , attention_dropout=model_args.attention_dropout , hidden_dropout=model_args.hidden_dropout , feat_proj_dropout=model_args.feat_proj_dropout , mask_time_prob=model_args.mask_time_prob , gradient_checkpointing=training_args.gradient_checkpointing , layerdrop=model_args.layerdrop , ctc_loss_reduction='''mean''' , pad_token_id=processor.tokenizer.pad_token_id , vocab_size=len(processor.tokenizer ) , ) if data_args.max_train_samples is not None: a :List[Any] = min(len(UpperCAmelCase_ ) , data_args.max_train_samples ) a :Dict = train_dataset.select(range(UpperCAmelCase_ ) ) if data_args.max_val_samples is not None: a :Dict = eval_dataset.select(range(data_args.max_val_samples ) ) a :Dict = torchaudio.transforms.Resample(4_8000 , 1_6000 ) # Preprocessing the datasets. # We need to read the aduio files as arrays and tokenize the targets. def speech_file_to_array_fn(UpperCAmelCase_ : List[Any] ): a , a :Tuple = torchaudio.load(batch['''path'''] ) a :Optional[Any] = resampler(UpperCAmelCase_ ).squeeze().numpy() a :List[Any] = 1_6000 a :str = batch['''text'''] return batch a :List[str] = train_dataset.map( UpperCAmelCase_ , remove_columns=train_dataset.column_names , num_proc=data_args.preprocessing_num_workers , ) a :Optional[Any] = eval_dataset.map( UpperCAmelCase_ , remove_columns=eval_dataset.column_names , num_proc=data_args.preprocessing_num_workers , ) def prepare_dataset(UpperCAmelCase_ : List[str] ): # check that all files have the correct sampling rate assert ( len(set(batch['''sampling_rate'''] ) ) == 1 ), F'''Make sure all inputs have the same sampling rate of {processor.feature_extractor.sampling_rate}.''' a :Dict = processor( audio=batch['''speech'''] , text=batch['''target_text'''] , sampling_rate=batch['''sampling_rate'''][0] ) batch.update(UpperCAmelCase_ ) return batch a :Optional[Any] = train_dataset.map( UpperCAmelCase_ , remove_columns=train_dataset.column_names , batch_size=training_args.per_device_train_batch_size , batched=UpperCAmelCase_ , num_proc=data_args.preprocessing_num_workers , ) a :List[str] = eval_dataset.map( UpperCAmelCase_ , remove_columns=eval_dataset.column_names , batch_size=training_args.per_device_train_batch_size , batched=UpperCAmelCase_ , num_proc=data_args.preprocessing_num_workers , ) # Metric a :Optional[Any] = datasets.load_metric('''wer''' ) def compute_metrics(UpperCAmelCase_ : List[Any] ): a :List[str] = pred.predictions a :Dict = np.argmax(UpperCAmelCase_ , axis=-1 ) a :Dict = processor.tokenizer.pad_token_id a :int = processor.batch_decode(UpperCAmelCase_ ) # we do not want to group tokens when computing the metrics a :Dict = processor.batch_decode(pred.label_ids , group_tokens=UpperCAmelCase_ ) a :Optional[Any] = wer_metric.compute(predictions=UpperCAmelCase_ , references=UpperCAmelCase_ ) return {"wer": wer} if model_args.freeze_feature_extractor: model.freeze_feature_extractor() # Data collator a :int = DataCollatorCTCWithPadding(processor=UpperCAmelCase_ , padding=UpperCAmelCase_ ) # Initialize our Trainer a :Tuple = CTCTrainer( model=UpperCAmelCase_ , data_collator=UpperCAmelCase_ , args=UpperCAmelCase_ , compute_metrics=UpperCAmelCase_ , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , tokenizer=processor.feature_extractor , ) # Training if training_args.do_train: if last_checkpoint is not None: a :int = last_checkpoint elif os.path.isdir(model_args.model_name_or_path ): a :Tuple = model_args.model_name_or_path else: a :Optional[int] = None # Save the feature_extractor and the tokenizer if is_main_process(training_args.local_rank ): processor.save_pretrained(training_args.output_dir ) a :int = trainer.train(resume_from_checkpoint=UpperCAmelCase_ ) trainer.save_model() a :Optional[int] = train_result.metrics a :int = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(UpperCAmelCase_ ) ) a :Optional[Any] = min(UpperCAmelCase_ , len(UpperCAmelCase_ ) ) trainer.log_metrics('''train''' , UpperCAmelCase_ ) trainer.save_metrics('''train''' , UpperCAmelCase_ ) trainer.save_state() # Evaluation a :Dict = {} if training_args.do_eval: logger.info('''*** Evaluate ***''' ) a :Optional[int] = trainer.evaluate() a :Tuple = data_args.max_val_samples if data_args.max_val_samples is not None else len(UpperCAmelCase_ ) a :Optional[Any] = min(UpperCAmelCase_ , len(UpperCAmelCase_ ) ) trainer.log_metrics('''eval''' , UpperCAmelCase_ ) trainer.save_metrics('''eval''' , UpperCAmelCase_ ) return results if __name__ == "__main__": main()
281
import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, CycleDiffusionPipeline, DDIMScheduler, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class _snake_case ( _snake_case , _snake_case , unittest.TestCase ): SCREAMING_SNAKE_CASE__ = CycleDiffusionPipeline SCREAMING_SNAKE_CASE__ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - { 'negative_prompt', 'height', 'width', 'negative_prompt_embeds', } SCREAMING_SNAKE_CASE__ = PipelineTesterMixin.required_optional_params - {'latents'} SCREAMING_SNAKE_CASE__ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'source_prompt'} ) SCREAMING_SNAKE_CASE__ = IMAGE_TO_IMAGE_IMAGE_PARAMS SCREAMING_SNAKE_CASE__ = IMAGE_TO_IMAGE_IMAGE_PARAMS def SCREAMING_SNAKE_CASE__ ( self ): torch.manual_seed(0 ) a :Optional[Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') , cross_attention_dim=32 , ) a :List[str] = DDIMScheduler( beta_start=0.0_0085 , beta_end=0.012 , beta_schedule='''scaled_linear''' , num_train_timesteps=1000 , clip_sample=_lowerCamelCase , set_alpha_to_one=_lowerCamelCase , ) torch.manual_seed(0 ) a :List[str] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , ) torch.manual_seed(0 ) a :Dict = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) a :str = CLIPTextModel(_lowerCamelCase ) a :List[str] = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) a :Union[str, Any] = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''safety_checker''': None, '''feature_extractor''': None, } return components def SCREAMING_SNAKE_CASE__ ( self , _lowerCamelCase , _lowerCamelCase=0 ): a :Tuple = floats_tensor((1, 3, 32, 32) , rng=random.Random(_lowerCamelCase ) ).to(_lowerCamelCase ) a :Tuple = image / 2 + 0.5 if str(_lowerCamelCase ).startswith('''mps''' ): a :List[str] = torch.manual_seed(_lowerCamelCase ) else: a :Any = torch.Generator(device=_lowerCamelCase ).manual_seed(_lowerCamelCase ) a :int = { '''prompt''': '''An astronaut riding an elephant''', '''source_prompt''': '''An astronaut riding a horse''', '''image''': image, '''generator''': generator, '''num_inference_steps''': 2, '''eta''': 0.1, '''strength''': 0.8, '''guidance_scale''': 3, '''source_guidance_scale''': 1, '''output_type''': '''numpy''', } return inputs def SCREAMING_SNAKE_CASE__ ( self ): a :Union[str, Any] = '''cpu''' # ensure determinism for the device-dependent torch.Generator a :Optional[Any] = self.get_dummy_components() a :Dict = CycleDiffusionPipeline(**_lowerCamelCase ) a :Optional[Any] = pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) a :List[str] = self.get_dummy_inputs(_lowerCamelCase ) a :Any = pipe(**_lowerCamelCase ) a :List[Any] = output.images a :str = images[0, -3:, -3:, -1] assert images.shape == (1, 32, 32, 3) a :List[Any] = np.array([0.4459, 0.4943, 0.4544, 0.6643, 0.5474, 0.4327, 0.5701, 0.5959, 0.5179] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @unittest.skipIf(torch_device != '''cuda''' , '''This test requires a GPU''' ) def SCREAMING_SNAKE_CASE__ ( self ): a :Optional[int] = self.get_dummy_components() for name, module in components.items(): if hasattr(_lowerCamelCase , '''half''' ): a :Union[str, Any] = module.half() a :List[Any] = CycleDiffusionPipeline(**_lowerCamelCase ) a :Dict = pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) a :Tuple = self.get_dummy_inputs(_lowerCamelCase ) a :Optional[int] = pipe(**_lowerCamelCase ) a :Optional[Any] = output.images a :List[Any] = images[0, -3:, -3:, -1] assert images.shape == (1, 32, 32, 3) a :str = np.array([0.3506, 0.4543, 0.446, 0.4575, 0.5195, 0.4155, 0.5273, 0.518, 0.4116] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @skip_mps def SCREAMING_SNAKE_CASE__ ( self ): return super().test_save_load_local() @unittest.skip('''non-deterministic pipeline''' ) def SCREAMING_SNAKE_CASE__ ( self ): return super().test_inference_batch_single_identical() @skip_mps def SCREAMING_SNAKE_CASE__ ( self ): return super().test_dict_tuple_outputs_equivalent() @skip_mps def SCREAMING_SNAKE_CASE__ ( self ): return super().test_save_load_optional_components() @skip_mps def SCREAMING_SNAKE_CASE__ ( self ): return super().test_attention_slicing_forward_pass() @slow @require_torch_gpu class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( self ): a :str = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/cycle-diffusion/black_colored_car.png''' ) a :Optional[int] = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car_fp16.npy''' ) a :Optional[Any] = init_image.resize((512, 512) ) a :List[str] = '''CompVis/stable-diffusion-v1-4''' a :List[str] = DDIMScheduler.from_pretrained(_lowerCamelCase , subfolder='''scheduler''' ) a :Tuple = CycleDiffusionPipeline.from_pretrained( _lowerCamelCase , scheduler=_lowerCamelCase , safety_checker=_lowerCamelCase , torch_dtype=torch.floataa , revision='''fp16''' ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) pipe.enable_attention_slicing() a :Optional[Any] = '''A black colored car''' a :Any = '''A blue colored car''' a :str = torch.manual_seed(0 ) a :List[Any] = pipe( prompt=_lowerCamelCase , source_prompt=_lowerCamelCase , image=_lowerCamelCase , num_inference_steps=100 , eta=0.1 , strength=0.85 , guidance_scale=3 , source_guidance_scale=1 , generator=_lowerCamelCase , output_type='''np''' , ) a :int = output.images # the values aren't exactly equal, but the images look the same visually assert np.abs(image - expected_image ).max() < 5e-1 def SCREAMING_SNAKE_CASE__ ( self ): a :str = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/cycle-diffusion/black_colored_car.png''' ) a :Optional[int] = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car.npy''' ) a :List[str] = init_image.resize((512, 512) ) a :List[str] = '''CompVis/stable-diffusion-v1-4''' a :Any = DDIMScheduler.from_pretrained(_lowerCamelCase , subfolder='''scheduler''' ) a :int = CycleDiffusionPipeline.from_pretrained(_lowerCamelCase , scheduler=_lowerCamelCase , safety_checker=_lowerCamelCase ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) pipe.enable_attention_slicing() a :Optional[int] = '''A black colored car''' a :Any = '''A blue colored car''' a :Optional[int] = torch.manual_seed(0 ) a :Union[str, Any] = pipe( prompt=_lowerCamelCase , source_prompt=_lowerCamelCase , image=_lowerCamelCase , num_inference_steps=100 , eta=0.1 , strength=0.85 , guidance_scale=3 , source_guidance_scale=1 , generator=_lowerCamelCase , output_type='''np''' , ) a :Optional[int] = output.images assert np.abs(image - expected_image ).max() < 2e-2
281
1
import logging import math from functools import partial from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Union import torch from .tensor_utils import tensor_tree_map, tree_map def a ( snake_case__: Union[dict, list, tuple, torch.Tensor] ): '''simple docstring''' lowercase_ = [] if isinstance(snake_case__ , snake_case__ ): for v in tree.values(): shapes.extend(_fetch_dims(snake_case__ ) ) elif isinstance(snake_case__ , (list, tuple) ): for t in tree: shapes.extend(_fetch_dims(snake_case__ ) ) elif isinstance(snake_case__ , torch.Tensor ): shapes.append(tree.shape ) else: raise ValueError('''Not supported''' ) return shapes @torch.jit.ignore def a ( snake_case__: int , snake_case__: Tuple[int, ...] ): '''simple docstring''' lowercase_ = [] for d in reversed(snake_case__ ): idx.append(flat_idx % d ) lowercase_ = flat_idx // d return tuple(reversed(snake_case__ ) ) @torch.jit.ignore def a ( snake_case__: Sequence[int] , snake_case__: Sequence[int] , snake_case__: Sequence[int] , snake_case__: Optional[Sequence[bool]] = None , snake_case__: Optional[Sequence[bool]] = None , ): '''simple docstring''' # start_edges and end_edges both indicate whether, starting from any given # dimension, the start/end index is at the top/bottom edge of the # corresponding tensor, modeled as a tree def reduce_edge_list(snake_case__: List[bool] ) -> None: lowercase_ = True for i in range(len(snake_case__ ) ): lowercase_ = -1 * (i + 1) l[reversed_idx] &= tally lowercase_ = l[reversed_idx] if start_edges is None: lowercase_ = [s == 0 for s in start] reduce_edge_list(snake_case__ ) if end_edges is None: lowercase_ = [e == (d - 1) for e, d in zip(snake_case__ , snake_case__ )] reduce_edge_list(snake_case__ ) # Base cases. Either start/end are empty and we're done, or the final, # one-dimensional tensor can be simply sliced if len(snake_case__ ) == 0: return [()] elif len(snake_case__ ) == 1: return [(slice(start[0] , end[0] + 1 ),)] lowercase_ = [] lowercase_ = [] # Dimensions common to start and end can be selected directly for s, e in zip(snake_case__ , snake_case__ ): if s == e: path_list.append(slice(snake_case__ , s + 1 ) ) else: break lowercase_ = tuple(snake_case__ ) lowercase_ = len(snake_case__ ) # start == end, and we're done if divergence_idx == len(snake_case__ ): return [path] def upper() -> Tuple[Tuple[slice, ...], ...]: assert start_edges is not None assert end_edges is not None lowercase_ = start[divergence_idx] return tuple( path + (slice(snake_case__ , sdi + 1 ),) + s for s in _get_minimal_slice_set( start[divergence_idx + 1 :] , [d - 1 for d in dims[divergence_idx + 1 :]] , dims[divergence_idx + 1 :] , start_edges=start_edges[divergence_idx + 1 :] , end_edges=[True for _ in end_edges[divergence_idx + 1 :]] , ) ) def lower() -> Tuple[Tuple[slice, ...], ...]: assert start_edges is not None assert end_edges is not None lowercase_ = end[divergence_idx] return tuple( path + (slice(snake_case__ , edi + 1 ),) + s for s in _get_minimal_slice_set( [0 for _ in start[divergence_idx + 1 :]] , end[divergence_idx + 1 :] , dims[divergence_idx + 1 :] , start_edges=[True for _ in start_edges[divergence_idx + 1 :]] , end_edges=end_edges[divergence_idx + 1 :] , ) ) # If both start and end are at the edges of the subtree rooted at # divergence_idx, we can just select the whole subtree at once if start_edges[divergence_idx] and end_edges[divergence_idx]: slices.append(path + (slice(start[divergence_idx] , end[divergence_idx] + 1 ),) ) # If just start is at the edge, we can grab almost all of the subtree, # treating only the ragged bottom edge as an edge case elif start_edges[divergence_idx]: slices.append(path + (slice(start[divergence_idx] , end[divergence_idx] ),) ) slices.extend(lower() ) # Analogous to the previous case, but the top is ragged this time elif end_edges[divergence_idx]: slices.extend(upper() ) slices.append(path + (slice(start[divergence_idx] + 1 , end[divergence_idx] + 1 ),) ) # If both sides of the range are ragged, we need to handle both sides # separately. If there's contiguous meat in between them, we can index it # in one big chunk else: slices.extend(upper() ) lowercase_ = end[divergence_idx] - start[divergence_idx] if middle_ground > 1: slices.append(path + (slice(start[divergence_idx] + 1 , end[divergence_idx] ),) ) slices.extend(lower() ) return slices @torch.jit.ignore def a ( snake_case__: torch.Tensor , snake_case__: int , snake_case__: int , snake_case__: int ): '''simple docstring''' lowercase_ = t.shape[:no_batch_dims] lowercase_ = list(_flat_idx_to_idx(snake_case__ , snake_case__ ) ) # _get_minimal_slice_set is inclusive lowercase_ = list(_flat_idx_to_idx(flat_end - 1 , snake_case__ ) ) # Get an ordered list of slices to perform lowercase_ = _get_minimal_slice_set( snake_case__ , snake_case__ , snake_case__ , ) lowercase_ = [t[s] for s in slices] return torch.cat([s.view((-1,) + t.shape[no_batch_dims:] ) for s in sliced_tensors] ) def a ( snake_case__: Callable , snake_case__: Dict[str, Any] , snake_case__: int , snake_case__: int , snake_case__: bool = False , snake_case__: Any = None , snake_case__: bool = False , ): '''simple docstring''' if not (len(snake_case__ ) > 0): raise ValueError('''Must provide at least one input''' ) lowercase_ = [shape[:no_batch_dims] for shape in _fetch_dims(snake_case__ )] lowercase_ = tuple([max(snake_case__ ) for s in zip(*snake_case__ )] ) def _prep_inputs(snake_case__: torch.Tensor ) -> torch.Tensor: if not low_mem: if not sum(t.shape[:no_batch_dims] ) == no_batch_dims: lowercase_ = t.expand(orig_batch_dims + t.shape[no_batch_dims:] ) lowercase_ = t.reshape(-1 , *t.shape[no_batch_dims:] ) else: lowercase_ = t.expand(orig_batch_dims + t.shape[no_batch_dims:] ) return t lowercase_ = tensor_tree_map(_prep_inputs , snake_case__ ) lowercase_ = None if _out is not None: lowercase_ = tensor_tree_map(lambda snake_case__ : t.view([-1] + list(t.shape[no_batch_dims:] ) ) , _out ) lowercase_ = 1 for d in orig_batch_dims: flat_batch_dim *= d lowercase_ = flat_batch_dim // chunk_size + (flat_batch_dim % chunk_size != 0) def _select_chunk(snake_case__: torch.Tensor ) -> torch.Tensor: return t[i : i + chunk_size] if t.shape[0] != 1 else t lowercase_ = 0 lowercase_ = prepped_outputs for _ in range(snake_case__ ): # Chunk the input if not low_mem: lowercase_ = _select_chunk else: lowercase_ = partial( _chunk_slice , flat_start=snake_case__ , flat_end=min(snake_case__ , i + chunk_size ) , no_batch_dims=len(snake_case__ ) , ) lowercase_ = tensor_tree_map(snake_case__ , snake_case__ ) # Run the layer on the chunk lowercase_ = layer(**snake_case__ ) # Allocate space for the output if out is None: lowercase_ = tensor_tree_map(lambda snake_case__ : t.new_zeros((flat_batch_dim,) + t.shape[1:] ) , snake_case__ ) # Put the chunk in its pre-allocated space if isinstance(snake_case__ , snake_case__ ): def assign(snake_case__: dict , snake_case__: dict ) -> None: for k, v in da.items(): if isinstance(snake_case__ , snake_case__ ): assign(snake_case__ , da[k] ) else: if _add_into_out: v[i : i + chunk_size] += da[k] else: lowercase_ = da[k] assign(snake_case__ , snake_case__ ) elif isinstance(snake_case__ , snake_case__ ): for xa, xa in zip(snake_case__ , snake_case__ ): if _add_into_out: xa[i : i + chunk_size] += xa else: lowercase_ = xa elif isinstance(snake_case__ , torch.Tensor ): if _add_into_out: out[i : i + chunk_size] += output_chunk else: lowercase_ = output_chunk else: raise ValueError('''Not supported''' ) i += chunk_size lowercase_ = tensor_tree_map(lambda snake_case__ : t.view(orig_batch_dims + t.shape[1:] ) , snake_case__ ) return out class lowercase__: """simple docstring""" def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE_ : int = 5_1_2 , ) -> Tuple: lowercase_ = max_chunk_size lowercase_ = None lowercase_ = None def _lowercase ( self : Dict , SCREAMING_SNAKE_CASE_ : Callable , SCREAMING_SNAKE_CASE_ : tuple , SCREAMING_SNAKE_CASE_ : int ) -> int: logging.info('''Tuning chunk size...''' ) if min_chunk_size >= self.max_chunk_size: return min_chunk_size lowercase_ = [2**l for l in range(int(math.log(self.max_chunk_size , 2 ) ) + 1 )] lowercase_ = [c for c in candidates if c > min_chunk_size] lowercase_ = [min_chunk_size] + candidates candidates[-1] += 4 def test_chunk_size(SCREAMING_SNAKE_CASE_ : int ) -> bool: try: with torch.no_grad(): fn(*SCREAMING_SNAKE_CASE_ , chunk_size=SCREAMING_SNAKE_CASE_ ) return True except RuntimeError: return False lowercase_ = 0 lowercase_ = len(SCREAMING_SNAKE_CASE_ ) - 1 while i > min_viable_chunk_size_index: lowercase_ = test_chunk_size(candidates[i] ) if not viable: lowercase_ = (min_viable_chunk_size_index + i) // 2 else: lowercase_ = i lowercase_ = (i + len(SCREAMING_SNAKE_CASE_ ) - 1) // 2 return candidates[min_viable_chunk_size_index] def _lowercase ( self : Tuple , SCREAMING_SNAKE_CASE_ : Iterable , SCREAMING_SNAKE_CASE_ : Iterable ) -> bool: lowercase_ = True for aa, aa in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): assert type(SCREAMING_SNAKE_CASE_ ) == type(SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , (list, tuple) ): consistent &= self._compare_arg_caches(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) elif isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): lowercase_ = [v for _, v in sorted(aa.items() , key=lambda SCREAMING_SNAKE_CASE_ : x[0] )] lowercase_ = [v for _, v in sorted(aa.items() , key=lambda SCREAMING_SNAKE_CASE_ : x[0] )] consistent &= self._compare_arg_caches(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else: consistent &= aa == aa return consistent def _lowercase ( self : Tuple , SCREAMING_SNAKE_CASE_ : Callable , SCREAMING_SNAKE_CASE_ : tuple , SCREAMING_SNAKE_CASE_ : int , ) -> int: lowercase_ = True lowercase_ = tree_map(lambda SCREAMING_SNAKE_CASE_ : a.shape if isinstance(SCREAMING_SNAKE_CASE_ , torch.Tensor ) else a , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if self.cached_arg_data is not None: # If args have changed shape/value, we need to re-tune assert len(self.cached_arg_data ) == len(SCREAMING_SNAKE_CASE_ ) lowercase_ = self._compare_arg_caches(self.cached_arg_data , SCREAMING_SNAKE_CASE_ ) else: # Otherwise, we can reuse the precomputed value lowercase_ = False if not consistent: lowercase_ = self._determine_favorable_chunk_size( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ) lowercase_ = arg_data assert self.cached_chunk_size is not None return self.cached_chunk_size
30
import unittest import numpy as np import torch from .utils_summarization import build_mask, compute_token_type_ids, process_story, truncate_or_pad class lowercase__( unittest.TestCase ): """simple docstring""" def _lowercase ( self : List[str] ) -> List[Any]: lowercase_ = 1_0 def _lowercase ( self : int ) -> List[str]: lowercase_ = [1, 2, 3, 4] lowercase_ = [1, 2, 3, 4, 0, 0, 0, 0, 0, 0] self.assertEqual(truncate_or_pad(SCREAMING_SNAKE_CASE_ , self.block_size , 0 ) , SCREAMING_SNAKE_CASE_ ) def _lowercase ( self : int ) -> Optional[Any]: lowercase_ = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0] lowercase_ = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0] self.assertEqual(truncate_or_pad(SCREAMING_SNAKE_CASE_ , self.block_size , 0 ) , SCREAMING_SNAKE_CASE_ ) def _lowercase ( self : Union[str, Any] ) -> Optional[int]: lowercase_ = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0, 1_1, 1_2, 1_3] lowercase_ = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1_0] self.assertEqual(truncate_or_pad(SCREAMING_SNAKE_CASE_ , self.block_size , 0 ) , SCREAMING_SNAKE_CASE_ ) def _lowercase ( self : Any ) -> List[Any]: lowercase_ = '''It was the year of Our Lord one thousand seven hundred and seventy-five.\n\nSpiritual revelations were conceded to England at that favoured period, as at this.''' lowercase_ , lowercase_ = process_story(SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , [] ) def _lowercase ( self : List[str] ) -> List[str]: lowercase_ = '''''' lowercase_ , lowercase_ = process_story(SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , [] ) self.assertEqual(SCREAMING_SNAKE_CASE_ , [] ) def _lowercase ( self : Union[str, Any] ) -> Union[str, Any]: lowercase_ = ( '''It was the year of Our Lord one thousand seven hundred and ''' '''seventy-five\n\nSpiritual revelations were conceded to England ''' '''at that favoured period, as at this.\n@highlight\n\nIt was the best of times''' ) lowercase_ , lowercase_ = process_story(SCREAMING_SNAKE_CASE_ ) lowercase_ = [ '''It was the year of Our Lord one thousand seven hundred and seventy-five.''', '''Spiritual revelations were conceded to England at that favoured period, as at this.''', ] self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) lowercase_ = ['''It was the best of times.'''] self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _lowercase ( self : Union[str, Any] ) -> Optional[Any]: lowercase_ = torch.tensor([1, 2, 3, 4] ) lowercase_ = torch.tensor([1, 1, 1, 1] ) np.testing.assert_array_equal(build_mask(SCREAMING_SNAKE_CASE_ , 0 ).numpy() , expected.numpy() ) def _lowercase ( self : List[Any] ) -> Tuple: lowercase_ = torch.tensor([1, 2, 3, 4, 2_3, 2_3, 2_3] ) lowercase_ = torch.tensor([1, 1, 1, 1, 0, 0, 0] ) np.testing.assert_array_equal(build_mask(SCREAMING_SNAKE_CASE_ , 2_3 ).numpy() , expected.numpy() ) def _lowercase ( self : int ) -> Dict: lowercase_ = torch.tensor([8, 2, 3, 4, 1, 1, 1] ) lowercase_ = torch.tensor([1, 1, 1, 1, 0, 0, 0] ) np.testing.assert_array_equal(build_mask(SCREAMING_SNAKE_CASE_ , 1 ).numpy() , expected.numpy() ) def _lowercase ( self : List[str] ) -> Tuple: lowercase_ = 1_0_1 lowercase_ = torch.tensor([[1, 2, 3, 4, 5, 6], [1, 2, 3, 1_0_1, 5, 6], [1, 1_0_1, 3, 4, 1_0_1, 6]] ) lowercase_ = torch.tensor([[1, 1, 1, 1, 1, 1], [1, 1, 1, 0, 0, 0], [1, 0, 0, 0, 1, 1]] ) lowercase_ = compute_token_type_ids(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) np.testing.assert_array_equal(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
30
1
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_mobilebert import MobileBertTokenizer _lowerCAmelCase :List[str] = logging.get_logger(__name__) _lowerCAmelCase :Optional[int] = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} _lowerCAmelCase :Any = { 'vocab_file': {'mobilebert-uncased': 'https://huggingface.co/google/mobilebert-uncased/resolve/main/vocab.txt'}, 'tokenizer_file': { 'mobilebert-uncased': 'https://huggingface.co/google/mobilebert-uncased/resolve/main/tokenizer.json' }, } _lowerCAmelCase :Dict = {'mobilebert-uncased': 512} _lowerCAmelCase :Dict = {} class _UpperCAmelCase ( _UpperCAmelCase ): '''simple docstring''' a__ =VOCAB_FILES_NAMES a__ =PRETRAINED_VOCAB_FILES_MAP a__ =PRETRAINED_INIT_CONFIGURATION a__ =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a__ =MobileBertTokenizer def __init__( self , A=None , A=None , A=True , A="[UNK]" , A="[SEP]" , A="[PAD]" , A="[CLS]" , A="[MASK]" , A=True , A=None , **A , ) -> Any: super().__init__( _UpperCAmelCase , tokenizer_file=_UpperCAmelCase , do_lower_case=_UpperCAmelCase , unk_token=_UpperCAmelCase , sep_token=_UpperCAmelCase , pad_token=_UpperCAmelCase , cls_token=_UpperCAmelCase , mask_token=_UpperCAmelCase , tokenize_chinese_chars=_UpperCAmelCase , strip_accents=_UpperCAmelCase , **_UpperCAmelCase , ) _UpperCAmelCase : Optional[Any] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , _UpperCAmelCase ) != do_lower_case or normalizer_state.get('''strip_accents''' , _UpperCAmelCase ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , _UpperCAmelCase ) != tokenize_chinese_chars ): _UpperCAmelCase : Optional[Any] = getattr(_UpperCAmelCase , normalizer_state.pop('''type''' ) ) _UpperCAmelCase : Any = do_lower_case _UpperCAmelCase : List[Any] = strip_accents _UpperCAmelCase : List[Any] = tokenize_chinese_chars _UpperCAmelCase : Tuple = normalizer_class(**_UpperCAmelCase ) _UpperCAmelCase : Dict = do_lower_case def __lowerCAmelCase ( self , A , A=None ) -> List[str]: _UpperCAmelCase : Any = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __lowerCAmelCase ( self , A , A = None ) -> Optional[Any]: _UpperCAmelCase : Union[str, Any] = [self.sep_token_id] _UpperCAmelCase : Optional[int] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __lowerCAmelCase ( self , A , A = None ) -> Optional[Any]: _UpperCAmelCase : Optional[Any] = self._tokenizer.model.save(_UpperCAmelCase , name=_UpperCAmelCase ) return tuple(_UpperCAmelCase )
352
"""simple docstring""" from ...processing_utils import ProcessorMixin class _UpperCAmelCase ( a ): '''simple docstring''' a__ ='''WhisperFeatureExtractor''' a__ ='''WhisperTokenizer''' def __init__( self , A , A ) -> Any: super().__init__(A , A ) _UpperCAmelCase : int = self.feature_extractor _UpperCAmelCase : List[str] = False def __lowerCAmelCase ( self , A=None , A=None , A=True ) -> Optional[int]: return self.tokenizer.get_decoder_prompt_ids(task=A , language=A , no_timestamps=A ) def __call__( self , *A , **A ) -> Tuple: # For backward compatibility if self._in_target_context_manager: return self.current_processor(*A , **A ) _UpperCAmelCase : str = kwargs.pop('''audio''' , A ) _UpperCAmelCase : Dict = kwargs.pop('''sampling_rate''' , A ) _UpperCAmelCase : Dict = kwargs.pop('''text''' , A ) if len(A ) > 0: _UpperCAmelCase : List[Any] = args[0] _UpperCAmelCase : Union[str, Any] = args[1:] if audio is None and text is None: raise ValueError('''You need to specify either an `audio` or `text` input to process.''' ) if audio is not None: _UpperCAmelCase : Optional[Any] = self.feature_extractor(A , *A , sampling_rate=A , **A ) if text is not None: _UpperCAmelCase : Any = self.tokenizer(A , **A ) if text is None: return inputs elif audio is None: return encodings else: _UpperCAmelCase : int = encodings['''input_ids'''] return inputs def __lowerCAmelCase ( self , *A , **A ) -> Optional[Any]: return self.tokenizer.batch_decode(*A , **A ) def __lowerCAmelCase ( self , *A , **A ) -> Any: return self.tokenizer.decode(*A , **A ) def __lowerCAmelCase ( self , A , A="np" ) -> Any: return self.tokenizer.get_prompt_ids(A , return_tensors=A )
68
0
'''simple docstring''' from ....configuration_utils import PretrainedConfig from ....utils import logging SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) # TODO: upload to AWS SCREAMING_SNAKE_CASE__ = { 'yjernite/retribert-base-uncased': ( 'https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/config.json' ), } class a_ ( lowerCamelCase ): lowercase = """retribert""" def __init__( self , _SCREAMING_SNAKE_CASE=30522 , _SCREAMING_SNAKE_CASE=768 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=3072 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=512 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=1e-12 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=128 , _SCREAMING_SNAKE_CASE=0 , **_SCREAMING_SNAKE_CASE , ) -> Any: """simple docstring""" super().__init__(pad_token_id=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) UpperCamelCase = vocab_size UpperCamelCase = hidden_size UpperCamelCase = num_hidden_layers UpperCamelCase = num_attention_heads UpperCamelCase = hidden_act UpperCamelCase = intermediate_size UpperCamelCase = hidden_dropout_prob UpperCamelCase = attention_probs_dropout_prob UpperCamelCase = max_position_embeddings UpperCamelCase = type_vocab_size UpperCamelCase = initializer_range UpperCamelCase = layer_norm_eps UpperCamelCase = share_encoders UpperCamelCase = projection_dim
321
'''simple docstring''' import math from typing import Any, Callable, List, Optional, Tuple, Union import numpy as np import torch from ...models import TaFilmDecoder from ...schedulers import DDPMScheduler from ...utils import is_onnx_available, logging, randn_tensor if is_onnx_available(): from ..onnx_utils import OnnxRuntimeModel from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline from .continous_encoder import SpectrogramContEncoder from .notes_encoder import SpectrogramNotesEncoder SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) # pylint: disable=invalid-name SCREAMING_SNAKE_CASE__ = 2_5_6 class a_ ( lowerCamelCase ): lowercase = ["""melgan"""] def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , ) -> None: """simple docstring""" super().__init__() # From MELGAN UpperCamelCase = math.log(1e-5 ) # Matches MelGAN training. UpperCamelCase = 4.0 # Largest value for most examples UpperCamelCase = 128 self.register_modules( notes_encoder=_SCREAMING_SNAKE_CASE , continuous_encoder=_SCREAMING_SNAKE_CASE , decoder=_SCREAMING_SNAKE_CASE , scheduler=_SCREAMING_SNAKE_CASE , melgan=_SCREAMING_SNAKE_CASE , ) def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=(-1.0, 1.0) , _SCREAMING_SNAKE_CASE=False ) -> Any: """simple docstring""" UpperCamelCase ,UpperCamelCase = output_range if clip: UpperCamelCase = torch.clip(_SCREAMING_SNAKE_CASE , self.min_value , self.max_value ) # Scale to [0, 1]. UpperCamelCase = (features - self.min_value) / (self.max_value - self.min_value) # Scale to [min_out, max_out]. return zero_one * (max_out - min_out) + min_out def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=(-1.0, 1.0) , _SCREAMING_SNAKE_CASE=False ) -> Optional[Any]: """simple docstring""" UpperCamelCase ,UpperCamelCase = input_range UpperCamelCase = torch.clip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if clip else outputs # Scale to [0, 1]. UpperCamelCase = (outputs - min_out) / (max_out - min_out) # Scale to [self.min_value, self.max_value]. return zero_one * (self.max_value - self.min_value) + self.min_value def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" UpperCamelCase = input_tokens > 0 UpperCamelCase ,UpperCamelCase = self.notes_encoder( encoder_input_tokens=_SCREAMING_SNAKE_CASE , encoder_inputs_mask=_SCREAMING_SNAKE_CASE ) UpperCamelCase ,UpperCamelCase = self.continuous_encoder( encoder_inputs=_SCREAMING_SNAKE_CASE , encoder_inputs_mask=_SCREAMING_SNAKE_CASE ) return [(tokens_encoded, tokens_mask), (continuous_encoded, continuous_mask)] def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" UpperCamelCase = noise_time if not torch.is_tensor(_SCREAMING_SNAKE_CASE ): UpperCamelCase = torch.tensor([timesteps] , dtype=torch.long , device=input_tokens.device ) elif torch.is_tensor(_SCREAMING_SNAKE_CASE ) and len(timesteps.shape ) == 0: UpperCamelCase = timesteps[None].to(input_tokens.device ) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML UpperCamelCase = timesteps * torch.ones(input_tokens.shape[0] , dtype=timesteps.dtype , device=timesteps.device ) UpperCamelCase = self.decoder( encodings_and_masks=_SCREAMING_SNAKE_CASE , decoder_input_tokens=_SCREAMING_SNAKE_CASE , decoder_noise_time=_SCREAMING_SNAKE_CASE ) return logits @torch.no_grad() def __call__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 100 , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = "numpy" , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1 , ) -> Union[AudioPipelineOutput, Tuple]: """simple docstring""" if (callback_steps is None) or ( callback_steps is not None and (not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) or callback_steps <= 0) ): raise ValueError( F"`callback_steps` has to be a positive integer but is {callback_steps} of type" F" {type(_SCREAMING_SNAKE_CASE )}." ) UpperCamelCase = np.zeros([1, TARGET_FEATURE_LENGTH, self.n_dims] , dtype=np.floataa ) UpperCamelCase = np.zeros([1, 0, self.n_dims] , np.floataa ) UpperCamelCase = torch.ones((1, TARGET_FEATURE_LENGTH) , dtype=_SCREAMING_SNAKE_CASE , device=self.device ) for i, encoder_input_tokens in enumerate(_SCREAMING_SNAKE_CASE ): if i == 0: UpperCamelCase = torch.from_numpy(pred_mel[:1].copy() ).to( device=self.device , dtype=self.decoder.dtype ) # The first chunk has no previous context. UpperCamelCase = torch.zeros((1, TARGET_FEATURE_LENGTH) , dtype=_SCREAMING_SNAKE_CASE , device=self.device ) else: # The full song pipeline does not feed in a context feature, so the mask # will be all 0s after the feature converter. Because we know we're # feeding in a full context chunk from the previous prediction, set it # to all 1s. UpperCamelCase = ones UpperCamelCase = self.scale_features( _SCREAMING_SNAKE_CASE , output_range=[-1.0, 1.0] , clip=_SCREAMING_SNAKE_CASE ) UpperCamelCase = self.encode( input_tokens=torch.IntTensor([encoder_input_tokens] ).to(device=self.device ) , continuous_inputs=_SCREAMING_SNAKE_CASE , continuous_mask=_SCREAMING_SNAKE_CASE , ) # Sample encoder_continuous_inputs shaped gaussian noise to begin loop UpperCamelCase = randn_tensor( shape=encoder_continuous_inputs.shape , generator=_SCREAMING_SNAKE_CASE , device=self.device , dtype=self.decoder.dtype , ) # set step values self.scheduler.set_timesteps(_SCREAMING_SNAKE_CASE ) # Denoising diffusion loop for j, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): UpperCamelCase = self.decode( encodings_and_masks=_SCREAMING_SNAKE_CASE , input_tokens=_SCREAMING_SNAKE_CASE , noise_time=t / self.scheduler.config.num_train_timesteps , ) # Compute previous output: x_t -> x_t-1 UpperCamelCase = self.scheduler.step(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE ).prev_sample UpperCamelCase = self.scale_to_features(_SCREAMING_SNAKE_CASE , input_range=[-1.0, 1.0] ) UpperCamelCase = mel[:1] UpperCamelCase = mel.cpu().float().numpy() UpperCamelCase = np.concatenate([full_pred_mel, pred_mel[:1]] , axis=1 ) # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) logger.info("""Generated segment""" , _SCREAMING_SNAKE_CASE ) if output_type == "numpy" and not is_onnx_available(): raise ValueError( """Cannot return output in 'np' format if ONNX is not available. Make sure to have ONNX installed or set 'output_type' to 'mel'.""" ) elif output_type == "numpy" and self.melgan is None: raise ValueError( """Cannot return output in 'np' format if melgan component is not defined. Make sure to define `self.melgan` or set 'output_type' to 'mel'.""" ) if output_type == "numpy": UpperCamelCase = self.melgan(input_features=full_pred_mel.astype(np.floataa ) ) else: UpperCamelCase = full_pred_mel if not return_dict: return (output,) return AudioPipelineOutput(audios=_SCREAMING_SNAKE_CASE )
321
1
def __snake_case ( _lowerCAmelCase : int ) -> None: A_ : Union[str, Any] = generate_pascal_triangle(_lowerCAmelCase ) for row_idx in range(_lowerCAmelCase ): # Print left spaces for _ in range(num_rows - row_idx - 1 ): print(end=" " ) # Print row values for col_idx in range(row_idx + 1 ): if col_idx != row_idx: print(triangle[row_idx][col_idx] , end=" " ) else: print(triangle[row_idx][col_idx] , end="" ) print() def __snake_case ( _lowerCAmelCase : int ) -> list[list[int]]: if not isinstance(_lowerCAmelCase , _lowerCAmelCase ): raise TypeError("The input value of 'num_rows' should be 'int'" ) if num_rows == 0: return [] elif num_rows < 0: raise ValueError( "The input value of 'num_rows' should be greater than or equal to 0" ) A_ : list[list[int]] = [] for current_row_idx in range(_lowerCAmelCase ): A_ : Dict = populate_current_row(_lowerCAmelCase , _lowerCAmelCase ) triangle.append(_lowerCAmelCase ) return triangle def __snake_case ( _lowerCAmelCase : list[list[int]] , _lowerCAmelCase : int ) -> list[int]: A_ : Tuple = [-1] * (current_row_idx + 1) # first and last elements of current row are equal to 1 A_ , A_ : str = 1, 1 for current_col_idx in range(1 , _lowerCAmelCase ): calculate_current_element( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) return current_row def __snake_case ( _lowerCAmelCase : list[list[int]] , _lowerCAmelCase : list[int] , _lowerCAmelCase : int , _lowerCAmelCase : int , ) -> None: A_ : List[Any] = triangle[current_row_idx - 1][current_col_idx - 1] A_ : List[Any] = triangle[current_row_idx - 1][current_col_idx] A_ : Union[str, Any] = above_to_left_elt + above_to_right_elt def __snake_case ( _lowerCAmelCase : int ) -> list[list[int]]: if not isinstance(_lowerCAmelCase , _lowerCAmelCase ): raise TypeError("The input value of 'num_rows' should be 'int'" ) if num_rows == 0: return [] elif num_rows < 0: raise ValueError( "The input value of 'num_rows' should be greater than or equal to 0" ) A_ : list[list[int]] = [[1]] for row_index in range(1 , _lowerCAmelCase ): A_ : Optional[int] = [0] + result[-1] + [0] A_ : Dict = row_index + 1 # Calculate the number of distinct elements in a row A_ : Optional[int] = sum(divmod(_lowerCAmelCase , 2 ) ) A_ : Optional[Any] = [ temp_row[i - 1] + temp_row[i] for i in range(1 , distinct_elements + 1 ) ] A_ : str = row_first_half[: (row_index + 1) // 2] row_second_half.reverse() A_ : List[Any] = row_first_half + row_second_half result.append(_lowerCAmelCase ) return result def __snake_case ( ) -> None: from collections.abc import Callable from timeit import timeit def benchmark_a_function(_lowerCAmelCase : Callable , _lowerCAmelCase : int ) -> None: A_ : List[str] = f"{func.__name__}({value})" A_ : str = timeit(f"__main__.{call}" , setup="import __main__" ) # print(f"{call:38} = {func(value)} -- {timing:.4f} seconds") print(f"{call:38} -- {timing:.4f} seconds" ) for value in range(15 ): # (1, 7, 14): for func in (generate_pascal_triangle, generate_pascal_triangle_optimized): benchmark_a_function(_lowerCAmelCase , _lowerCAmelCase ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
70
from math import pi, sqrt def __snake_case ( _lowerCAmelCase : float ) -> float: if num <= 0: raise ValueError("math domain error" ) if num > 1_71.5: raise OverflowError("math range error" ) elif num - int(_lowerCAmelCase ) not in (0, 0.5): raise NotImplementedError("num must be an integer or a half-integer" ) elif num == 0.5: return sqrt(_lowerCAmelCase ) else: return 1.0 if num == 1 else (num - 1) * gamma(num - 1 ) def __snake_case ( ) -> None: assert gamma(0.5 ) == sqrt(_lowerCAmelCase ) assert gamma(1 ) == 1.0 assert gamma(2 ) == 1.0 if __name__ == "__main__": from doctest import testmod testmod() _lowerCAmelCase : List[str] = 1.0 while num: _lowerCAmelCase : List[str] = float(input('''Gamma of: ''')) print(F'''gamma({num}) = {gamma(num)}''') print('''\nEnter 0 to exit...''')
70
1
from arguments import InitializationArguments from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, HfArgumentParser # Configuration lowercase : str = HfArgumentParser(InitializationArguments) lowercase : int = parser.parse_args() # Load codeparrot tokenizer trained for Python code tokenization lowercase : Optional[int] = AutoTokenizer.from_pretrained(args.tokenizer_name) # Config: "scale_attn_by_layer_idx" and "reorder_and_upcast_attn" are Mistral stability tweaks lowercase : Optional[Any] = { """vocab_size""": len(tokenizer), """scale_attn_by_inverse_layer_idx""": True, """reorder_and_upcast_attn""": True, } # Load model config (GPT-2 large in this case) lowercase : str = AutoConfig.from_pretrained(args.config_name, **config_kwargs) # Initialize new model with config lowercase : Union[str, Any] = AutoModelForCausalLM.from_config(config) # Save model to the hub model.save_pretrained(args.model_name, push_to_hub=args.push_to_hub)
20
"""simple docstring""" from ....configuration_utils import PretrainedConfig from ....utils import logging lowerCAmelCase__ = logging.get_logger(__name__) # TODO: upload to AWS lowerCAmelCase__ = { '''yjernite/retribert-base-uncased''': ( '''https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/config.json''' ), } class __snake_case ( _lowercase): snake_case__ : int = "retribert" def __init__( self : Optional[int] , __lowerCAmelCase : str=3_0_5_2_2 , __lowerCAmelCase : Tuple=7_6_8 , __lowerCAmelCase : Union[str, Any]=8 , __lowerCAmelCase : Any=1_2 , __lowerCAmelCase : Optional[int]=3_0_7_2 , __lowerCAmelCase : List[str]="gelu" , __lowerCAmelCase : Tuple=0.1 , __lowerCAmelCase : Tuple=0.1 , __lowerCAmelCase : Tuple=5_1_2 , __lowerCAmelCase : List[str]=2 , __lowerCAmelCase : Tuple=0.02 , __lowerCAmelCase : Optional[Any]=1E-12 , __lowerCAmelCase : Tuple=True , __lowerCAmelCase : Any=1_2_8 , __lowerCAmelCase : Optional[int]=0 , **__lowerCAmelCase : str , ): """simple docstring""" super().__init__(pad_token_id=__lowerCAmelCase , **__lowerCAmelCase ) _lowerCamelCase : Dict = vocab_size _lowerCamelCase : Union[str, Any] = hidden_size _lowerCamelCase : Dict = num_hidden_layers _lowerCamelCase : int = num_attention_heads _lowerCamelCase : int = hidden_act _lowerCamelCase : str = intermediate_size _lowerCamelCase : Union[str, Any] = hidden_dropout_prob _lowerCamelCase : List[Any] = attention_probs_dropout_prob _lowerCamelCase : Optional[int] = max_position_embeddings _lowerCamelCase : List[Any] = type_vocab_size _lowerCamelCase : Any = initializer_range _lowerCamelCase : Optional[int] = layer_norm_eps _lowerCamelCase : int = share_encoders _lowerCamelCase : Optional[Any] = projection_dim
72
0
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 snake_case_ ( lowerCAmelCase_ : Union[str, Any] ): return EnvironmentCommand() def snake_case_ ( lowerCAmelCase_ : Tuple ): return EnvironmentCommand(args.accelerate_config_file ) class lowerCAmelCase ( __a ): '''simple docstring''' @staticmethod def lowerCAmelCase ( __a : ArgumentParser ) -> str: """simple docstring""" __lowercase : Union[str, Any] = 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 : Union[str, Any] ) -> None: """simple docstring""" __lowercase : Optional[Any] = accelerate_config_file def lowerCAmelCase ( self : List[Any] ) -> List[Any]: """simple docstring""" __lowercase : Dict = """not installed""" if is_safetensors_available(): import safetensors __lowercase : int = safetensors.__version__ elif importlib.util.find_spec("""safetensors""" ) is not None: import safetensors __lowercase : Union[str, Any] = F"{safetensors.__version__} but is ignored because of PyTorch version too old." __lowercase : Union[str, Any] = """not installed""" __lowercase : int = """not found""" if is_accelerate_available(): import accelerate from accelerate.commands.config import default_config_file, load_config_from_file __lowercase : Optional[int] = accelerate.__version__ # Get the default from the config file. if self._accelerate_config_file is not None or os.path.isfile(__a ): __lowercase : Optional[Any] = load_config_from_file(self._accelerate_config_file ).to_dict() __lowercase : List[Any] = ( """\n""".join([F"\t- {prop}: {val}" for prop, val in accelerate_config.items()] ) if isinstance(__a , __a ) else F"\t{accelerate_config}" ) __lowercase : int = """not installed""" __lowercase : Union[str, Any] = """NA""" if is_torch_available(): import torch __lowercase : Optional[Any] = torch.__version__ __lowercase : List[str] = torch.cuda.is_available() __lowercase : Union[str, Any] = """not installed""" __lowercase : Tuple = """NA""" if is_tf_available(): import tensorflow as tf __lowercase : Dict = tf.__version__ try: # deprecated in v2.1 __lowercase : Any = tf.test.is_gpu_available() except AttributeError: # returns list of devices, convert to bool __lowercase : int = bool(tf.config.list_physical_devices("""GPU""" ) ) __lowercase : Optional[Any] = """not installed""" __lowercase : List[Any] = """not installed""" __lowercase : str = """not installed""" __lowercase : Tuple = """NA""" if is_flax_available(): import flax import jax import jaxlib __lowercase : int = flax.__version__ __lowercase : int = jax.__version__ __lowercase : List[str] = jaxlib.__version__ __lowercase : str = jax.lib.xla_bridge.get_backend().platform __lowercase : List[Any] = { """`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 lowerCAmelCase ( __a : List[Any] ) -> List[str]: """simple docstring""" return "\n".join([F"- {prop}: {val}" for prop, val in d.items()] ) + "\n"
306
import json import multiprocessing as mp import re from collections import defaultdict from functools import partial from typing import Dict, List, Optional, Set, Tuple, Type from datasets import Dataset from datasketch import MinHash, MinHashLSH from dpu_utils.utils.iterators import ThreadedIterator from tqdm import tqdm lowerCamelCase : str = re.compile('''[^A-Za-z_0-9]''') # parameters used in DuplicationIndex lowerCamelCase : Union[str, Any] = 10 lowerCamelCase : List[str] = 2_56 def snake_case_ ( lowerCAmelCase_ : List[str] ): if len(lowerCAmelCase_ ) < MIN_NUM_TOKENS: return None __lowercase : Dict = MinHash(num_perm=lowerCAmelCase_ ) for token in set(lowerCAmelCase_ ): min_hash.update(token.encode() ) return min_hash def snake_case_ ( lowerCAmelCase_ : str ): return {t for t in NON_ALPHA.split(lowerCAmelCase_ ) if len(t.strip() ) > 0} class lowerCAmelCase : '''simple docstring''' def __init__( self : List[str] , *, __a : float = 0.85 , ) -> Union[str, Any]: """simple docstring""" __lowercase : Optional[Any] = duplication_jaccard_threshold __lowercase : Optional[Any] = NUM_PERM __lowercase : List[Any] = MinHashLSH(threshold=self._duplication_jaccard_threshold , num_perm=self._num_perm ) __lowercase : List[str] = defaultdict(__a ) def lowerCAmelCase ( self : str , __a : Tuple , __a : MinHash ) -> None: """simple docstring""" __lowercase : List[Any] = self._index.query(__a ) if code_key in self._index.keys: print(F"Duplicate key {code_key}" ) return self._index.insert(__a , __a ) if len(__a ) > 0: for base_duplicate in close_duplicates: if base_duplicate in self._duplicate_clusters: self._duplicate_clusters[base_duplicate].add(__a ) break else: self._duplicate_clusters[close_duplicates[0]].add(__a ) def lowerCAmelCase ( self : Union[str, Any] ) -> List[List[Dict]]: """simple docstring""" __lowercase : Dict = [] for base, duplicates in self._duplicate_clusters.items(): __lowercase : List[str] = [base] + list(__a ) # reformat the cluster to be a list of dict __lowercase : Optional[Any] = [{"""base_index""": el[0], """repo_name""": el[1], """path""": el[2]} for el in cluster] duplicate_clusters.append(__a ) return duplicate_clusters def lowerCAmelCase ( self : Any , __a : int ) -> None: """simple docstring""" __lowercase : Tuple = self.get_duplicate_clusters() with open(__a , """w""" ) as f: json.dump(__a , __a ) def snake_case_ ( lowerCAmelCase_ : str ): __lowercase , __lowercase : Union[str, Any] = element __lowercase : Optional[Any] = get_min_hash([t for t in NON_ALPHA.split(data["""content"""] ) if len(t.strip() ) > 0] ) if min_hash is not None: return (index, data["repo_name"], data["path"]), min_hash def snake_case_ ( lowerCAmelCase_ : Type[Dataset] ): with mp.Pool() as pool: for data in pool.imap_unordered( _compute_min_hash , ThreadedIterator(lowerCAmelCase_ , max_queue_size=10000 ) , chunksize=100 , ): if data is not None: yield data def snake_case_ ( lowerCAmelCase_ : Type[Dataset] , lowerCAmelCase_ : float ): __lowercase : Dict = DuplicationIndex(duplication_jaccard_threshold=lowerCAmelCase_ ) for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(lowerCAmelCase_ ) ) , max_queue_size=100 ) ): di.add(lowerCAmelCase_ , lowerCAmelCase_ ) # Returns a List[Cluster] where Cluster is List[str] with the filenames. return di.get_duplicate_clusters() def snake_case_ ( lowerCAmelCase_ : str , lowerCAmelCase_ : str ): __lowercase : List[str] = get_tokens(lowerCAmelCase_ ) __lowercase : Dict = get_tokens(lowerCAmelCase_ ) return len(tokensa & tokensa ) / len(tokensa | tokensa ) lowerCamelCase : List[str] = None def snake_case_ ( lowerCAmelCase_ : List[str] , lowerCAmelCase_ : List[Any] ): __lowercase : Union[str, Any] = [] for elementa in cluster: __lowercase : Tuple = _shared_dataset[elementa["""base_index"""]]["""content"""] for elementa in extremes: __lowercase : Dict = _shared_dataset[elementa["""base_index"""]]["""content"""] if jaccard_similarity(lowerCAmelCase_ , lowerCAmelCase_ ) >= jaccard_threshold: elementa["copies"] += 1 break else: __lowercase : Dict = 1 extremes.append(lowerCAmelCase_ ) return extremes def snake_case_ ( lowerCAmelCase_ : List[str] , lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : Tuple ): global _shared_dataset __lowercase : Tuple = dataset __lowercase : Optional[int] = [] __lowercase : str = partial(_find_cluster_extremes_shared , jaccard_threshold=lowerCAmelCase_ ) with mp.Pool() as pool: for extremes in tqdm( pool.imap_unordered( lowerCAmelCase_ , lowerCAmelCase_ , ) , total=len(lowerCAmelCase_ ) , ): extremes_list.append(lowerCAmelCase_ ) return extremes_list def snake_case_ ( lowerCAmelCase_ : Type[Dataset] , lowerCAmelCase_ : float = 0.85 ): __lowercase : Optional[int] = make_duplicate_clusters(lowerCAmelCase_ , lowerCAmelCase_ ) __lowercase : Tuple = {x["""base_index"""] for cluster in duplicate_clusters for x in cluster} __lowercase : int = {} __lowercase : Dict = find_extremes(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) for extremes in extremes_clusters: for element in extremes: __lowercase : Optional[Any] = element __lowercase : int = duplicate_indices - set(extreme_dict.keys() ) __lowercase : int = dataset.filter(lambda lowerCAmelCase_ , lowerCAmelCase_ : idx not in remove_indices , with_indices=lowerCAmelCase_ ) # update duplicate_clusters for cluster in duplicate_clusters: for element in cluster: __lowercase : List[str] = element["""base_index"""] in extreme_dict if element["is_extreme"]: __lowercase : str = extreme_dict[element["""base_index"""]]["""copies"""] print(F"Original dataset size: {len(lowerCAmelCase_ )}" ) print(F"Number of duplicate clusters: {len(lowerCAmelCase_ )}" ) print(F"Files in duplicate cluster: {len(lowerCAmelCase_ )}" ) print(F"Unique files in duplicate cluster: {len(lowerCAmelCase_ )}" ) print(F"Filtered dataset size: {len(lowerCAmelCase_ )}" ) return ds_filter, duplicate_clusters
306
1
import numpy as np from matplotlib import pyplot as plt from sklearn.datasets import load_iris from sklearn.metrics import ConfusionMatrixDisplay from sklearn.model_selection import train_test_split from xgboost import XGBClassifier def lowerCAmelCase_ ( _snake_case : dict ) -> tuple: '''simple docstring''' return (data["data"], data["target"]) def lowerCAmelCase_ ( _snake_case : np.ndarray , _snake_case : np.ndarray ) -> XGBClassifier: '''simple docstring''' __magic_name__ : str = XGBClassifier() classifier.fit(_snake_case , _snake_case ) return classifier def lowerCAmelCase_ ( ) -> None: '''simple docstring''' __magic_name__ : str = load_iris() __magic_name__ , __magic_name__ : List[Any] = data_handling(_snake_case ) __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ : List[str] = train_test_split( _snake_case , _snake_case , test_size=0.25 ) __magic_name__ : Optional[int] = iris["target_names"] # Create an XGBoost Classifier from the training data __magic_name__ : Dict = xgboost(_snake_case , _snake_case ) # Display the confusion matrix of the classifier with both training and test sets ConfusionMatrixDisplay.from_estimator( _snake_case , _snake_case , _snake_case , display_labels=_snake_case , cmap="Blues" , normalize="true" , ) plt.title("Normalized Confusion Matrix - IRIS Dataset" ) plt.show() if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
281
import argparse import csv import logging import os import random import numpy as np import torch from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset from tqdm import tqdm, trange from transformers import ( CONFIG_NAME, WEIGHTS_NAME, AdamW, OpenAIGPTDoubleHeadsModel, OpenAIGPTTokenizer, get_linear_schedule_with_warmup, ) logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO ) snake_case : Optional[int] = logging.getLogger(__name__) def lowerCAmelCase_ ( _snake_case : Dict , _snake_case : Union[str, Any] ) -> Tuple: '''simple docstring''' __magic_name__ : List[str] = np.argmax(_snake_case , axis=1 ) return np.sum(outputs == labels ) def lowerCAmelCase_ ( _snake_case : Optional[Any] ) -> Dict: '''simple docstring''' with open(_snake_case , encoding="utf_8" ) as f: __magic_name__ : List[str] = csv.reader(_snake_case ) __magic_name__ : List[Any] = [] next(_snake_case ) # skip the first line for line in tqdm(_snake_case ): output.append((" ".join(line[1:5] ), line[5], line[6], int(line[-1] ) - 1) ) return output def lowerCAmelCase_ ( _snake_case : str , _snake_case : Tuple , _snake_case : Union[str, Any] , _snake_case : List[Any] , _snake_case : Tuple , _snake_case : Optional[int] ) -> int: '''simple docstring''' __magic_name__ : Optional[int] = [] for dataset in encoded_datasets: __magic_name__ : Union[str, Any] = len(_snake_case ) __magic_name__ : Dict = np.zeros((n_batch, 2, input_len) , dtype=np.intaa ) __magic_name__ : List[str] = np.zeros((n_batch, 2) , dtype=np.intaa ) __magic_name__ : Optional[int] = np.full((n_batch, 2, input_len) , fill_value=-100 , dtype=np.intaa ) __magic_name__ : int = np.zeros((n_batch,) , dtype=np.intaa ) for ( i, (story, conta, conta, mc_label), ) in enumerate(_snake_case ): __magic_name__ : Dict = [start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token] __magic_name__ : Dict = [start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token] __magic_name__ : str = with_conta __magic_name__ : Tuple = with_conta __magic_name__ : Union[str, Any] = len(_snake_case ) - 1 __magic_name__ : int = len(_snake_case ) - 1 __magic_name__ : Optional[Any] = with_conta __magic_name__ : Optional[Any] = with_conta __magic_name__ : Optional[int] = mc_label __magic_name__ : str = (input_ids, mc_token_ids, lm_labels, mc_labels) tensor_datasets.append(tuple(torch.tensor(_snake_case ) for t in all_inputs ) ) return tensor_datasets def lowerCAmelCase_ ( ) -> List[Any]: '''simple docstring''' __magic_name__ : Any = argparse.ArgumentParser() parser.add_argument("--model_name" , type=_snake_case , default="openai-gpt" , help="pretrained model name" ) parser.add_argument("--do_train" , action="store_true" , help="Whether to run training." ) parser.add_argument("--do_eval" , action="store_true" , help="Whether to run eval on the dev set." ) parser.add_argument( "--output_dir" , default=_snake_case , type=_snake_case , required=_snake_case , help="The output directory where the model predictions and checkpoints will be written." , ) parser.add_argument("--train_dataset" , type=_snake_case , default="" ) parser.add_argument("--eval_dataset" , type=_snake_case , default="" ) parser.add_argument("--seed" , type=_snake_case , default=42 ) parser.add_argument("--num_train_epochs" , type=_snake_case , default=3 ) parser.add_argument("--train_batch_size" , type=_snake_case , default=8 ) parser.add_argument("--eval_batch_size" , type=_snake_case , default=16 ) parser.add_argument("--adam_epsilon" , default=1E-8 , type=_snake_case , help="Epsilon for Adam optimizer." ) parser.add_argument("--max_grad_norm" , type=_snake_case , default=1 ) parser.add_argument( "--max_steps" , default=-1 , type=_snake_case , help=( "If > 0: set total number of training steps to perform. Override num_train_epochs." ) , ) parser.add_argument( "--gradient_accumulation_steps" , type=_snake_case , default=1 , help="Number of updates steps to accumulate before performing a backward/update pass." , ) parser.add_argument("--learning_rate" , type=_snake_case , default=6.25E-5 ) parser.add_argument("--warmup_steps" , default=0 , type=_snake_case , help="Linear warmup over warmup_steps." ) parser.add_argument("--lr_schedule" , type=_snake_case , default="warmup_linear" ) parser.add_argument("--weight_decay" , type=_snake_case , default=0.01 ) parser.add_argument("--lm_coef" , type=_snake_case , default=0.9 ) parser.add_argument("--n_valid" , type=_snake_case , default=374 ) parser.add_argument("--server_ip" , type=_snake_case , default="" , help="Can be used for distant debugging." ) parser.add_argument("--server_port" , type=_snake_case , default="" , help="Can be used for distant debugging." ) __magic_name__ : List[Any] = parser.parse_args() print(_snake_case ) if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print("Waiting for debugger attach" ) ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=_snake_case ) ptvsd.wait_for_attach() random.seed(args.seed ) np.random.seed(args.seed ) torch.manual_seed(args.seed ) torch.cuda.manual_seed_all(args.seed ) __magic_name__ : Dict = torch.device("cuda" if torch.cuda.is_available() else "cpu" ) __magic_name__ : Optional[int] = torch.cuda.device_count() logger.info("device: {}, n_gpu {}".format(_snake_case , _snake_case ) ) if not args.do_train and not args.do_eval: raise ValueError("At least one of `do_train` or `do_eval` must be True." ) if not os.path.exists(args.output_dir ): os.makedirs(args.output_dir ) # Load tokenizer and model # This loading functions also add new tokens and embeddings called `special tokens` # These new embeddings will be fine-tuned on the RocStories dataset __magic_name__ : List[Any] = ["_start_", "_delimiter_", "_classify_"] __magic_name__ : Optional[int] = OpenAIGPTTokenizer.from_pretrained(args.model_name ) tokenizer.add_tokens(_snake_case ) __magic_name__ : Optional[Any] = tokenizer.convert_tokens_to_ids(_snake_case ) __magic_name__ : List[str] = OpenAIGPTDoubleHeadsModel.from_pretrained(args.model_name ) model.resize_token_embeddings(len(_snake_case ) ) model.to(_snake_case ) # Load and encode the datasets def tokenize_and_encode(_snake_case : str ): if isinstance(_snake_case , _snake_case ): return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(_snake_case ) ) elif isinstance(_snake_case , _snake_case ): return obj return [tokenize_and_encode(_snake_case ) for o in obj] logger.info("Encoding dataset..." ) __magic_name__ : Optional[int] = load_rocstories_dataset(args.train_dataset ) __magic_name__ : str = load_rocstories_dataset(args.eval_dataset ) __magic_name__ : int = (train_dataset, eval_dataset) __magic_name__ : List[str] = tokenize_and_encode(_snake_case ) # Compute the max input length for the Transformer __magic_name__ : Optional[Any] = model.config.n_positions // 2 - 2 __magic_name__ : Optional[int] = max( len(story[:max_length] ) + max(len(conta[:max_length] ) , len(conta[:max_length] ) ) + 3 for dataset in encoded_datasets for story, conta, conta, _ in dataset ) __magic_name__ : List[str] = min(_snake_case , model.config.n_positions ) # Max size of input for the pre-trained model # Prepare inputs tensors and dataloaders __magic_name__ : List[Any] = pre_process_datasets(_snake_case , _snake_case , _snake_case , *_snake_case ) __magic_name__ , __magic_name__ : Optional[int] = tensor_datasets[0], tensor_datasets[1] __magic_name__ : Tuple = TensorDataset(*_snake_case ) __magic_name__ : Union[str, Any] = RandomSampler(_snake_case ) __magic_name__ : Dict = DataLoader(_snake_case , sampler=_snake_case , batch_size=args.train_batch_size ) __magic_name__ : Any = TensorDataset(*_snake_case ) __magic_name__ : Optional[Any] = SequentialSampler(_snake_case ) __magic_name__ : int = DataLoader(_snake_case , sampler=_snake_case , batch_size=args.eval_batch_size ) # Prepare optimizer if args.do_train: if args.max_steps > 0: __magic_name__ : Tuple = args.max_steps __magic_name__ : List[str] = args.max_steps // (len(_snake_case ) // args.gradient_accumulation_steps) + 1 else: __magic_name__ : List[str] = len(_snake_case ) // args.gradient_accumulation_steps * args.num_train_epochs __magic_name__ : str = list(model.named_parameters() ) __magic_name__ : Dict = ["bias", "LayerNorm.bias", "LayerNorm.weight"] __magic_name__ : str = [ { "params": [p for n, p in param_optimizer if not any(nd in n for nd in no_decay )], "weight_decay": args.weight_decay, }, {"params": [p for n, p in param_optimizer if any(nd in n for nd in no_decay )], "weight_decay": 0.0}, ] __magic_name__ : str = AdamW(_snake_case , lr=args.learning_rate , eps=args.adam_epsilon ) __magic_name__ : List[str] = get_linear_schedule_with_warmup( _snake_case , num_warmup_steps=args.warmup_steps , num_training_steps=_snake_case ) if args.do_train: __magic_name__ , __magic_name__ , __magic_name__ : Union[str, Any] = 0, 0, None model.train() for _ in trange(int(args.num_train_epochs ) , desc="Epoch" ): __magic_name__ : List[str] = 0 __magic_name__ : Tuple = 0 __magic_name__ : Dict = tqdm(_snake_case , desc="Training" ) for step, batch in enumerate(_snake_case ): __magic_name__ : Optional[Any] = tuple(t.to(_snake_case ) for t in batch ) __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ : Dict = batch __magic_name__ : Optional[Any] = model(_snake_case , mc_token_ids=_snake_case , lm_labels=_snake_case , mc_labels=_snake_case ) __magic_name__ : Optional[Any] = args.lm_coef * losses[0] + losses[1] loss.backward() optimizer.step() scheduler.step() optimizer.zero_grad() tr_loss += loss.item() __magic_name__ : List[str] = ( loss.item() if exp_average_loss is None else 0.7 * exp_average_loss + 0.3 * loss.item() ) nb_tr_steps += 1 __magic_name__ : int = "Training loss: {:.2e} lr: {:.2e}".format(_snake_case , scheduler.get_lr()[0] ) # Save a trained model if args.do_train: # Save a trained model, configuration and tokenizer __magic_name__ : Dict = model.module if hasattr(_snake_case , "module" ) else model # Only save the model itself # If we save using the predefined names, we can load using `from_pretrained` __magic_name__ : List[Any] = os.path.join(args.output_dir , _snake_case ) __magic_name__ : Dict = os.path.join(args.output_dir , _snake_case ) torch.save(model_to_save.state_dict() , _snake_case ) model_to_save.config.to_json_file(_snake_case ) tokenizer.save_vocabulary(args.output_dir ) # Load a trained model and vocabulary that you have fine-tuned __magic_name__ : Dict = OpenAIGPTDoubleHeadsModel.from_pretrained(args.output_dir ) __magic_name__ : Optional[int] = OpenAIGPTTokenizer.from_pretrained(args.output_dir ) model.to(_snake_case ) if args.do_eval: model.eval() __magic_name__ , __magic_name__ : Any = 0, 0 __magic_name__ , __magic_name__ : Union[str, Any] = 0, 0 for batch in tqdm(_snake_case , desc="Evaluating" ): __magic_name__ : int = tuple(t.to(_snake_case ) for t in batch ) __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ : Union[str, Any] = batch with torch.no_grad(): __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ : Dict = model( _snake_case , mc_token_ids=_snake_case , lm_labels=_snake_case , mc_labels=_snake_case ) __magic_name__ : Tuple = mc_logits.detach().cpu().numpy() __magic_name__ : Any = mc_labels.to("cpu" ).numpy() __magic_name__ : str = accuracy(_snake_case , _snake_case ) eval_loss += mc_loss.mean().item() eval_accuracy += tmp_eval_accuracy nb_eval_examples += input_ids.size(0 ) nb_eval_steps += 1 __magic_name__ : Tuple = eval_loss / nb_eval_steps __magic_name__ : List[Any] = eval_accuracy / nb_eval_examples __magic_name__ : int = tr_loss / nb_tr_steps if args.do_train else None __magic_name__ : Any = {"eval_loss": eval_loss, "eval_accuracy": eval_accuracy, "train_loss": train_loss} __magic_name__ : int = os.path.join(args.output_dir , "eval_results.txt" ) with open(_snake_case , "w" ) as writer: logger.info("***** Eval results *****" ) for key in sorted(result.keys() ): logger.info(" %s = %s" , _snake_case , str(result[key] ) ) writer.write("%s = %s\n" % (key, str(result[key] )) ) if __name__ == "__main__": main()
281
1
def lowerCamelCase__ (__lowerCamelCase ): _SCREAMING_SNAKE_CASE : set[int] = set() # To detect a back edge, keep track of vertices currently in the recursion stack _SCREAMING_SNAKE_CASE : set[int] = set() return any( node not in visited and depth_first_search(__lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ) for node in graph ) def lowerCamelCase__ (__lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ): visited.add(__lowerCamelCase ) rec_stk.add(__lowerCamelCase ) for node in graph[vertex]: if node not in visited: if depth_first_search(__lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ): return True elif node in rec_stk: return True # The node needs to be removed from recursion stack before function ends rec_stk.remove(__lowerCamelCase ) return False if __name__ == "__main__": from doctest import testmod testmod()
325
import logging import os from typing import List, Tuple import numpy as np import psutil import torch import torch.distributed as dist from transformers import RagRetriever UpperCamelCase__ =logging.getLogger(__name__) class lowerCAmelCase__( __lowercase ): '''simple docstring''' def __init__( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=None ) -> Optional[Any]: super().__init__( __lowerCamelCase , question_encoder_tokenizer=__lowerCamelCase , generator_tokenizer=__lowerCamelCase , index=__lowerCamelCase , init_retrieval=__lowerCamelCase , ) _SCREAMING_SNAKE_CASE : List[Any] = None def UpperCamelCase_ ( self , __lowerCamelCase ) -> Any: logger.info("initializing retrieval" ) # initializing a separate process group for retrieval as the default # nccl backend doesn't support gather/scatter operations while gloo # is too slow to replace nccl for the core gpu communication if dist.is_initialized(): logger.info("dist initialized" ) # needs to be set manually _SCREAMING_SNAKE_CASE : List[str] = self._infer_socket_ifname() # avoid clash with the NCCL port _SCREAMING_SNAKE_CASE : List[Any] = str(distributed_port + 1 ) _SCREAMING_SNAKE_CASE : int = dist.new_group(ranks=__lowerCamelCase , backend="gloo" ) # initialize retriever only on the main worker if not dist.is_initialized() or self._is_main(): logger.info("dist not initialized / main" ) self.index.init_index() # all processes wait untill the retriever is initialized by the main process if dist.is_initialized(): torch.distributed.barrier(group=self.process_group ) def UpperCamelCase_ ( self ) -> Optional[Any]: return dist.get_rank(group=self.process_group ) == 0 def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=torch.floataa ) -> Optional[Any]: _SCREAMING_SNAKE_CASE : Optional[int] = torch.empty(__lowerCamelCase , dtype=__lowerCamelCase ) dist.scatter(__lowerCamelCase , src=0 , scatter_list=__lowerCamelCase , group=self.process_group ) return target_tensor def UpperCamelCase_ ( self ) -> Tuple: _SCREAMING_SNAKE_CASE : int = psutil.net_if_addrs() # a hacky way to deal with varying network interface names _SCREAMING_SNAKE_CASE : Any = next((addr for addr in addrs if addr.startswith("e" )) , __lowerCamelCase ) return ifname def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase ) -> Tuple[np.ndarray, List[dict]]: # single GPU training if not dist.is_initialized(): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Dict = self._main_retrieve(__lowerCamelCase , __lowerCamelCase ) return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(__lowerCamelCase ) # distributed training _SCREAMING_SNAKE_CASE : Union[str, Any] = dist.get_world_size(group=self.process_group ) # gather logic _SCREAMING_SNAKE_CASE : Any = None if self._is_main(): _SCREAMING_SNAKE_CASE : Optional[Any] = [torch.empty(question_hidden_states.shape , dtype=torch.floataa ) for _ in range(__lowerCamelCase )] dist.gather(torch.tensor(__lowerCamelCase ) , dst=0 , gather_list=__lowerCamelCase , group=self.process_group ) # scatter logic _SCREAMING_SNAKE_CASE : Optional[int] = question_hidden_states.shape[0] _SCREAMING_SNAKE_CASE : Optional[Any] = [] _SCREAMING_SNAKE_CASE : Optional[int] = [] if self._is_main(): assert len(__lowerCamelCase ) == world_size _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : int = self._main_retrieve(torch.cat(__lowerCamelCase ).numpy() , __lowerCamelCase ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = torch.tensor(__lowerCamelCase ), torch.tensor(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : List[str] = self._chunk_tensor(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Tuple = self._chunk_tensor(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = self._scattered(__lowerCamelCase , [n_queries, n_docs] , target_type=torch.intaa ) _SCREAMING_SNAKE_CASE : Optional[Any] = self._scattered(__lowerCamelCase , [n_queries, n_docs, question_hidden_states.shape[1]] ) return retrieved_doc_embeds.numpy(), doc_ids.numpy(), self.index.get_doc_dicts(__lowerCamelCase )
325
1
import os import pytest from datasets import ( get_dataset_config_info, get_dataset_config_names, get_dataset_infos, get_dataset_split_names, inspect_dataset, inspect_metric, ) UpperCAmelCase__ = pytest.mark.integration @pytest.mark.parametrize('''path''' , ['''paws''', '''csv'''] ) def _a ( a :Dict , a :Optional[int] ) -> List[str]: inspect_dataset(a , a ) a = path + '''.py''' assert script_name in os.listdir(a ) assert "__pycache__" not in os.listdir(a ) @pytest.mark.filterwarnings('''ignore:inspect_metric is deprecated:FutureWarning''' ) @pytest.mark.filterwarnings('''ignore:metric_module_factory is deprecated:FutureWarning''' ) @pytest.mark.parametrize('''path''' , ['''accuracy'''] ) def _a ( a :Any , a :Optional[Any] ) -> Union[str, Any]: inspect_metric(a , a ) a = path + '''.py''' assert script_name in os.listdir(a ) assert "__pycache__" not in os.listdir(a ) @pytest.mark.parametrize( '''path, config_name, expected_splits''' , [ ('''squad''', '''plain_text''', ['''train''', '''validation''']), ('''dalle-mini/wit''', '''dalle-mini--wit''', ['''train''']), ('''paws''', '''labeled_final''', ['''train''', '''test''', '''validation''']), ] , ) def _a ( a :Union[str, Any] , a :List[Any] , a :Optional[Any] ) -> List[str]: a = get_dataset_config_info(a , config_name=a ) assert info.config_name == config_name assert list(info.splits.keys() ) == expected_splits @pytest.mark.parametrize( '''path, config_name, expected_exception''' , [ ('''paws''', None, ValueError), ] , ) def _a ( a :str , a :Tuple , a :Any ) -> Tuple: with pytest.raises(a ): get_dataset_config_info(a , config_name=a ) @pytest.mark.parametrize( '''path, expected''' , [ ('''squad''', '''plain_text'''), ('''acronym_identification''', '''default'''), ('''lhoestq/squad''', '''plain_text'''), ('''lhoestq/test''', '''default'''), ('''lhoestq/demo1''', '''lhoestq--demo1'''), ('''dalle-mini/wit''', '''dalle-mini--wit'''), ] , ) def _a ( a :Any , a :Union[str, Any] ) -> Optional[Any]: a = get_dataset_config_names(a ) assert expected in config_names @pytest.mark.parametrize( '''path, expected_configs, expected_splits_in_first_config''' , [ ('''squad''', ['''plain_text'''], ['''train''', '''validation''']), ('''dalle-mini/wit''', ['''dalle-mini--wit'''], ['''train''']), ('''paws''', ['''labeled_final''', '''labeled_swap''', '''unlabeled_final'''], ['''train''', '''test''', '''validation''']), ] , ) def _a ( a :Optional[int] , a :Optional[Any] , a :Optional[Any] ) -> List[Any]: a = get_dataset_infos(a ) assert list(infos.keys() ) == expected_configs a = expected_configs[0] assert expected_config in infos a = infos[expected_config] assert info.config_name == expected_config assert list(info.splits.keys() ) == expected_splits_in_first_config @pytest.mark.parametrize( '''path, expected_config, expected_splits''' , [ ('''squad''', '''plain_text''', ['''train''', '''validation''']), ('''dalle-mini/wit''', '''dalle-mini--wit''', ['''train''']), ('''paws''', '''labeled_final''', ['''train''', '''test''', '''validation''']), ] , ) def _a ( a :str , a :Union[str, Any] , a :Union[str, Any] ) -> Any: a = get_dataset_infos(a ) assert expected_config in infos a = infos[expected_config] assert info.config_name == expected_config assert list(info.splits.keys() ) == expected_splits @pytest.mark.parametrize( '''path, config_name, expected_exception''' , [ ('''paws''', None, ValueError), ] , ) def _a ( a :Dict , a :Any , a :Optional[int] ) -> Tuple: with pytest.raises(a ): get_dataset_split_names(a , config_name=a )
0
def lowerCAmelCase__ ( ) -> Any: '''simple docstring''' for n in range(1 , 1_0_0_0_0_0_0 ): yield n * (n + 1) // 2 def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Tuple ) -> Any: '''simple docstring''' A__ = 1 A__ = 2 while i * i <= n: A__ = 0 while n % i == 0: n //= i multiplicity += 1 divisors_count *= multiplicity + 1 i += 1 if n > 1: divisors_count *= 2 return divisors_count def lowerCAmelCase__ ( ) -> Dict: '''simple docstring''' return next(i for i in triangle_number_generator() if count_divisors(SCREAMING_SNAKE_CASE_ ) > 5_0_0 ) if __name__ == "__main__": print(solution())
68
0
"""simple docstring""" import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DeiTConfig, DeiTForImageClassificationWithTeacher, DeiTImageProcessor from transformers.utils import logging logging.set_verbosity_info() a_ = logging.get_logger(__name__) def __lowercase ( snake_case_ : List[str] ,snake_case_ : Dict=False ) ->Any: '''simple docstring''' __A : str = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F"""blocks.{i}.norm1.weight""", F"""deit.encoder.layer.{i}.layernorm_before.weight""") ) rename_keys.append((F"""blocks.{i}.norm1.bias""", F"""deit.encoder.layer.{i}.layernorm_before.bias""") ) rename_keys.append((F"""blocks.{i}.attn.proj.weight""", F"""deit.encoder.layer.{i}.attention.output.dense.weight""") ) rename_keys.append((F"""blocks.{i}.attn.proj.bias""", F"""deit.encoder.layer.{i}.attention.output.dense.bias""") ) rename_keys.append((F"""blocks.{i}.norm2.weight""", F"""deit.encoder.layer.{i}.layernorm_after.weight""") ) rename_keys.append((F"""blocks.{i}.norm2.bias""", F"""deit.encoder.layer.{i}.layernorm_after.bias""") ) rename_keys.append((F"""blocks.{i}.mlp.fc1.weight""", F"""deit.encoder.layer.{i}.intermediate.dense.weight""") ) rename_keys.append((F"""blocks.{i}.mlp.fc1.bias""", F"""deit.encoder.layer.{i}.intermediate.dense.bias""") ) rename_keys.append((F"""blocks.{i}.mlp.fc2.weight""", F"""deit.encoder.layer.{i}.output.dense.weight""") ) rename_keys.append((F"""blocks.{i}.mlp.fc2.bias""", F"""deit.encoder.layer.{i}.output.dense.bias""") ) # projection layer + position embeddings rename_keys.extend( [ ('''cls_token''', '''deit.embeddings.cls_token'''), ('''dist_token''', '''deit.embeddings.distillation_token'''), ('''patch_embed.proj.weight''', '''deit.embeddings.patch_embeddings.projection.weight'''), ('''patch_embed.proj.bias''', '''deit.embeddings.patch_embeddings.projection.bias'''), ('''pos_embed''', '''deit.embeddings.position_embeddings'''), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ('''norm.weight''', '''layernorm.weight'''), ('''norm.bias''', '''layernorm.bias'''), ('''pre_logits.fc.weight''', '''pooler.dense.weight'''), ('''pre_logits.fc.bias''', '''pooler.dense.bias'''), ] ) # if just the base model, we should remove "deit" from all keys that start with "deit" __A : Optional[Any] = [(pair[0], pair[1][4:]) if pair[1].startswith('''deit''' ) else pair for pair in rename_keys] else: # layernorm + classification heads rename_keys.extend( [ ('''norm.weight''', '''deit.layernorm.weight'''), ('''norm.bias''', '''deit.layernorm.bias'''), ('''head.weight''', '''cls_classifier.weight'''), ('''head.bias''', '''cls_classifier.bias'''), ('''head_dist.weight''', '''distillation_classifier.weight'''), ('''head_dist.bias''', '''distillation_classifier.bias'''), ] ) return rename_keys def __lowercase ( snake_case_ : Optional[Any] ,snake_case_ : Union[str, Any] ,snake_case_ : Optional[Any]=False ) ->List[Any]: '''simple docstring''' for i in range(config.num_hidden_layers ): if base_model: __A : Tuple = '''''' else: __A : Optional[Any] = '''deit.''' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) __A : Union[str, Any] = state_dict.pop(F"""blocks.{i}.attn.qkv.weight""" ) __A : List[Any] = state_dict.pop(F"""blocks.{i}.attn.qkv.bias""" ) # next, add query, keys and values (in that order) to the state dict __A : List[Any] = in_proj_weight[ : config.hidden_size, : ] __A : Any = in_proj_bias[: config.hidden_size] __A : Union[str, Any] = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] __A : Dict = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] __A : List[Any] = in_proj_weight[ -config.hidden_size :, : ] __A : Union[str, Any] = in_proj_bias[-config.hidden_size :] def __lowercase ( snake_case_ : int ,snake_case_ : Union[str, Any] ,snake_case_ : Tuple ) ->Any: '''simple docstring''' __A : int = dct.pop(snake_case_ ) __A : Union[str, Any] = val def __lowercase ( ) ->int: '''simple docstring''' __A : Any = '''http://images.cocodataset.org/val2017/000000039769.jpg''' __A : int = Image.open(requests.get(snake_case_ ,stream=snake_case_ ).raw ) return im @torch.no_grad() def __lowercase ( snake_case_ : str ,snake_case_ : List[str] ) ->Tuple: '''simple docstring''' __A : Optional[Any] = DeiTConfig() # all deit models have fine-tuned heads __A : List[Any] = False # dataset (fine-tuned on ImageNet 2012), patch_size and image_size __A : Dict = 1000 __A : List[Any] = '''huggingface/label-files''' __A : Union[str, Any] = '''imagenet-1k-id2label.json''' __A : Tuple = json.load(open(hf_hub_download(snake_case_ ,snake_case_ ,repo_type='''dataset''' ) ,'''r''' ) ) __A : str = {int(snake_case_ ): v for k, v in idalabel.items()} __A : str = idalabel __A : Tuple = {v: k for k, v in idalabel.items()} __A : List[Any] = int(deit_name[-6:-4] ) __A : List[Any] = int(deit_name[-3:] ) # size of the architecture if deit_name[9:].startswith('''tiny''' ): __A : int = 192 __A : Optional[Any] = 768 __A : Optional[int] = 12 __A : Tuple = 3 elif deit_name[9:].startswith('''small''' ): __A : int = 384 __A : str = 1536 __A : Any = 12 __A : List[str] = 6 if deit_name[9:].startswith('''base''' ): pass elif deit_name[4:].startswith('''large''' ): __A : List[str] = 1024 __A : Union[str, Any] = 4096 __A : str = 24 __A : str = 16 # load original model from timm __A : Tuple = timm.create_model(snake_case_ ,pretrained=snake_case_ ) timm_model.eval() # load state_dict of original model, remove and rename some keys __A : Union[str, Any] = timm_model.state_dict() __A : Dict = create_rename_keys(snake_case_ ,snake_case_ ) for src, dest in rename_keys: rename_key(snake_case_ ,snake_case_ ,snake_case_ ) read_in_q_k_v(snake_case_ ,snake_case_ ,snake_case_ ) # load HuggingFace model __A : Optional[int] = DeiTForImageClassificationWithTeacher(snake_case_ ).eval() model.load_state_dict(snake_case_ ) # Check outputs on an image, prepared by DeiTImageProcessor __A : int = int( (256 / 224) * config.image_size ) # to maintain same ratio w.r.t. 224 images, see https://github.com/facebookresearch/deit/blob/ab5715372db8c6cad5740714b2216d55aeae052e/datasets.py#L103 __A : List[str] = DeiTImageProcessor(size=snake_case_ ,crop_size=config.image_size ) __A : Tuple = image_processor(images=prepare_img() ,return_tensors='''pt''' ) __A : Optional[int] = encoding['''pixel_values'''] __A : Union[str, Any] = model(snake_case_ ) __A : Any = timm_model(snake_case_ ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(snake_case_ ,outputs.logits ,atol=1e-3 ) Path(snake_case_ ).mkdir(exist_ok=snake_case_ ) print(F"""Saving model {deit_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(snake_case_ ) print(F"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(snake_case_ ) if __name__ == "__main__": a_ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--deit_name""", default="""vit_deit_base_distilled_patch16_224""", type=str, help="""Name of the DeiT timm model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) a_ = parser.parse_args() convert_deit_checkpoint(args.deit_name, args.pytorch_dump_folder_path)
291
"""simple docstring""" import numpy as np import qiskit def __lowercase ( snake_case_ : int = 8 ,snake_case_ : int | None = None ) ->str: '''simple docstring''' __A : str = np.random.default_rng(seed=snake_case_ ) # Roughly 25% of the qubits will contribute to the key. # So we take more than we need. __A : str = 6 * key_len # Measurement basis for Alice's qubits. __A : Any = rng.integers(2 ,size=snake_case_ ) # The set of states Alice will prepare. __A : Any = rng.integers(2 ,size=snake_case_ ) # Measurement basis for Bob's qubits. __A : str = rng.integers(2 ,size=snake_case_ ) # Quantum Circuit to simulate BB84 __A : Dict = qiskit.QuantumCircuit(snake_case_ ,name='''BB84''' ) # Alice prepares her qubits according to rules above. for index, _ in enumerate(snake_case_ ): if alice_state[index] == 1: bbaa_circ.x(snake_case_ ) if alice_basis[index] == 1: bbaa_circ.h(snake_case_ ) bbaa_circ.barrier() # Bob measures the received qubits according to rules above. for index, _ in enumerate(snake_case_ ): if bob_basis[index] == 1: bbaa_circ.h(snake_case_ ) bbaa_circ.barrier() bbaa_circ.measure_all() # Simulate the quantum circuit. __A : List[str] = qiskit.Aer.get_backend('''aer_simulator''' ) # We only need to run one shot because the key is unique. # Multiple shots will produce the same key. __A : List[str] = qiskit.execute(snake_case_ ,snake_case_ ,shots=1 ,seed_simulator=snake_case_ ) # Returns the result of measurement. __A : Union[str, Any] = job.result().get_counts(snake_case_ ).most_frequent() # Extracting the generated key from the simulation results. # Only keep measurement results where Alice and Bob chose the same basis. __A : int = ''''''.join( [ result_bit for alice_basis_bit, bob_basis_bit, result_bit in zip( snake_case_ ,snake_case_ ,snake_case_ ) if alice_basis_bit == bob_basis_bit ] ) # Get final key. Pad with 0 if too short, otherwise truncate. __A : Union[str, Any] = gen_key[:key_len] if len(snake_case_ ) >= key_len else gen_key.ljust(snake_case_ ,'''0''' ) return key if __name__ == "__main__": print(f'''The generated key is : {bbaa(8, seed=0)}''') from doctest import testmod testmod()
291
1
'''simple docstring''' from collections import OrderedDict from typing import Any, List, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import logging A__ : Any =logging.get_logger(__name__) A__ : List[Any] ={ '''Salesforce/codegen-350M-nl''': '''https://huggingface.co/Salesforce/codegen-350M-nl/resolve/main/config.json''', '''Salesforce/codegen-350M-multi''': '''https://huggingface.co/Salesforce/codegen-350M-multi/resolve/main/config.json''', '''Salesforce/codegen-350M-mono''': '''https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/config.json''', '''Salesforce/codegen-2B-nl''': '''https://huggingface.co/Salesforce/codegen-2B-nl/resolve/main/config.json''', '''Salesforce/codegen-2B-multi''': '''https://huggingface.co/Salesforce/codegen-2B-multi/resolve/main/config.json''', '''Salesforce/codegen-2B-mono''': '''https://huggingface.co/Salesforce/codegen-2B-mono/resolve/main/config.json''', '''Salesforce/codegen-6B-nl''': '''https://huggingface.co/Salesforce/codegen-6B-nl/resolve/main/config.json''', '''Salesforce/codegen-6B-multi''': '''https://huggingface.co/Salesforce/codegen-6B-multi/resolve/main/config.json''', '''Salesforce/codegen-6B-mono''': '''https://huggingface.co/Salesforce/codegen-6B-mono/resolve/main/config.json''', '''Salesforce/codegen-16B-nl''': '''https://huggingface.co/Salesforce/codegen-16B-nl/resolve/main/config.json''', '''Salesforce/codegen-16B-multi''': '''https://huggingface.co/Salesforce/codegen-16B-multi/resolve/main/config.json''', '''Salesforce/codegen-16B-mono''': '''https://huggingface.co/Salesforce/codegen-16B-mono/resolve/main/config.json''', } class UpperCAmelCase ( snake_case_ ): _lowercase: str = '''codegen''' _lowercase: Tuple = { '''max_position_embeddings''': '''n_positions''', '''hidden_size''': '''n_embd''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self : List[str] , __snake_case : List[str]=5_04_00 , __snake_case : Tuple=20_48 , __snake_case : Tuple=20_48 , __snake_case : Optional[int]=40_96 , __snake_case : Dict=28 , __snake_case : Any=16 , __snake_case : Any=64 , __snake_case : Dict=None , __snake_case : Optional[Any]="gelu_new" , __snake_case : Tuple=0.0 , __snake_case : str=0.0 , __snake_case : int=0.0 , __snake_case : int=1E-5 , __snake_case : str=0.02 , __snake_case : Tuple=True , __snake_case : List[Any]=5_02_56 , __snake_case : Optional[Any]=5_02_56 , __snake_case : Union[str, Any]=False , **__snake_case : List[str] , ) -> Optional[int]: _lowerCAmelCase = vocab_size _lowerCAmelCase = n_ctx _lowerCAmelCase = n_positions _lowerCAmelCase = n_embd _lowerCAmelCase = n_layer _lowerCAmelCase = n_head _lowerCAmelCase = n_inner _lowerCAmelCase = rotary_dim _lowerCAmelCase = activation_function _lowerCAmelCase = resid_pdrop _lowerCAmelCase = embd_pdrop _lowerCAmelCase = attn_pdrop _lowerCAmelCase = layer_norm_epsilon _lowerCAmelCase = initializer_range _lowerCAmelCase = use_cache _lowerCAmelCase = bos_token_id _lowerCAmelCase = eos_token_id super().__init__( bos_token_id=__snake_case , eos_token_id=__snake_case , tie_word_embeddings=__snake_case , **__snake_case ) class UpperCAmelCase ( snake_case_ ): def __init__( self : Optional[int] , __snake_case : PretrainedConfig , __snake_case : str = "default" , __snake_case : List[PatchingSpec] = None , __snake_case : bool = False , ) -> Dict: super().__init__(__snake_case , task=__snake_case , patching_specs=__snake_case , use_past=__snake_case ) if not getattr(self._config , """pad_token_id""" , __snake_case ): # TODO: how to do that better? _lowerCAmelCase = 0 @property def lowercase__ ( self : Dict ) -> Mapping[str, Mapping[int, str]]: _lowerCAmelCase = OrderedDict({"""input_ids""": {0: """batch""", 1: """sequence"""}} ) if self.use_past: self.fill_with_past_key_values_(__snake_case , direction="""inputs""" ) _lowerCAmelCase = {0: """batch""", 1: """past_sequence + sequence"""} else: _lowerCAmelCase = {0: """batch""", 1: """sequence"""} return common_inputs @property def lowercase__ ( self : List[Any] ) -> int: return self._config.n_layer @property def lowercase__ ( self : Union[str, Any] ) -> int: return self._config.n_head def lowercase__ ( self : List[Any] , __snake_case : PreTrainedTokenizer , __snake_case : int = -1 , __snake_case : int = -1 , __snake_case : bool = False , __snake_case : Optional[TensorType] = None , ) -> Mapping[str, Any]: _lowerCAmelCase = super(__snake_case , self ).generate_dummy_inputs( __snake_case , batch_size=__snake_case , seq_length=__snake_case , is_pair=__snake_case , framework=__snake_case ) # We need to order the input in the way they appears in the forward() _lowerCAmelCase = OrderedDict({"""input_ids""": common_inputs["""input_ids"""]} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed.""" ) else: import torch _lowerCAmelCase , _lowerCAmelCase = common_inputs["""input_ids"""].shape # Not using the same length for past_key_values _lowerCAmelCase = seqlen + 2 _lowerCAmelCase = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) _lowerCAmelCase = [ (torch.zeros(__snake_case ), torch.zeros(__snake_case )) for _ in range(self.num_layers ) ] _lowerCAmelCase = common_inputs["""attention_mask"""] if self.use_past: _lowerCAmelCase = ordered_inputs["""attention_mask"""].dtype _lowerCAmelCase = torch.cat( [ordered_inputs["""attention_mask"""], torch.ones(__snake_case , __snake_case , dtype=__snake_case )] , dim=1 ) return ordered_inputs @property def lowercase__ ( self : str ) -> int: return 13
70
'''simple docstring''' # This model implementation is heavily inspired by https://github.com/haofanwang/ControlNet-for-Diffusers/ import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, ControlNetModel, DDIMScheduler, StableDiffusionControlNetImgaImgPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet import MultiControlNetModel from diffusers.utils import floats_tensor, load_image, load_numpy, randn_tensor, slow, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, ) enable_full_determinism() class UpperCAmelCase ( snake_case_ , snake_case_ , snake_case_ , unittest.TestCase ): _lowercase: Optional[int] = StableDiffusionControlNetImgaImgPipeline _lowercase: Tuple = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''} _lowercase: str = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS _lowercase: Tuple = IMAGE_TO_IMAGE_IMAGE_PARAMS.union({'''control_image'''} ) _lowercase: Union[str, Any] = IMAGE_TO_IMAGE_IMAGE_PARAMS def lowercase__ ( self : List[str] ) -> List[str]: torch.manual_seed(0 ) _lowerCAmelCase = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , ) torch.manual_seed(0 ) _lowerCAmelCase = ControlNetModel( block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , ) torch.manual_seed(0 ) _lowerCAmelCase = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule="""scaled_linear""" , clip_sample=__snake_case , set_alpha_to_one=__snake_case , ) torch.manual_seed(0 ) _lowerCAmelCase = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) torch.manual_seed(0 ) _lowerCAmelCase = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , ) _lowerCAmelCase = CLIPTextModel(__snake_case ) _lowerCAmelCase = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) _lowerCAmelCase = { """unet""": unet, """controlnet""": controlnet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def lowercase__ ( self : Any , __snake_case : str , __snake_case : Any=0 ) -> str: if str(__snake_case ).startswith("""mps""" ): _lowerCAmelCase = torch.manual_seed(__snake_case ) else: _lowerCAmelCase = torch.Generator(device=__snake_case ).manual_seed(__snake_case ) _lowerCAmelCase = 2 _lowerCAmelCase = randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=__snake_case , device=torch.device(__snake_case ) , ) _lowerCAmelCase = floats_tensor(control_image.shape , rng=random.Random(__snake_case ) ).to(__snake_case ) _lowerCAmelCase = image.cpu().permute(0 , 2 , 3 , 1 )[0] _lowerCAmelCase = Image.fromarray(np.uinta(__snake_case ) ).convert("""RGB""" ).resize((64, 64) ) _lowerCAmelCase = { """prompt""": """A painting of a squirrel eating a burger""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", """image""": image, """control_image""": control_image, } return inputs def lowercase__ ( self : Optional[int] ) -> List[Any]: return self._test_attention_slicing_forward_pass(expected_max_diff=2E-3 ) @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def lowercase__ ( self : Tuple ) -> Optional[int]: self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2E-3 ) def lowercase__ ( self : Tuple ) -> Optional[int]: self._test_inference_batch_single_identical(expected_max_diff=2E-3 ) class UpperCAmelCase ( snake_case_ , snake_case_ , unittest.TestCase ): _lowercase: Any = StableDiffusionControlNetImgaImgPipeline _lowercase: Dict = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''} _lowercase: List[Any] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS _lowercase: Any = frozenset([] ) # TO_DO: add image_params once refactored VaeImageProcessor.preprocess def lowercase__ ( self : Optional[Any] ) -> Union[str, Any]: torch.manual_seed(0 ) _lowerCAmelCase = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , ) torch.manual_seed(0 ) def init_weights(__snake_case : Optional[Any] ): if isinstance(__snake_case , torch.nn.Convad ): torch.nn.init.normal(m.weight ) m.bias.data.fill_(1.0 ) _lowerCAmelCase = ControlNetModel( block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , ) controlneta.controlnet_down_blocks.apply(__snake_case ) torch.manual_seed(0 ) _lowerCAmelCase = ControlNetModel( block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , ) controlneta.controlnet_down_blocks.apply(__snake_case ) torch.manual_seed(0 ) _lowerCAmelCase = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule="""scaled_linear""" , clip_sample=__snake_case , set_alpha_to_one=__snake_case , ) torch.manual_seed(0 ) _lowerCAmelCase = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) torch.manual_seed(0 ) _lowerCAmelCase = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , ) _lowerCAmelCase = CLIPTextModel(__snake_case ) _lowerCAmelCase = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) _lowerCAmelCase = MultiControlNetModel([controlneta, controlneta] ) _lowerCAmelCase = { """unet""": unet, """controlnet""": controlnet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def lowercase__ ( self : Tuple , __snake_case : int , __snake_case : List[str]=0 ) -> Union[str, Any]: if str(__snake_case ).startswith("""mps""" ): _lowerCAmelCase = torch.manual_seed(__snake_case ) else: _lowerCAmelCase = torch.Generator(device=__snake_case ).manual_seed(__snake_case ) _lowerCAmelCase = 2 _lowerCAmelCase = [ randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=__snake_case , device=torch.device(__snake_case ) , ), randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=__snake_case , device=torch.device(__snake_case ) , ), ] _lowerCAmelCase = floats_tensor(control_image[0].shape , rng=random.Random(__snake_case ) ).to(__snake_case ) _lowerCAmelCase = image.cpu().permute(0 , 2 , 3 , 1 )[0] _lowerCAmelCase = Image.fromarray(np.uinta(__snake_case ) ).convert("""RGB""" ).resize((64, 64) ) _lowerCAmelCase = { """prompt""": """A painting of a squirrel eating a burger""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", """image""": image, """control_image""": control_image, } return inputs def lowercase__ ( self : List[str] ) -> Dict: _lowerCAmelCase = self.get_dummy_components() _lowerCAmelCase = self.pipeline_class(**__snake_case ) pipe.to(__snake_case ) _lowerCAmelCase = 10.0 _lowerCAmelCase = 4 _lowerCAmelCase = self.get_dummy_inputs(__snake_case ) _lowerCAmelCase = steps _lowerCAmelCase = scale _lowerCAmelCase = pipe(**__snake_case )[0] _lowerCAmelCase = self.get_dummy_inputs(__snake_case ) _lowerCAmelCase = steps _lowerCAmelCase = scale _lowerCAmelCase = pipe(**__snake_case , control_guidance_start=0.1 , control_guidance_end=0.2 )[0] _lowerCAmelCase = self.get_dummy_inputs(__snake_case ) _lowerCAmelCase = steps _lowerCAmelCase = scale _lowerCAmelCase = pipe(**__snake_case , control_guidance_start=[0.1, 0.3] , control_guidance_end=[0.2, 0.7] )[0] _lowerCAmelCase = self.get_dummy_inputs(__snake_case ) _lowerCAmelCase = steps _lowerCAmelCase = scale _lowerCAmelCase = pipe(**__snake_case , control_guidance_start=0.4 , control_guidance_end=[0.5, 0.8] )[0] # make sure that all outputs are different assert np.sum(np.abs(output_a - output_a ) ) > 1E-3 assert np.sum(np.abs(output_a - output_a ) ) > 1E-3 assert np.sum(np.abs(output_a - output_a ) ) > 1E-3 def lowercase__ ( self : int ) -> str: return self._test_attention_slicing_forward_pass(expected_max_diff=2E-3 ) @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def lowercase__ ( self : Optional[Any] ) -> Dict: self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2E-3 ) def lowercase__ ( self : int ) -> str: self._test_inference_batch_single_identical(expected_max_diff=2E-3 ) def lowercase__ ( self : Union[str, Any] ) -> Optional[Any]: _lowerCAmelCase = self.get_dummy_components() _lowerCAmelCase = self.pipeline_class(**__snake_case ) pipe.to(__snake_case ) pipe.set_progress_bar_config(disable=__snake_case ) with tempfile.TemporaryDirectory() as tmpdir: try: # save_pretrained is not implemented for Multi-ControlNet pipe.save_pretrained(__snake_case ) except NotImplementedError: pass @slow @require_torch_gpu class UpperCAmelCase ( unittest.TestCase ): def lowercase__ ( self : Union[str, Any] ) -> int: super().tearDown() gc.collect() torch.cuda.empty_cache() def lowercase__ ( self : List[str] ) -> Any: _lowerCAmelCase = ControlNetModel.from_pretrained("""lllyasviel/sd-controlnet-canny""" ) _lowerCAmelCase = StableDiffusionControlNetImgaImgPipeline.from_pretrained( """runwayml/stable-diffusion-v1-5""" , safety_checker=__snake_case , controlnet=__snake_case ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=__snake_case ) _lowerCAmelCase = torch.Generator(device="""cpu""" ).manual_seed(0 ) _lowerCAmelCase = """evil space-punk bird""" _lowerCAmelCase = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png""" ).resize((5_12, 5_12) ) _lowerCAmelCase = load_image( """https://huggingface.co/lllyasviel/sd-controlnet-canny/resolve/main/images/bird.png""" ).resize((5_12, 5_12) ) _lowerCAmelCase = pipe( __snake_case , __snake_case , control_image=__snake_case , generator=__snake_case , output_type="""np""" , num_inference_steps=50 , strength=0.6 , ) _lowerCAmelCase = output.images[0] assert image.shape == (5_12, 5_12, 3) _lowerCAmelCase = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/img2img.npy""" ) assert np.abs(expected_image - image ).max() < 9E-2
70
1
import argparse import fairseq import torch from transformers import UniSpeechSatConfig, UniSpeechSatForCTC, UniSpeechSatForPreTraining, logging logging.set_verbosity_info() UpperCamelCase__ : Optional[int] = logging.get_logger(__name__) UpperCamelCase__ : str = { """post_extract_proj""": """feature_projection.projection""", """encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""", """self_attn.k_proj""": """encoder.layers.*.attention.k_proj""", """self_attn.v_proj""": """encoder.layers.*.attention.v_proj""", """self_attn.q_proj""": """encoder.layers.*.attention.q_proj""", """self_attn.out_proj""": """encoder.layers.*.attention.out_proj""", """self_attn_layer_norm""": """encoder.layers.*.layer_norm""", """fc1""": """encoder.layers.*.feed_forward.intermediate_dense""", """fc2""": """encoder.layers.*.feed_forward.output_dense""", """final_layer_norm""": """encoder.layers.*.final_layer_norm""", """encoder.layer_norm""": """encoder.layer_norm""", """encoder.layer_norm_for_extract""": """layer_norm_for_extract""", """w2v_model.layer_norm""": """feature_projection.layer_norm""", """quantizer.weight_proj""": """quantizer.weight_proj""", """quantizer.vars""": """quantizer.codevectors""", """project_q""": """project_q""", """final_proj""": """project_hid""", """w2v_encoder.proj""": """lm_head""", """label_embs_concat""": """label_embeddings_concat""", """mask_emb""": """masked_spec_embed""", """spk_proj""": """speaker_proj""", } UpperCamelCase__ : Optional[Any] = [ """lm_head""", """quantizer.weight_proj""", """quantizer.codevectors""", """project_q""", """project_hid""", """label_embeddings_concat""", """speaker_proj""", """layer_norm_for_extract""", ] def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_, snake_case_, snake_case_ ) -> List[Any]: """simple docstring""" for attribute in key.split('''.''' ): a = getattr(snake_case_, snake_case_ ) if weight_type is not None: a = getattr(snake_case_, snake_case_ ).shape else: a = hf_pointer.shape if hf_shape != value.shape: raise ValueError( f"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be""" f""" {value.shape} for {full_name}""" ) if weight_type == "weight": a = value elif weight_type == "weight_g": a = value elif weight_type == "weight_v": a = value elif weight_type == "bias": a = value else: a = value logger.info(f"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_ ) -> Union[str, Any]: """simple docstring""" a = [] a = fairseq_model.state_dict() a = hf_model.unispeech_sat.feature_extractor for name, value in fairseq_dict.items(): a = False if "conv_layers" in name: load_conv_layer( snake_case_, snake_case_, snake_case_, snake_case_, hf_model.config.feat_extract_norm == '''group''', ) a = True else: for key, mapped_key in MAPPING.items(): a = '''unispeech_sat.''' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0]: if "layer_norm_for_extract" in name and (".".join(name.split('''.''' )[:-1] ) != key): # special case since naming is very similar continue a = True if "*" in mapped_key: a = name.split(snake_case_ )[0].split('''.''' )[-2] a = mapped_key.replace('''*''', snake_case_ ) if "weight_g" in name: a = '''weight_g''' elif "weight_v" in name: a = '''weight_v''' elif "bias" in name: a = '''bias''' elif "weight" in name: # TODO: don't match quantizer.weight_proj a = '''weight''' else: a = None set_recursively(snake_case_, snake_case_, snake_case_, snake_case_, snake_case_ ) continue if not is_used: unused_weights.append(snake_case_ ) logger.warning(f"""Unused weights: {unused_weights}""" ) def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_, snake_case_, snake_case_ ) -> Union[str, Any]: """simple docstring""" a = full_name.split('''conv_layers.''' )[-1] a = name.split('''.''' ) a = int(items[0] ) a = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) a = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) a = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor[layer_id].layer_norm.bias.data.shape} was found.""" ) a = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.""" ) a = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(snake_case_ ) @torch.no_grad() def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_=None, snake_case_=None, snake_case_=True ) -> Union[str, Any]: """simple docstring""" if config_path is not None: a = UniSpeechSatConfig.from_pretrained(snake_case_ ) else: a = UniSpeechSatConfig() a = '''''' if is_finetuned: a = UniSpeechSatForCTC(snake_case_ ) else: a = UniSpeechSatForPreTraining(snake_case_ ) a , a , a = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path], arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] )} ) a = model[0].eval() recursively_load_weights(snake_case_, snake_case_ ) hf_wavavec.save_pretrained(snake_case_ ) if __name__ == "__main__": UpperCamelCase__ : Optional[int] = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""") parser.add_argument("""--dict_path""", default=None, type=str, help="""Path to dict of fine-tuned model""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument( """--not_finetuned""", action="""store_true""", help="""Whether the model to convert is a fine-tuned model or not""" ) UpperCamelCase__ : int = parser.parse_args() convert_unispeech_sat_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
354
import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> List[str]: """simple docstring""" monkeypatch.setattr('''datasets.utils.deprecation_utils._emitted_deprecation_warnings''', set() ) @pytest.fixture def SCREAMING_SNAKE_CASE__ ( snake_case_ ) -> Optional[int]: """simple docstring""" class lowerCamelCase_ : def __init__( self : Dict ,__lowerCamelCase : List[str] ): '''simple docstring''' a = metric_id class lowerCamelCase_ : SCREAMING_SNAKE_CASE_ = [MetricMock(a_ ) for metric_id in ['accuracy', 'mse', 'precision', 'codeparrot/apps_metric']] def SCREAMING_SNAKE_CASE_ ( self : Dict ): '''simple docstring''' return self._metrics monkeypatch.setattr('''datasets.inspect.huggingface_hub''', HfhMock() ) @pytest.mark.parametrize( '''func, args''', [(load_metric, ('''metrics/mse''',)), (list_metrics, ()), (inspect_metric, ('''metrics/mse''', '''tmp_path'''))] ) def SCREAMING_SNAKE_CASE__ ( snake_case_, snake_case_, snake_case_, snake_case_, snake_case_ ) -> Tuple: """simple docstring""" if "tmp_path" in args: a = tuple(arg if arg != '''tmp_path''' else tmp_path for arg in args ) with pytest.warns(snake_case_, match='''https://huggingface.co/docs/evaluate''' ): func(*snake_case_ )
330
0
import shutil import tempfile import unittest from transformers import ( SPIECE_UNDERLINE, AddedToken, BatchEncoding, NllbTokenizer, NllbTokenizerFast, 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 _A = get_tests_dir('fixtures/test_sentencepiece.model') if is_torch_available(): from transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right _A = 25_6047 _A = 25_6145 @require_sentencepiece @require_tokenizers class UpperCAmelCase__ ( A_ , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Tuple = NllbTokenizer UpperCAmelCase__ : Any = NllbTokenizerFast UpperCAmelCase__ : str = True UpperCAmelCase__ : Optional[Any] = True UpperCAmelCase__ : Dict = {} def _a ( self ) -> Optional[Any]: super().setUp() # We have a SentencePiece fixture for testing __UpperCamelCase =NllbTokenizer(A_ , keep_accents=A_ ) tokenizer.save_pretrained(self.tmpdirname ) def _a ( self ) -> Optional[int]: __UpperCamelCase =NllbTokenizer(A_ , keep_accents=A_ ) __UpperCamelCase =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 [285, 46, 10, 170, 382]] , ) __UpperCamelCase =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', 'é', '.', ] , ) __UpperCamelCase =tokenizer.convert_tokens_to_ids(A_ ) self.assertListEqual( A_ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) __UpperCamelCase =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 _a ( self ) -> int: __UpperCamelCase =(self.rust_tokenizer_class, 'hf-internal-testing/tiny-random-nllb', {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __UpperCamelCase =self.rust_tokenizer_class.from_pretrained(A_ , **A_ ) __UpperCamelCase =self.tokenizer_class.from_pretrained(A_ , **A_ ) __UpperCamelCase =tempfile.mkdtemp() __UpperCamelCase =tokenizer_r.save_pretrained(A_ ) __UpperCamelCase =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 ) ) __UpperCamelCase =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 __UpperCamelCase =tokenizer_r.from_pretrained(A_ ) __UpperCamelCase =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=True __UpperCamelCase =tempfile.mkdtemp() __UpperCamelCase =tokenizer_r.save_pretrained(A_ , legacy_format=A_ ) __UpperCamelCase =tokenizer_p.save_pretrained(A_ ) # Checks it save with the same files self.assertSequenceEqual(A_ , A_ ) # Checks everything loads correctly in the same way __UpperCamelCase =tokenizer_r.from_pretrained(A_ ) __UpperCamelCase =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 __UpperCamelCase =tempfile.mkdtemp() __UpperCamelCase =tokenizer_r.save_pretrained(A_ , legacy_format=A_ ) __UpperCamelCase =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 __UpperCamelCase =tokenizer_r.from_pretrained(A_ ) __UpperCamelCase =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 def _a ( self ) -> List[Any]: if not self.test_seqaseq: return __UpperCamelCase =self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'{tokenizer.__class__.__name__}' ): # Longer text that will definitely require truncation. __UpperCamelCase =[ ' 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.', ] __UpperCamelCase =[ 'Ş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.', ] try: __UpperCamelCase =tokenizer.prepare_seqaseq_batch( src_texts=A_ , tgt_texts=A_ , max_length=3 , max_target_length=10 , return_tensors='pt' , src_lang='eng_Latn' , tgt_lang='ron_Latn' , ) except NotImplementedError: return self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.labels.shape[1] , 10 ) # max_target_length will default to max_length if not specified __UpperCamelCase =tokenizer.prepare_seqaseq_batch( A_ , tgt_texts=A_ , max_length=3 , return_tensors='pt' ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.labels.shape[1] , 3 ) __UpperCamelCase =tokenizer.prepare_seqaseq_batch( src_texts=A_ , max_length=3 , max_target_length=10 , return_tensors='pt' ) self.assertEqual(batch_encoder_only.input_ids.shape[1] , 3 ) self.assertEqual(batch_encoder_only.attention_mask.shape[1] , 3 ) self.assertNotIn('decoder_input_ids' , A_ ) @unittest.skip('Unfortunately way too slow to build a BPE with SentencePiece.' ) def _a ( self ) -> List[Any]: pass def _a ( self ) -> List[str]: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): __UpperCamelCase =[AddedToken('<special>' , lstrip=A_ )] __UpperCamelCase =self.rust_tokenizer_class.from_pretrained( A_ , additional_special_tokens=A_ , **A_ ) __UpperCamelCase =tokenizer_r.encode('Hey this is a <special> token' ) __UpperCamelCase =tokenizer_r.encode('<special>' , add_special_tokens=A_ )[0] self.assertTrue(special_token_id in r_output ) if self.test_slow_tokenizer: __UpperCamelCase =self.rust_tokenizer_class.from_pretrained( A_ , additional_special_tokens=A_ , **A_ , ) __UpperCamelCase =self.tokenizer_class.from_pretrained( A_ , additional_special_tokens=A_ , **A_ ) __UpperCamelCase =tokenizer_p.encode('Hey this is a <special> token' ) __UpperCamelCase =tokenizer_cr.encode('Hey this is a <special> token' ) self.assertEqual(A_ , A_ ) self.assertEqual(A_ , A_ ) self.assertTrue(special_token_id in p_output ) self.assertTrue(special_token_id in cr_output ) @require_torch @require_sentencepiece @require_tokenizers class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Optional[int] = "facebook/nllb-200-distilled-600M" UpperCAmelCase__ : int = [ " 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.", ] UpperCAmelCase__ : List[str] = [ "Ş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.", ] UpperCAmelCase__ : Optional[Any] = [ 2_5_6_0_4_7, 1_6_2_9_7, 1_3_4_4_0_8, 8_1_6_5, 2_4_8_0_6_6, 1_4_7_3_4, 9_5_0, 1_1_3_5, 1_0_5_7_2_1, 3_5_7_3, 8_3, 2_7_3_5_2, 1_0_8, 4_9_4_8_6, 2, ] @classmethod def _a ( cls ) -> List[Any]: __UpperCamelCase =NllbTokenizer.from_pretrained( cls.checkpoint_name , src_lang='eng_Latn' , tgt_lang='ron_Latn' ) __UpperCamelCase =1 return cls def _a ( self ) -> Tuple: self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['ace_Arab'] , 256001 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['ace_Latn'] , 256002 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['fra_Latn'] , 256057 ) def _a ( self ) -> Dict: __UpperCamelCase =self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , A_ ) def _a ( self ) -> List[str]: self.assertIn(A_ , self.tokenizer.all_special_ids ) # fmt: off __UpperCamelCase =[RO_CODE, 4254, 98068, 112923, 39072, 3909, 713, 102767, 26, 17314, 35642, 14683, 33118, 2022, 66987, 2, 256047] # fmt: on __UpperCamelCase =self.tokenizer.decode(A_ , skip_special_tokens=A_ ) __UpperCamelCase =self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=A_ ) self.assertEqual(A_ , A_ ) self.assertNotIn(self.tokenizer.eos_token , A_ ) def _a ( self ) -> Any: __UpperCamelCase =['this is gunna be a long sentence ' * 20] assert isinstance(src_text[0] , A_ ) __UpperCamelCase =10 __UpperCamelCase =self.tokenizer(A_ , max_length=A_ , truncation=A_ ).input_ids[0] self.assertEqual(ids[-1] , 2 ) self.assertEqual(ids[0] , A_ ) self.assertEqual(len(A_ ) , A_ ) def _a ( self ) -> List[str]: self.assertListEqual(self.tokenizer.convert_tokens_to_ids(['<mask>', 'ar_AR'] ) , [256203, 3] ) def _a ( self ) -> Optional[Any]: __UpperCamelCase =tempfile.mkdtemp() __UpperCamelCase =self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(A_ ) __UpperCamelCase =NllbTokenizer.from_pretrained(A_ ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , A_ ) @require_torch def _a ( self ) -> Dict: __UpperCamelCase =self.tokenizer( self.src_text , text_target=self.tgt_text , padding=A_ , truncation=A_ , max_length=len(self.expected_src_tokens ) , return_tensors='pt' , ) __UpperCamelCase =shift_tokens_right( batch['labels'] , self.tokenizer.pad_token_id , self.tokenizer.lang_code_to_id['ron_Latn'] ) self.assertIsInstance(A_ , A_ ) self.assertEqual((2, 15) , batch.input_ids.shape ) self.assertEqual((2, 15) , batch.attention_mask.shape ) __UpperCamelCase =batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , A_ ) self.assertEqual(A_ , batch.decoder_input_ids[0, 0] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [EN_CODE] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) def _a ( self ) -> Any: __UpperCamelCase =self.tokenizer(self.src_text , padding=A_ , truncation=A_ , max_length=3 , return_tensors='pt' ) __UpperCamelCase =self.tokenizer( text_target=self.tgt_text , padding=A_ , truncation=A_ , max_length=10 , return_tensors='pt' ) __UpperCamelCase =targets['input_ids'] __UpperCamelCase =shift_tokens_right( A_ , self.tokenizer.pad_token_id , decoder_start_token_id=self.tokenizer.lang_code_to_id[self.tokenizer.tgt_lang] , ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def _a ( self ) -> Optional[Any]: __UpperCamelCase =self.tokenizer._build_translation_inputs( 'A test' , return_tensors='pt' , src_lang='eng_Latn' , tgt_lang='fra_Latn' ) self.assertEqual( nested_simplify(A_ ) , { # A, test, EOS, en_XX 'input_ids': [[256047, 70, 7356, 2]], 'attention_mask': [[1, 1, 1, 1]], # ar_AR 'forced_bos_token_id': 256057, } , ) @require_torch def _a ( self ) -> Optional[int]: __UpperCamelCase =True __UpperCamelCase =self.tokenizer( 'UN Chief says there is no military solution in Syria' , src_lang='eng_Latn' , tgt_lang='fra_Latn' ) self.assertEqual( inputs.input_ids , [16297, 134408, 25653, 6370, 248, 254, 103929, 94995, 108, 49486, 2, 256047] ) __UpperCamelCase =False __UpperCamelCase =self.tokenizer( 'UN Chief says there is no military solution in Syria' , src_lang='eng_Latn' , tgt_lang='fra_Latn' ) self.assertEqual( inputs.input_ids , [256047, 16297, 134408, 25653, 6370, 248, 254, 103929, 94995, 108, 49486, 2] )
62
'''simple docstring''' from __future__ import annotations def a__ ( lowercase : str, lowercase : list[str] | None = None, lowercase : dict[str, float] | None = None, lowercase : bool = False, ) -> tuple[int, float, str]: """simple docstring""" _UpperCamelCase = cipher_alphabet or [chr(lowercase ) for i in range(97, 123 )] # If the argument is None or the user provided an empty dictionary if not frequencies_dict: # Frequencies of letters in the english language (how much they show up) _UpperCamelCase = { '''a''': 0.0_8_4_9_7, '''b''': 0.0_1_4_9_2, '''c''': 0.0_2_2_0_2, '''d''': 0.0_4_2_5_3, '''e''': 0.1_1_1_6_2, '''f''': 0.0_2_2_2_8, '''g''': 0.0_2_0_1_5, '''h''': 0.0_6_0_9_4, '''i''': 0.0_7_5_4_6, '''j''': 0.0_0_1_5_3, '''k''': 0.0_1_2_9_2, '''l''': 0.0_4_0_2_5, '''m''': 0.0_2_4_0_6, '''n''': 0.0_6_7_4_9, '''o''': 0.0_7_5_0_7, '''p''': 0.0_1_9_2_9, '''q''': 0.0_0_0_9_5, '''r''': 0.0_7_5_8_7, '''s''': 0.0_6_3_2_7, '''t''': 0.0_9_3_5_6, '''u''': 0.0_2_7_5_8, '''v''': 0.0_0_9_7_8, '''w''': 0.0_2_5_6_0, '''x''': 0.0_0_1_5_0, '''y''': 0.0_1_9_9_4, '''z''': 0.0_0_0_7_7, } else: # Custom frequencies dictionary _UpperCamelCase = frequencies_dict if not case_sensitive: _UpperCamelCase = ciphertext.lower() # Chi squared statistic values _UpperCamelCase = {} # cycle through all of the shifts for shift in range(len(lowercase ) ): _UpperCamelCase = '''''' # decrypt the message with the shift for letter in ciphertext: try: # Try to index the letter in the alphabet _UpperCamelCase = (alphabet_letters.index(letter.lower() ) - shift) % len( lowercase ) decrypted_with_shift += ( alphabet_letters[new_key].upper() if case_sensitive and letter.isupper() else alphabet_letters[new_key] ) except ValueError: # Append the character if it isn't in the alphabet decrypted_with_shift += letter _UpperCamelCase = 0.0 # Loop through each letter in the decoded message with the shift for letter in decrypted_with_shift: if case_sensitive: _UpperCamelCase = letter.lower() if letter in frequencies: # Get the amount of times the letter occurs in the message _UpperCamelCase = decrypted_with_shift.lower().count(lowercase ) # Get the excepcted amount of times the letter should appear based # on letter frequencies _UpperCamelCase = frequencies[letter] * occurrences # Complete the chi squared statistic formula _UpperCamelCase = ((occurrences - expected) ** 2) / expected # Add the margin of error to the total chi squared statistic chi_squared_statistic += chi_letter_value else: if letter.lower() in frequencies: # Get the amount of times the letter occurs in the message _UpperCamelCase = decrypted_with_shift.count(lowercase ) # Get the excepcted amount of times the letter should appear based # on letter frequencies _UpperCamelCase = frequencies[letter] * occurrences # Complete the chi squared statistic formula _UpperCamelCase = ((occurrences - expected) ** 2) / expected # Add the margin of error to the total chi squared statistic chi_squared_statistic += chi_letter_value # Add the data to the chi_squared_statistic_values dictionary _UpperCamelCase = ( chi_squared_statistic, decrypted_with_shift, ) # Get the most likely cipher by finding the cipher with the smallest chi squared # statistic def chi_squared_statistic_values_sorting_key(lowercase : int ) -> tuple[float, str]: return chi_squared_statistic_values[key] _UpperCamelCase = min( lowercase, key=lowercase, ) # Get all the data from the most likely cipher (key, decoded message) ( ( _UpperCamelCase ) , ( _UpperCamelCase ) , ) = chi_squared_statistic_values[most_likely_cipher] # Return the data on the most likely shift return ( most_likely_cipher, most_likely_cipher_chi_squared_value, decoded_most_likely_cipher, )
324
0
"""simple docstring""" import logging from pathlib import Path import numpy as np import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.utilities import rank_zero_only from utils_rag import save_json def _UpperCAmelCase ( __lowerCamelCase : Optional[int] ) -> Dict: _snake_case = filter(lambda __lowerCamelCase : p.requires_grad , model.parameters() ) _snake_case = sum([np.prod(p.size() ) for p in model_parameters] ) return params UpperCAmelCase__ = logging.getLogger(__name__) def _UpperCAmelCase ( __lowerCamelCase : List[str] , __lowerCamelCase : Optional[int] ) -> Union[str, Any]: if metric == "rouge2": _snake_case = '''{val_avg_rouge2:.4f}-{step_count}''' elif metric == "bleu": _snake_case = '''{val_avg_bleu:.4f}-{step_count}''' elif metric == "em": _snake_case = '''{val_avg_em:.4f}-{step_count}''' elif metric == "loss": _snake_case = '''{val_avg_loss:.4f}-{step_count}''' else: raise NotImplementedError( f'''seq2seq callbacks only support rouge2 and bleu, got {metric}, You can make your own by adding to this''' ''' function.''' ) _snake_case = ModelCheckpoint( dirpath=__lowerCamelCase , filename=__lowerCamelCase , monitor=f'''val_{metric}''' , mode='''max''' , save_top_k=1 , every_n_epochs=1 , ) return checkpoint_callback def _UpperCAmelCase ( __lowerCamelCase : List[Any] , __lowerCamelCase : Optional[int] ) -> Any: return EarlyStopping( monitor=f'''val_{metric}''' , mode='''min''' if '''loss''' in metric else '''max''' , patience=__lowerCamelCase , verbose=__lowerCamelCase , ) class lowerCAmelCase__ ( pl.Callback ): def lowercase ( self : List[Any] , _lowerCamelCase : List[Any] , _lowerCamelCase : List[str] ): _snake_case = {f'''lr_group_{i}''': param['''lr'''] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups )} pl_module.logger.log_metrics(_lowerCamelCase ) @rank_zero_only def lowercase ( self : Any , _lowerCamelCase : pl.Trainer , _lowerCamelCase : pl.LightningModule , _lowerCamelCase : str , _lowerCamelCase : Any=True ): logger.info(f'''***** {type_path} results at step {trainer.global_step:05d} *****''' ) _snake_case = trainer.callback_metrics trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ['''log''', '''progress_bar''', '''preds''']} ) # Log results _snake_case = Path(pl_module.hparams.output_dir ) if type_path == "test": _snake_case = od / '''test_results.txt''' _snake_case = od / '''test_generations.txt''' else: # this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json # If people want this it will be easy enough to add back. _snake_case = od / f'''{type_path}_results/{trainer.global_step:05d}.txt''' _snake_case = od / f'''{type_path}_generations/{trainer.global_step:05d}.txt''' results_file.parent.mkdir(exist_ok=_lowerCamelCase ) generations_file.parent.mkdir(exist_ok=_lowerCamelCase ) with open(_lowerCamelCase , '''a+''' ) as writer: for key in sorted(_lowerCamelCase ): if key in ["log", "progress_bar", "preds"]: continue _snake_case = metrics[key] if isinstance(_lowerCamelCase , torch.Tensor ): _snake_case = val.item() _snake_case = f'''{key}: {val:.6f}\n''' writer.write(_lowerCamelCase ) if not save_generations: return if "preds" in metrics: _snake_case = '''\n'''.join(metrics['''preds'''] ) generations_file.open('''w+''' ).write(_lowerCamelCase ) @rank_zero_only def lowercase ( self : Optional[int] , _lowerCamelCase : Any , _lowerCamelCase : Union[str, Any] ): try: _snake_case = pl_module.model.model.num_parameters() except AttributeError: _snake_case = pl_module.model.num_parameters() _snake_case = count_trainable_parameters(_lowerCamelCase ) # mp stands for million parameters trainer.logger.log_metrics({'''n_params''': npars, '''mp''': npars / 1e6, '''grad_mp''': n_trainable_pars / 1e6} ) @rank_zero_only def lowercase ( self : Dict , _lowerCamelCase : pl.Trainer , _lowerCamelCase : pl.LightningModule ): save_json(pl_module.metrics , pl_module.metrics_save_path ) return self._write_logs(_lowerCamelCase , _lowerCamelCase , '''test''' ) @rank_zero_only def lowercase ( self : Any , _lowerCamelCase : pl.Trainer , _lowerCamelCase : Any ): save_json(pl_module.metrics , pl_module.metrics_save_path ) # Uncommenting this will save val generations # return self._write_logs(trainer, pl_module, "valid")
40
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, is_vision_available, ) UpperCAmelCase__ = {'processing_layoutxlm': ['LayoutXLMProcessor']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = ['LayoutXLMTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = ['LayoutXLMTokenizerFast'] if TYPE_CHECKING: from .processing_layoutxlm import LayoutXLMProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutxlm import LayoutXLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutxlm_fast import LayoutXLMTokenizerFast else: import sys UpperCAmelCase__ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
40
1
def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : dict ) -> bool: __lowercase = set() # To detect a back edge, keep track of vertices currently in the recursion stack __lowercase = set() return any( node not in visited and depth_first_search(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for node in graph ) def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : dict , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : set , SCREAMING_SNAKE_CASE : set ) -> bool: visited.add(SCREAMING_SNAKE_CASE ) rec_stk.add(SCREAMING_SNAKE_CASE ) for node in graph[vertex]: if node not in visited: if depth_first_search(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): return True elif node in rec_stk: return True # The node needs to be removed from recursion stack before function ends rec_stk.remove(SCREAMING_SNAKE_CASE ) return False if __name__ == "__main__": from doctest import testmod testmod()
325
from math import isqrt, loga def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : int ) -> list[int]: __lowercase = [True] * max_number for i in range(2 , isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2 , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): __lowercase = False return [i for i in range(2 , SCREAMING_SNAKE_CASE ) if is_prime[i]] def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : int = 800800 , SCREAMING_SNAKE_CASE : int = 800800 ) -> int: __lowercase = degree * loga(SCREAMING_SNAKE_CASE ) __lowercase = int(SCREAMING_SNAKE_CASE ) __lowercase = calculate_prime_numbers(SCREAMING_SNAKE_CASE ) __lowercase = 0 __lowercase = 0 __lowercase = len(SCREAMING_SNAKE_CASE ) - 1 while left < right: while ( prime_numbers[right] * loga(prime_numbers[left] ) + prime_numbers[left] * loga(prime_numbers[right] ) > upper_bound ): right -= 1 hybrid_integers_count += right - left left += 1 return hybrid_integers_count if __name__ == "__main__": print(F'''{solution() = }''')
325
1
"""simple docstring""" import copy from ...configuration_utils import PretrainedConfig from ...utils import add_start_docstrings __snake_case = R""" [`RagConfig`] stores the configuration of a *RagModel*. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information. Args: title_sep (`str`, *optional*, defaults to `\" / \"`): Separator inserted between the title and the text of the retrieved document when calling [`RagRetriever`]. doc_sep (`str`, *optional*, defaults to `\" // \"`): Separator inserted between the text of the retrieved document and the original input when calling [`RagRetriever`]. n_docs (`int`, *optional*, defaults to 5): Number of documents to retrieve. max_combined_length (`int`, *optional*, defaults to 300): Max length of contextualized input returned by [`~RagRetriever.__call__`]. retrieval_vector_size (`int`, *optional*, defaults to 768): Dimensionality of the document embeddings indexed by [`RagRetriever`]. retrieval_batch_size (`int`, *optional*, defaults to 8): Retrieval batch size, defined as the number of queries issues concurrently to the faiss index encapsulated [`RagRetriever`]. dataset (`str`, *optional*, defaults to `\"wiki_dpr\"`): A dataset identifier of the indexed dataset in HuggingFace Datasets (list all available datasets and ids using `datasets.list_datasets()`). dataset_split (`str`, *optional*, defaults to `\"train\"`) Which split of the `dataset` to load. index_name (`str`, *optional*, defaults to `\"compressed\"`) The index name of the index associated with the `dataset`. One can choose between `\"legacy\"`, `\"exact\"` and `\"compressed\"`. index_path (`str`, *optional*) The path to the serialized faiss index on disk. passages_path (`str`, *optional*): A path to text passages compatible with the faiss index. Required if using [`~models.rag.retrieval_rag.LegacyIndex`] use_dummy_dataset (`bool`, *optional*, defaults to `False`) Whether to load a \"dummy\" variant of the dataset specified by `dataset`. label_smoothing (`float`, *optional*, defaults to 0.0): Only relevant if `return_loss` is set to `True`. Controls the `epsilon` parameter value for label smoothing in the loss calculation. If set to 0, no label smoothing is performed. do_marginalize (`bool`, *optional*, defaults to `False`): If `True`, the logits are marginalized over all documents by making use of `torch.nn.functional.log_softmax`. reduce_loss (`bool`, *optional*, defaults to `False`): Whether or not to reduce the NLL loss using the `torch.Tensor.sum` operation. do_deduplication (`bool`, *optional*, defaults to `True`): Whether or not to deduplicate the generations from different context documents for a given input. Has to be set to `False` if used while training with distributed backend. exclude_bos_score (`bool`, *optional*, defaults to `False`): Whether or not to disregard the BOS token when computing the loss. output_retrieved(`bool`, *optional*, defaults to `False`): If set to `True`, `retrieved_doc_embeds`, `retrieved_doc_ids`, `context_input_ids` and `context_attention_mask` are returned. See returned tensors for more detail. use_cache (`bool`, *optional*, defaults to `True`): Whether or not the model should return the last key/values attentions (not used by all models). forced_eos_token_id (`int`, *optional*): The id of the token to force as the last generated token when `max_length` is reached. Usually set to `eos_token_id`. """ @add_start_docstrings(snake_case_ ) class _lowerCAmelCase ( snake_case_ ): __UpperCAmelCase : Any = '''rag''' __UpperCAmelCase : Optional[Any] = True def __init__( self , UpperCamelCase__=None , UpperCamelCase__=True , UpperCamelCase__=None , UpperCamelCase__=None , UpperCamelCase__=None , UpperCamelCase__=None , UpperCamelCase__=None , UpperCamelCase__=" / " , UpperCamelCase__=" // " , UpperCamelCase__=5 , UpperCamelCase__=300 , UpperCamelCase__=768 , UpperCamelCase__=8 , UpperCamelCase__="wiki_dpr" , UpperCamelCase__="train" , UpperCamelCase__="compressed" , UpperCamelCase__=None , UpperCamelCase__=None , UpperCamelCase__=False , UpperCamelCase__=False , UpperCamelCase__=0.0 , UpperCamelCase__=True , UpperCamelCase__=False , UpperCamelCase__=False , UpperCamelCase__=False , UpperCamelCase__=True , UpperCamelCase__=None , **UpperCamelCase__ , ) -> int: '''simple docstring''' super().__init__( bos_token_id=UpperCamelCase__ , pad_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ , decoder_start_token_id=UpperCamelCase__ , forced_eos_token_id=UpperCamelCase__ , is_encoder_decoder=UpperCamelCase__ , prefix=UpperCamelCase__ , vocab_size=UpperCamelCase__ , **UpperCamelCase__ , ) assert ( "question_encoder" in kwargs and "generator" in kwargs ), "Config has to be initialized with question_encoder and generator config" snake_case : Tuple = kwargs.pop("question_encoder" ) snake_case : int = question_encoder_config.pop("model_type" ) snake_case : Tuple = kwargs.pop("generator" ) snake_case : Optional[Any] = decoder_config.pop("model_type" ) from ..auto.configuration_auto import AutoConfig snake_case : Optional[Any] = AutoConfig.for_model(UpperCamelCase__ , **UpperCamelCase__ ) snake_case : str = AutoConfig.for_model(UpperCamelCase__ , **UpperCamelCase__ ) snake_case : Tuple = reduce_loss snake_case : str = label_smoothing snake_case : Union[str, Any] = exclude_bos_score snake_case : List[str] = do_marginalize snake_case : Dict = title_sep snake_case : Union[str, Any] = doc_sep snake_case : int = n_docs snake_case : Tuple = max_combined_length snake_case : Any = dataset snake_case : List[str] = dataset_split snake_case : str = index_name snake_case : Union[str, Any] = retrieval_vector_size snake_case : Union[str, Any] = retrieval_batch_size snake_case : Tuple = passages_path snake_case : List[str] = index_path snake_case : str = use_dummy_dataset snake_case : str = output_retrieved snake_case : int = do_deduplication snake_case : Union[str, Any] = use_cache if self.forced_eos_token_id is None: snake_case : Union[str, Any] = getattr(self.generator , "forced_eos_token_id" , UpperCamelCase__ ) @classmethod def lowerCamelCase ( cls , UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__ ) -> PretrainedConfig: '''simple docstring''' return cls(question_encoder=question_encoder_config.to_dict() , generator=generator_config.to_dict() , **UpperCamelCase__ ) def lowerCamelCase ( self ) -> Tuple: '''simple docstring''' snake_case : List[Any] = copy.deepcopy(self.__dict__ ) snake_case : Optional[Any] = self.question_encoder.to_dict() snake_case : Optional[int] = self.generator.to_dict() snake_case : Union[str, Any] = self.__class__.model_type return output
112
"""simple docstring""" import math import sys def __lowerCAmelCase ( lowercase : int ) -> int: """simple docstring""" if number != int(lowercase ): raise ValueError("the value of input must be a natural number" ) if number < 0: raise ValueError("the value of input must not be a negative number" ) if number == 0: return 1 snake_case : Optional[Any] = [-1] * (number + 1) snake_case : str = 0 for i in range(1 , number + 1 ): snake_case : List[Any] = sys.maxsize snake_case : Union[str, Any] = int(math.sqrt(lowercase ) ) for j in range(1 , root + 1 ): snake_case : List[str] = 1 + answers[i - (j**2)] snake_case : Optional[Any] = min(lowercase , lowercase ) snake_case : Any = answer return answers[number] if __name__ == "__main__": import doctest doctest.testmod()
112
1
"""simple docstring""" import functools import logging import os import sys import threading from logging import ( CRITICAL, # NOQA DEBUG, # NOQA ERROR, # NOQA FATAL, # NOQA INFO, # NOQA NOTSET, # NOQA WARN, # NOQA WARNING, # NOQA ) from typing import Optional import huggingface_hub.utils as hf_hub_utils from tqdm import auto as tqdm_lib lowerCAmelCase : List[str] = threading.Lock() lowerCAmelCase : Optional[logging.Handler] = None lowerCAmelCase : Union[str, Any] = { """debug""": logging.DEBUG, """info""": logging.INFO, """warning""": logging.WARNING, """error""": logging.ERROR, """critical""": logging.CRITICAL, } lowerCAmelCase : Any = logging.WARNING lowerCAmelCase : int = True def a__ ( ) -> Dict: lowerCamelCase = os.getenv("""TRANSFORMERS_VERBOSITY""" , snake_case__ ) if env_level_str: if env_level_str in log_levels: return log_levels[env_level_str] else: logging.getLogger().warning( F'Unknown option TRANSFORMERS_VERBOSITY={env_level_str}, ' F'has to be one of: { ", ".join(log_levels.keys() ) }' ) return _default_log_level def a__ ( ) -> str: return __name__.split(""".""" )[0] def a__ ( ) -> logging.Logger: return logging.getLogger(_get_library_name() ) def a__ ( ) -> None: global _default_handler with _lock: if _default_handler: # This library has already configured the library root logger. return lowerCamelCase = logging.StreamHandler() # Set sys.stderr as stream. lowerCamelCase = sys.stderr.flush # Apply our default configuration to the library root logger. lowerCamelCase = _get_library_root_logger() library_root_logger.addHandler(_default_handler ) library_root_logger.setLevel(_get_default_logging_level() ) lowerCamelCase = False def a__ ( ) -> None: global _default_handler with _lock: if not _default_handler: return lowerCamelCase = _get_library_root_logger() library_root_logger.removeHandler(_default_handler ) library_root_logger.setLevel(logging.NOTSET ) lowerCamelCase = None def a__ ( ) -> Any: return log_levels def a__ ( snake_case__ = None ) -> logging.Logger: if name is None: lowerCamelCase = _get_library_name() _configure_library_root_logger() return logging.getLogger(snake_case__ ) def a__ ( ) -> int: _configure_library_root_logger() return _get_library_root_logger().getEffectiveLevel() def a__ ( snake_case__ ) -> None: _configure_library_root_logger() _get_library_root_logger().setLevel(snake_case__ ) def a__ ( ) -> List[Any]: return set_verbosity(snake_case__ ) def a__ ( ) -> Optional[int]: return set_verbosity(snake_case__ ) def a__ ( ) -> Optional[Any]: return set_verbosity(snake_case__ ) def a__ ( ) -> Optional[Any]: return set_verbosity(snake_case__ ) def a__ ( ) -> None: _configure_library_root_logger() assert _default_handler is not None _get_library_root_logger().removeHandler(_default_handler ) def a__ ( ) -> None: _configure_library_root_logger() assert _default_handler is not None _get_library_root_logger().addHandler(_default_handler ) def a__ ( snake_case__ ) -> None: _configure_library_root_logger() assert handler is not None _get_library_root_logger().addHandler(snake_case__ ) def a__ ( snake_case__ ) -> None: _configure_library_root_logger() assert handler is not None and handler not in _get_library_root_logger().handlers _get_library_root_logger().removeHandler(snake_case__ ) def a__ ( ) -> None: _configure_library_root_logger() lowerCamelCase = False def a__ ( ) -> None: _configure_library_root_logger() lowerCamelCase = True def a__ ( ) -> None: lowerCamelCase = _get_library_root_logger().handlers for handler in handlers: lowerCamelCase = logging.Formatter("""[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s""" ) handler.setFormatter(snake_case__ ) def a__ ( ) -> None: lowerCamelCase = _get_library_root_logger().handlers for handler in handlers: handler.setFormatter(snake_case__ ) def a__ ( self , *snake_case__ , **snake_case__ ) -> Tuple: lowerCamelCase = os.getenv("""TRANSFORMERS_NO_ADVISORY_WARNINGS""" , snake_case__ ) if no_advisory_warnings: return self.warning(*snake_case__ , **snake_case__ ) lowerCAmelCase : List[str] = warning_advice @functools.lru_cache(snake_case__ ) def a__ ( self , *snake_case__ , **snake_case__ ) -> Optional[int]: self.warning(*snake_case__ , **snake_case__ ) lowerCAmelCase : Optional[int] = warning_once class __magic_name__ : '''simple docstring''' def __init__( self , *_a , **_a ): # pylint: disable=unused-argument """simple docstring""" lowerCamelCase = args[0] if args else None def __iter__( self ): """simple docstring""" return iter(self._iterator ) def __getattr__( self , _a ): """simple docstring""" def empty_fn(*_a , **_a ): # pylint: disable=unused-argument return return empty_fn def __enter__( self ): """simple docstring""" return self def __exit__( self , _a , _a , _a ): """simple docstring""" return class __magic_name__ : '''simple docstring''' def __call__( self , *_a , **_a ): """simple docstring""" if _tqdm_active: return tqdm_lib.tqdm(*_a , **_a ) else: return EmptyTqdm(*_a , **_a ) def _lowerCAmelCase ( self , *_a , **_a ): """simple docstring""" lowerCamelCase = None if _tqdm_active: return tqdm_lib.tqdm.set_lock(*_a , **_a ) def _lowerCAmelCase ( self ): """simple docstring""" if _tqdm_active: return tqdm_lib.tqdm.get_lock() lowerCAmelCase : Optional[int] = _tqdm_cls() def a__ ( ) -> bool: global _tqdm_active return bool(_tqdm_active ) def a__ ( ) -> List[Any]: global _tqdm_active lowerCamelCase = True hf_hub_utils.enable_progress_bars() def a__ ( ) -> int: global _tqdm_active lowerCamelCase = False hf_hub_utils.disable_progress_bars()
291
"""simple docstring""" def a__ ( snake_case__ , snake_case__ = False ) -> str: if not isinstance(snake_case__ , snake_case__ ): lowerCamelCase = F'Expected string as input, found {type(snake_case__ )}' raise ValueError(snake_case__ ) if not isinstance(snake_case__ , snake_case__ ): lowerCamelCase = F'Expected boolean as use_pascal parameter, found {type(snake_case__ )}' raise ValueError(snake_case__ ) lowerCamelCase = input_str.split("""_""" ) lowerCamelCase = 0 if use_pascal else 1 lowerCamelCase = words[start_index:] lowerCamelCase = [word[0].upper() + word[1:] for word in words_to_capitalize] lowerCamelCase = """""" if use_pascal else words[0] return "".join([initial_word, *capitalized_words] ) if __name__ == "__main__": from doctest import testmod testmod()
291
1
"""simple docstring""" import random import unittest import numpy as np import torch from diffusers import ( DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionUpscalePipeline, PNDMScheduler, ) from diffusers.utils import floats_tensor from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class snake_case ( __snake_case, unittest.TestCase ): # TODO: is there an appropriate internal test set? SCREAMING_SNAKE_CASE_ : Optional[Any] = """ssube/stable-diffusion-x4-upscaler-onnx""" def lowercase_ ( self : int , UpperCamelCase__ : Union[str, Any]=0)-> Tuple: '''simple docstring''' __lowerCAmelCase: int = floats_tensor((1, 3, 1_2_8, 1_2_8) , rng=random.Random(UpperCamelCase__)) __lowerCAmelCase: str = torch.manual_seed(UpperCamelCase__) __lowerCAmelCase: Optional[Any] = { "prompt": "A painting of a squirrel eating a burger", "image": image, "generator": generator, "num_inference_steps": 3, "guidance_scale": 7.5, "output_type": "numpy", } return inputs def lowercase_ ( self : List[str])-> Optional[int]: '''simple docstring''' __lowerCAmelCase: List[str] = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider") pipe.set_progress_bar_config(disable=UpperCamelCase__) __lowerCAmelCase: Tuple = self.get_dummy_inputs() __lowerCAmelCase: Optional[int] = pipe(**UpperCamelCase__).images __lowerCAmelCase: int = image[0, -3:, -3:, -1].flatten() # started as 128, should now be 512 assert image.shape == (1, 5_1_2, 5_1_2, 3) __lowerCAmelCase: Dict = np.array( [0.6974782, 0.68902093, 0.70135885, 0.7583618, 0.7804545, 0.7854912, 0.78667426, 0.78743863, 0.78070223]) assert np.abs(image_slice - expected_slice).max() < 1e-1 def lowercase_ ( self : str)-> Dict: '''simple docstring''' __lowerCAmelCase: str = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider") __lowerCAmelCase: Union[str, Any] = PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=UpperCamelCase__) pipe.set_progress_bar_config(disable=UpperCamelCase__) __lowerCAmelCase: str = self.get_dummy_inputs() __lowerCAmelCase: Tuple = pipe(**UpperCamelCase__).images __lowerCAmelCase: Dict = image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) __lowerCAmelCase: Union[str, Any] = np.array( [0.6898892, 0.59240556, 0.52499527, 0.58866215, 0.52258235, 0.52572715, 0.62414473, 0.6174387, 0.6214964]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-1 def lowercase_ ( self : List[str])-> Optional[int]: '''simple docstring''' __lowerCAmelCase: Any = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider") __lowerCAmelCase: List[str] = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config) pipe.set_progress_bar_config(disable=UpperCamelCase__) __lowerCAmelCase: int = self.get_dummy_inputs() __lowerCAmelCase: Any = pipe(**UpperCamelCase__).images __lowerCAmelCase: Tuple = image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) __lowerCAmelCase: List[str] = np.array( [0.7659278, 0.76437664, 0.75579107, 0.7691116, 0.77666986, 0.7727672, 0.7758664, 0.7812226, 0.76942515]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-1 def lowercase_ ( self : List[str])-> Optional[int]: '''simple docstring''' __lowerCAmelCase: Dict = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider") __lowerCAmelCase: int = EulerDiscreteScheduler.from_config(pipe.scheduler.config) pipe.set_progress_bar_config(disable=UpperCamelCase__) __lowerCAmelCase: Any = self.get_dummy_inputs() __lowerCAmelCase: Dict = pipe(**UpperCamelCase__).images __lowerCAmelCase: str = image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) __lowerCAmelCase: Optional[int] = np.array( [0.6974782, 0.68902093, 0.70135885, 0.7583618, 0.7804545, 0.7854912, 0.78667426, 0.78743863, 0.78070223]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-1 def lowercase_ ( self : Dict)-> Union[str, Any]: '''simple docstring''' __lowerCAmelCase: List[str] = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider") __lowerCAmelCase: List[Any] = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config) pipe.set_progress_bar_config(disable=UpperCamelCase__) __lowerCAmelCase: List[Any] = self.get_dummy_inputs() __lowerCAmelCase: Optional[Any] = pipe(**UpperCamelCase__).images __lowerCAmelCase: int = image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) __lowerCAmelCase: Union[str, Any] = np.array( [0.77424496, 0.773601, 0.7645288, 0.7769598, 0.7772739, 0.7738688, 0.78187233, 0.77879584, 0.767043]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-1 @nightly @require_onnxruntime @require_torch_gpu class snake_case ( unittest.TestCase ): @property def lowercase_ ( self : Tuple)-> Optional[Any]: '''simple docstring''' return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def lowercase_ ( self : int)-> List[Any]: '''simple docstring''' __lowerCAmelCase: Dict = ort.SessionOptions() __lowerCAmelCase: str = False return options def lowercase_ ( self : str)-> str: '''simple docstring''' __lowerCAmelCase: Tuple = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/img2img/sketch-mountains-input.jpg") __lowerCAmelCase: List[Any] = init_image.resize((1_2_8, 1_2_8)) # using the PNDM scheduler by default __lowerCAmelCase: Dict = OnnxStableDiffusionUpscalePipeline.from_pretrained( "ssube/stable-diffusion-x4-upscaler-onnx" , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=UpperCamelCase__) __lowerCAmelCase: str = "A fantasy landscape, trending on artstation" __lowerCAmelCase: Union[str, Any] = torch.manual_seed(0) __lowerCAmelCase: List[Any] = pipe( prompt=UpperCamelCase__ , image=UpperCamelCase__ , guidance_scale=7.5 , num_inference_steps=1_0 , generator=UpperCamelCase__ , output_type="np" , ) __lowerCAmelCase: str = output.images __lowerCAmelCase: Optional[Any] = images[0, 2_5_5:2_5_8, 3_8_3:3_8_6, -1] assert images.shape == (1, 5_1_2, 5_1_2, 3) __lowerCAmelCase: Dict = np.array([0.4883, 0.4947, 0.4980, 0.4975, 0.4982, 0.4980, 0.5000, 0.5006, 0.4972]) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice).max() < 2e-2 def lowercase_ ( self : Dict)-> Any: '''simple docstring''' __lowerCAmelCase: Optional[int] = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/img2img/sketch-mountains-input.jpg") __lowerCAmelCase: str = init_image.resize((1_2_8, 1_2_8)) __lowerCAmelCase: Union[str, Any] = LMSDiscreteScheduler.from_pretrained( "ssube/stable-diffusion-x4-upscaler-onnx" , subfolder="scheduler") __lowerCAmelCase: Dict = OnnxStableDiffusionUpscalePipeline.from_pretrained( "ssube/stable-diffusion-x4-upscaler-onnx" , scheduler=UpperCamelCase__ , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=UpperCamelCase__) __lowerCAmelCase: Union[str, Any] = "A fantasy landscape, trending on artstation" __lowerCAmelCase: Dict = torch.manual_seed(0) __lowerCAmelCase: Dict = pipe( prompt=UpperCamelCase__ , image=UpperCamelCase__ , guidance_scale=7.5 , num_inference_steps=2_0 , generator=UpperCamelCase__ , output_type="np" , ) __lowerCAmelCase: Optional[int] = output.images __lowerCAmelCase: List[str] = images[0, 2_5_5:2_5_8, 3_8_3:3_8_6, -1] assert images.shape == (1, 5_1_2, 5_1_2, 3) __lowerCAmelCase: Optional[int] = np.array( [0.50173753, 0.50223356, 0.502039, 0.50233036, 0.5023725, 0.5022601, 0.5018758, 0.50234085, 0.50241566]) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice).max() < 2e-2
108
"""simple docstring""" from math import ceil def a__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> str: __lowerCAmelCase: Tuple = list(range(0 , __SCREAMING_SNAKE_CASE ) ) __lowerCAmelCase: Optional[Any] = [item for sublist in list(device_map.values() ) for item in sublist] # Duplicate check __lowerCAmelCase: List[Any] = [] for i in device_map_blocks: if device_map_blocks.count(__SCREAMING_SNAKE_CASE ) > 1 and i not in duplicate_blocks: duplicate_blocks.append(__SCREAMING_SNAKE_CASE ) # Missing blocks __lowerCAmelCase: Optional[Any] = [i for i in blocks if i not in device_map_blocks] __lowerCAmelCase: List[Any] = [i for i in device_map_blocks if i not in blocks] if len(__SCREAMING_SNAKE_CASE ) != 0: raise ValueError( "Duplicate attention blocks specified in device_map. Attention blocks must be specified to one device." " These attention blocks were specified more than once: " + str(__SCREAMING_SNAKE_CASE ) ) if len(__SCREAMING_SNAKE_CASE ) != 0: raise ValueError( "There are attention blocks for this model that are not specified in the device_map. Add these attention " "blocks to a device on the device_map: " + str(__SCREAMING_SNAKE_CASE ) ) if len(__SCREAMING_SNAKE_CASE ) != 0: raise ValueError( "The device_map contains more attention blocks than this model has. Remove these from the device_map:" + str(__SCREAMING_SNAKE_CASE ) ) def a__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> str: __lowerCAmelCase: List[Any] = list(range(__SCREAMING_SNAKE_CASE ) ) __lowerCAmelCase: Dict = int(ceil(n_layers / len(__SCREAMING_SNAKE_CASE ) ) ) __lowerCAmelCase: Union[str, Any] = [layers[i : i + n_blocks] for i in range(0 , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )] return dict(zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) )
108
1
"""simple docstring""" import warnings from typing import Dict, List, Optional, Tuple from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging lowerCamelCase_ = logging.get_logger(__name__) class _SCREAMING_SNAKE_CASE( lowerCAmelCase__ ): SCREAMING_SNAKE_CASE_ : List[Any] = ['''input_ids''', '''attention_mask'''] def __init__( self ,SCREAMING_SNAKE_CASE__="</s>" ,SCREAMING_SNAKE_CASE__="<unk>" ,SCREAMING_SNAKE_CASE__="<pad>" ,SCREAMING_SNAKE_CASE__=1_25 ,SCREAMING_SNAKE_CASE__=None ,**SCREAMING_SNAKE_CASE__ ,) -> Optional[int]: """simple docstring""" if extra_ids > 0 and additional_special_tokens is None: __SCREAMING_SNAKE_CASE :List[str] = [f'''<extra_id_{i}>''' for i in range(__UpperCAmelCase )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens __SCREAMING_SNAKE_CASE :Tuple = len(set(filter(lambda SCREAMING_SNAKE_CASE__ : bool('''extra_id''' in str(__UpperCAmelCase ) ) ,__UpperCAmelCase ) ) ) if extra_tokens != extra_ids: raise ValueError( f'''Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are''' ''' provided to ByT5Tokenizer. In this case the additional_special_tokens must include the''' ''' extra_ids tokens''' ) __SCREAMING_SNAKE_CASE :Optional[int] = AddedToken(__UpperCAmelCase ,lstrip=__UpperCAmelCase ,rstrip=__UpperCAmelCase ) if isinstance(__UpperCAmelCase ,__UpperCAmelCase ) else pad_token __SCREAMING_SNAKE_CASE :List[str] = AddedToken(__UpperCAmelCase ,lstrip=__UpperCAmelCase ,rstrip=__UpperCAmelCase ) if isinstance(__UpperCAmelCase ,__UpperCAmelCase ) else eos_token __SCREAMING_SNAKE_CASE :str = AddedToken(__UpperCAmelCase ,lstrip=__UpperCAmelCase ,rstrip=__UpperCAmelCase ) if isinstance(__UpperCAmelCase ,__UpperCAmelCase ) else unk_token super().__init__( eos_token=__UpperCAmelCase ,unk_token=__UpperCAmelCase ,pad_token=__UpperCAmelCase ,extra_ids=__UpperCAmelCase ,additional_special_tokens=__UpperCAmelCase ,**__UpperCAmelCase ,) __SCREAMING_SNAKE_CASE :str = extra_ids __SCREAMING_SNAKE_CASE :Union[str, Any] = 2**8 # utf is 8 bits # define special tokens dict __SCREAMING_SNAKE_CASE :str = { self.pad_token: 0, self.eos_token: 1, self.unk_token: 2, } __SCREAMING_SNAKE_CASE :Tuple = len(self.special_tokens_encoder ) __SCREAMING_SNAKE_CASE :int = len(__UpperCAmelCase ) for i, token in enumerate(__UpperCAmelCase ): __SCREAMING_SNAKE_CASE :Optional[int] = self.vocab_size + i - n __SCREAMING_SNAKE_CASE :Union[str, Any] = {v: k for k, v in self.special_tokens_encoder.items()} @property def _UpperCamelCase ( self ) -> List[str]: """simple docstring""" return self._utf_vocab_size + self._num_special_tokens + self._extra_ids def _UpperCamelCase ( self ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ = None ,SCREAMING_SNAKE_CASE__ = False ) -> int: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__UpperCAmelCase ,token_ids_a=__UpperCAmelCase ,already_has_special_tokens=__UpperCAmelCase ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(__UpperCAmelCase )) + [1] return ([0] * len(__UpperCAmelCase )) + [1] + ([0] * len(__UpperCAmelCase )) + [1] def _UpperCamelCase ( self ,SCREAMING_SNAKE_CASE__ ) -> str: """simple docstring""" if len(__UpperCAmelCase ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( f'''This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated''' ''' eos tokens being added.''' ) return token_ids else: return token_ids + [self.eos_token_id] def _UpperCamelCase ( self ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ = None ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE :Tuple = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def _UpperCamelCase ( self ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ = None ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE :Tuple = self._add_eos_if_not_present(__UpperCAmelCase ) if token_ids_a is None: return token_ids_a else: __SCREAMING_SNAKE_CASE :Optional[Any] = self._add_eos_if_not_present(__UpperCAmelCase ) return token_ids_a + token_ids_a def _UpperCamelCase ( self ,SCREAMING_SNAKE_CASE__ ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE :str = [chr(__UpperCAmelCase ) for i in text.encode('''utf-8''' )] return tokens def _UpperCamelCase ( self ,SCREAMING_SNAKE_CASE__ ) -> Optional[Any]: """simple docstring""" if token in self.special_tokens_encoder: __SCREAMING_SNAKE_CASE :Any = self.special_tokens_encoder[token] elif token in self.added_tokens_encoder: __SCREAMING_SNAKE_CASE :Dict = self.added_tokens_encoder[token] elif len(__UpperCAmelCase ) != 1: __SCREAMING_SNAKE_CASE :Optional[Any] = self.unk_token_id else: __SCREAMING_SNAKE_CASE :str = ord(__UpperCAmelCase ) + self._num_special_tokens return token_id def _UpperCamelCase ( self ,SCREAMING_SNAKE_CASE__ ) -> List[Any]: """simple docstring""" if index in self.special_tokens_decoder: __SCREAMING_SNAKE_CASE :Dict = self.special_tokens_decoder[index] else: __SCREAMING_SNAKE_CASE :List[str] = chr(index - self._num_special_tokens ) return token def _UpperCamelCase ( self ,SCREAMING_SNAKE_CASE__ ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE :Union[str, Any] = b'''''' for token in tokens: if token in self.special_tokens_decoder: __SCREAMING_SNAKE_CASE :Dict = self.special_tokens_decoder[token].encode('''utf-8''' ) elif token in self.added_tokens_decoder: __SCREAMING_SNAKE_CASE :Dict = self.special_tokens_decoder[token].encode('''utf-8''' ) elif token in self.special_tokens_encoder: __SCREAMING_SNAKE_CASE :Optional[int] = token.encode('''utf-8''' ) elif token in self.added_tokens_encoder: __SCREAMING_SNAKE_CASE :Dict = token.encode('''utf-8''' ) else: __SCREAMING_SNAKE_CASE :int = bytes([ord(__UpperCAmelCase )] ) bstring += tok_string __SCREAMING_SNAKE_CASE :Union[str, Any] = bstring.decode('''utf-8''' ,errors='''ignore''' ) return string def _UpperCamelCase ( self ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ = None ) -> Tuple: """simple docstring""" return ()
191
from __future__ import annotations from typing import Generic, TypeVar a_ = TypeVar("""T""") class __lowerCAmelCase ( Generic[T] ): def __init__( self , __UpperCAmelCase ): '''simple docstring''' __lowerCamelCase = data __lowerCamelCase = self __lowerCamelCase = 0 class __lowerCAmelCase ( Generic[T] ): def __init__( self ): '''simple docstring''' # map from node name to the node object __lowerCamelCase = {} def lowerCamelCase ( self , __UpperCAmelCase ): '''simple docstring''' # create a new set with x as its member __lowerCamelCase = DisjointSetTreeNode(__UpperCAmelCase ) def lowerCamelCase ( self , __UpperCAmelCase ): '''simple docstring''' # find the set x belongs to (with path-compression) __lowerCamelCase = self.map[data] if elem_ref != elem_ref.parent: __lowerCamelCase = self.find_set(elem_ref.parent.data ) return elem_ref.parent def lowerCamelCase ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' # helper function for union operation if nodea.rank > nodea.rank: __lowerCamelCase = nodea else: __lowerCamelCase = nodea if nodea.rank == nodea.rank: nodea.rank += 1 def lowerCamelCase ( self , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' # merge 2 disjoint sets self.link(self.find_set(__UpperCAmelCase ) , self.find_set(__UpperCAmelCase ) ) class __lowerCAmelCase ( Generic[T] ): def __init__( self ): '''simple docstring''' # connections: map from the node to the neighbouring nodes (with weights) __lowerCamelCase = {} def lowerCamelCase ( self , __UpperCAmelCase ): '''simple docstring''' # add a node ONLY if its not present in the graph if node not in self.connections: __lowerCamelCase = {} def lowerCamelCase ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' # add an edge with the given weight self.add_node(__UpperCAmelCase ) self.add_node(__UpperCAmelCase ) __lowerCamelCase = weight __lowerCamelCase = weight def lowerCamelCase ( self ): '''simple docstring''' __lowerCamelCase = [] __lowerCamelCase = set() for start in self.connections: for end in self.connections[start]: if (start, end) not in seen: seen.add((end, start) ) edges.append((start, end, self.connections[start][end]) ) edges.sort(key=lambda __UpperCAmelCase : x[2] ) # creating the disjoint set __lowerCamelCase = DisjointSetTree[T]() for node in self.connections: disjoint_set.make_set(__UpperCAmelCase ) # MST generation __lowerCamelCase = 0 __lowerCamelCase = 0 __lowerCamelCase = GraphUndirectedWeighted[T]() while num_edges < len(self.connections ) - 1: __lowerCamelCase ,__lowerCamelCase ,__lowerCamelCase = edges[index] index += 1 __lowerCamelCase = disjoint_set.find_set(__UpperCAmelCase ) __lowerCamelCase = disjoint_set.find_set(__UpperCAmelCase ) if parent_u != parent_v: num_edges += 1 graph.add_edge(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) disjoint_set.union(__UpperCAmelCase , __UpperCAmelCase ) return graph
330
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __lowercase = { 'configuration_ctrl': ['CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP', 'CTRLConfig'], 'tokenization_ctrl': ['CTRLTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase = [ 'CTRL_PRETRAINED_MODEL_ARCHIVE_LIST', 'CTRLForSequenceClassification', 'CTRLLMHeadModel', 'CTRLModel', 'CTRLPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase = [ 'TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFCTRLForSequenceClassification', 'TFCTRLLMHeadModel', 'TFCTRLModel', 'TFCTRLPreTrainedModel', ] if TYPE_CHECKING: from .configuration_ctrl import CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRLConfig from .tokenization_ctrl import CTRLTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ctrl import ( CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, CTRLForSequenceClassification, CTRLLMHeadModel, CTRLModel, CTRLPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_ctrl import ( TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, TFCTRLForSequenceClassification, TFCTRLLMHeadModel, TFCTRLModel, TFCTRLPreTrainedModel, ) else: import sys __lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
358
"""simple docstring""" def lowerCAmelCase (__UpperCamelCase : int = 3 , __UpperCamelCase : int = 7 , __UpperCamelCase : int = 1_0_0_0_0_0_0 ): """simple docstring""" __UpperCamelCase =0 __UpperCamelCase =1 for current_denominator in range(1 , limit + 1 ): __UpperCamelCase =current_denominator * numerator // denominator if current_denominator % denominator == 0: current_numerator -= 1 if current_numerator * max_denominator > current_denominator * max_numerator: __UpperCamelCase =current_numerator __UpperCamelCase =current_denominator return max_numerator if __name__ == "__main__": print(solution(numerator=3, denominator=7, limit=1_000_000))
85
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices __lowercase = logging.get_logger(__name__) class _A ( _a ,_a ): """simple docstring""" UpperCAmelCase : Optional[Any] = """maskformer-swin""" UpperCAmelCase : Optional[int] = { """num_attention_heads""": """num_heads""", """num_hidden_layers""": """num_layers""", } def __init__( self : Any , __UpperCAmelCase : List[Any]=224 , __UpperCAmelCase : Dict=4 , __UpperCAmelCase : int=3 , __UpperCAmelCase : int=96 , __UpperCAmelCase : Any=[2, 2, 6, 2] , __UpperCAmelCase : Tuple=[3, 6, 12, 24] , __UpperCAmelCase : Tuple=7 , __UpperCAmelCase : Dict=4.0 , __UpperCAmelCase : Union[str, Any]=True , __UpperCAmelCase : Any=0.0 , __UpperCAmelCase : Optional[Any]=0.0 , __UpperCAmelCase : List[Any]=0.1 , __UpperCAmelCase : List[Any]="gelu" , __UpperCAmelCase : Any=False , __UpperCAmelCase : Optional[int]=0.02 , __UpperCAmelCase : Dict=1e-5 , __UpperCAmelCase : Union[str, Any]=None , __UpperCAmelCase : str=None , **__UpperCAmelCase : List[str] , ): super().__init__(**__UpperCAmelCase) a : int = image_size a : str = patch_size a : Optional[int] = num_channels a : str = embed_dim a : int = depths a : Dict = len(__UpperCAmelCase) a : Dict = num_heads a : Union[str, Any] = window_size a : Optional[Any] = mlp_ratio a : Any = qkv_bias a : str = hidden_dropout_prob a : List[str] = attention_probs_dropout_prob a : Optional[int] = drop_path_rate a : List[str] = hidden_act a : int = use_absolute_embeddings a : int = layer_norm_eps a : List[str] = initializer_range # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model a : Dict = int(embed_dim * 2 ** (len(__UpperCAmelCase) - 1)) a : List[Any] = ["stem"] + [f'''stage{idx}''' for idx in range(1 , len(__UpperCAmelCase) + 1)] a , a : int = get_aligned_output_features_output_indices( out_features=__UpperCAmelCase , out_indices=__UpperCAmelCase , stage_names=self.stage_names)
40
"""simple docstring""" from __future__ import annotations class _A : """simple docstring""" def __init__( self : List[str] , __UpperCAmelCase : int = 0): a : Tuple = key def __snake_case ( self : List[str] , __UpperCAmelCase : str , __UpperCAmelCase : int): assert isinstance(__UpperCAmelCase , __UpperCAmelCase) and isinstance(__UpperCAmelCase , __UpperCAmelCase) a : Dict = key or self.__key or 1 # make sure key is an appropriate size key %= 255 return [chr(ord(__UpperCAmelCase) ^ key) for ch in content] def __snake_case ( self : int , __UpperCAmelCase : str , __UpperCAmelCase : int): assert isinstance(__UpperCAmelCase , __UpperCAmelCase) and isinstance(__UpperCAmelCase , __UpperCAmelCase) a : Optional[Any] = key or self.__key or 1 # make sure key is an appropriate size key %= 255 return [chr(ord(__UpperCAmelCase) ^ key) for ch in content] def __snake_case ( self : Optional[Any] , __UpperCAmelCase : str , __UpperCAmelCase : int = 0): assert isinstance(__UpperCAmelCase , __UpperCAmelCase) and isinstance(__UpperCAmelCase , __UpperCAmelCase) a : List[Any] = key or self.__key or 1 # make sure key can be any size while key > 255: key -= 255 # This will be returned a : Any = "" for ch in content: ans += chr(ord(__UpperCAmelCase) ^ key) return ans def __snake_case ( self : List[str] , __UpperCAmelCase : str , __UpperCAmelCase : int = 0): assert isinstance(__UpperCAmelCase , __UpperCAmelCase) and isinstance(__UpperCAmelCase , __UpperCAmelCase) a : Dict = key or self.__key or 1 # make sure key can be any size while key > 255: key -= 255 # This will be returned a : str = "" for ch in content: ans += chr(ord(__UpperCAmelCase) ^ key) return ans def __snake_case ( self : int , __UpperCAmelCase : str , __UpperCAmelCase : int = 0): assert isinstance(__UpperCAmelCase , __UpperCAmelCase) and isinstance(__UpperCAmelCase , __UpperCAmelCase) try: with open(__UpperCAmelCase) as fin, open("encrypt.out" , "w+") as fout: # actual encrypt-process for line in fin: fout.write(self.encrypt_string(__UpperCAmelCase , __UpperCAmelCase)) except OSError: return False return True def __snake_case ( self : Any , __UpperCAmelCase : str , __UpperCAmelCase : int): assert isinstance(__UpperCAmelCase , __UpperCAmelCase) and isinstance(__UpperCAmelCase , __UpperCAmelCase) try: with open(__UpperCAmelCase) as fin, open("decrypt.out" , "w+") as fout: # actual encrypt-process for line in fin: fout.write(self.decrypt_string(__UpperCAmelCase , __UpperCAmelCase)) except OSError: return False return True # Tests # crypt = XORCipher() # key = 67 # # test encrypt # print(crypt.encrypt("hallo welt",key)) # # test decrypt # print(crypt.decrypt(crypt.encrypt("hallo welt",key), key)) # # test encrypt_string # print(crypt.encrypt_string("hallo welt",key)) # # test decrypt_string # print(crypt.decrypt_string(crypt.encrypt_string("hallo welt",key),key)) # if (crypt.encrypt_file("test.txt",key)): # print("encrypt successful") # else: # print("encrypt unsuccessful") # if (crypt.decrypt_file("encrypt.out",key)): # print("decrypt successful") # else: # print("decrypt unsuccessful")
40
1
import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging __lowerCamelCase : str = logging.get_logger(__name__) __lowerCamelCase : Optional[int] = { """xlnet-base-cased""": """https://huggingface.co/xlnet-base-cased/resolve/main/config.json""", """xlnet-large-cased""": """https://huggingface.co/xlnet-large-cased/resolve/main/config.json""", } class SCREAMING_SNAKE_CASE__ ( UpperCamelCase_ ): """simple docstring""" a_ = "xlnet" a_ = ["mems"] a_ = { "n_token": "vocab_size", # Backward compatibility "hidden_size": "d_model", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self : Tuple , __A : List[Any]=3_2_0_0_0 , __A : Any=1_0_2_4 , __A : Dict=2_4 , __A : Dict=1_6 , __A : Union[str, Any]=4_0_9_6 , __A : int="gelu" , __A : Tuple=True , __A : Tuple="bi" , __A : List[Any]=0.0_2 , __A : Union[str, Any]=1e-1_2 , __A : Any=0.1 , __A : Any=5_1_2 , __A : Optional[Any]=None , __A : Optional[Any]=True , __A : Optional[Any]=False , __A : Dict=False , __A : int=-1 , __A : str=False , __A : List[str]="last" , __A : List[Any]=True , __A : List[str]="tanh" , __A : Optional[Any]=0.1 , __A : Dict=5 , __A : int=5 , __A : List[Any]=5 , __A : Any=1 , __A : int=2 , **__A : int , ): snake_case__ : List[str] = vocab_size snake_case__ : int = d_model snake_case__ : Optional[int] = n_layer snake_case__ : Tuple = n_head if d_model % n_head != 0: raise ValueError(f'''\'d_model % n_head\' ({d_model % n_head}) should be equal to 0''' ) if "d_head" in kwargs: if kwargs["d_head"] != d_model // n_head: raise ValueError( f'''`d_head` ({kwargs['d_head']}) should be equal to `d_model // n_head` ({d_model // n_head})''' ) snake_case__ : Optional[int] = d_model // n_head snake_case__ : Any = ff_activation snake_case__ : Optional[int] = d_inner snake_case__ : Union[str, Any] = untie_r snake_case__ : Optional[int] = attn_type snake_case__ : List[str] = initializer_range snake_case__ : int = layer_norm_eps snake_case__ : Optional[Any] = dropout snake_case__ : Tuple = mem_len snake_case__ : Union[str, Any] = reuse_len snake_case__ : List[str] = bi_data snake_case__ : List[str] = clamp_len snake_case__ : Any = same_length snake_case__ : Tuple = summary_type snake_case__ : List[Any] = summary_use_proj snake_case__ : List[str] = summary_activation snake_case__ : Optional[Any] = summary_last_dropout snake_case__ : Any = start_n_top snake_case__ : Optional[Any] = end_n_top snake_case__ : Union[str, Any] = bos_token_id snake_case__ : Union[str, Any] = pad_token_id snake_case__ : Optional[int] = eos_token_id if "use_cache" in kwargs: warnings.warn( "The `use_cache` argument is deprecated and will be removed in a future version, use `use_mems_eval`" " instead." , __A , ) snake_case__ : Tuple = kwargs["use_cache"] snake_case__ : Optional[Any] = use_mems_eval snake_case__ : List[str] = use_mems_train super().__init__(pad_token_id=__A , bos_token_id=__A , eos_token_id=__A , **__A ) @property def _lowercase ( self : Union[str, Any] ): logger.info(f'''The model {self.model_type} is one of the few models that has no sequence length limit.''' ) return -1 @max_position_embeddings.setter def _lowercase ( self : str , __A : Dict ): # Message copied from Transformer-XL documentation raise NotImplementedError( f'''The model {self.model_type} is one of the few models that has no sequence length limit.''' )
355
# limitations under the License. # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from .pipelines import DiffusionPipeline, ImagePipelineOutput # noqa: F401 from .utils import deprecate deprecate( """pipelines_utils""", """0.22.0""", """Importing `DiffusionPipeline` or `ImagePipelineOutput` from diffusers.pipeline_utils is deprecated. Please import from diffusers.pipelines.pipeline_utils instead.""", standard_warn=False, stacklevel=3, )
286
0
'''simple docstring''' import argparse import collections import os import re 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_table.py UpperCamelCase__ : int = '''src/transformers''' UpperCamelCase__ : Any = '''docs/source/en''' UpperCamelCase__ : Any = '''.''' def lowerCAmelCase_ ( _lowerCamelCase: str , _lowerCamelCase: Optional[Any] , _lowerCamelCase: Union[str, Any] ): with open(_lowerCamelCase , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: __SCREAMING_SNAKE_CASE : List[Any] = f.readlines() # Find the start prompt. __SCREAMING_SNAKE_CASE : Optional[Any] = 0 while not lines[start_index].startswith(_lowerCamelCase ): start_index += 1 start_index += 1 __SCREAMING_SNAKE_CASE : List[str] = start_index while not lines[end_index].startswith(_lowerCamelCase ): end_index += 1 end_index -= 1 while len(lines[start_index] ) <= 1: start_index += 1 while len(lines[end_index] ) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index] ), start_index, end_index, lines # Add here suffixes that are used to identify models, separated by | UpperCamelCase__ : Dict = '''Model|Encoder|Decoder|ForConditionalGeneration''' # Regexes that match TF/Flax/PT model names. UpperCamelCase__ : int = re.compile(R'''TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)''') UpperCamelCase__ : Optional[Any] = re.compile(R'''Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)''') # Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes. UpperCamelCase__ : Optional[int] = re.compile(R'''(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)''') # This is to make sure the transformers module imported is the one in the repo. UpperCamelCase__ : List[Any] = direct_transformers_import(TRANSFORMERS_PATH) def lowerCAmelCase_ ( _lowerCamelCase: Dict ): __SCREAMING_SNAKE_CASE : Tuple = re.finditer(""".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)""" , _lowerCamelCase ) return [m.group(0 ) for m in matches] def lowerCAmelCase_ ( _lowerCamelCase: Tuple , _lowerCamelCase: Optional[int] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = 2 if text == """✅""" or text == """❌""" else len(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = (width - text_length) // 2 __SCREAMING_SNAKE_CASE : Dict = width - text_length - left_indent return " " * left_indent + text + " " * right_indent def lowerCAmelCase_ ( ): __SCREAMING_SNAKE_CASE : str = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES __SCREAMING_SNAKE_CASE : Any = { name: config_maping_names[code] for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if code in config_maping_names } __SCREAMING_SNAKE_CASE : List[Any] = {name: config.replace("""Config""" , """""" ) for name, config in model_name_to_config.items()} # Dictionaries flagging if each model prefix has a slow/fast tokenizer, backend in PT/TF/Flax. __SCREAMING_SNAKE_CASE : Tuple = collections.defaultdict(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = collections.defaultdict(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = collections.defaultdict(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = collections.defaultdict(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = collections.defaultdict(_lowerCamelCase ) # Let's lookup through all transformers object (once). for attr_name in dir(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Union[str, Any] = None if attr_name.endswith("""Tokenizer""" ): __SCREAMING_SNAKE_CASE : Union[str, Any] = slow_tokenizers __SCREAMING_SNAKE_CASE : Optional[Any] = attr_name[:-9] elif attr_name.endswith("""TokenizerFast""" ): __SCREAMING_SNAKE_CASE : Any = fast_tokenizers __SCREAMING_SNAKE_CASE : Optional[Any] = attr_name[:-13] elif _re_tf_models.match(_lowerCamelCase ) is not None: __SCREAMING_SNAKE_CASE : List[Any] = tf_models __SCREAMING_SNAKE_CASE : Union[str, Any] = _re_tf_models.match(_lowerCamelCase ).groups()[0] elif _re_flax_models.match(_lowerCamelCase ) is not None: __SCREAMING_SNAKE_CASE : Union[str, Any] = flax_models __SCREAMING_SNAKE_CASE : List[str] = _re_flax_models.match(_lowerCamelCase ).groups()[0] elif _re_pt_models.match(_lowerCamelCase ) is not None: __SCREAMING_SNAKE_CASE : Dict = pt_models __SCREAMING_SNAKE_CASE : Optional[Any] = _re_pt_models.match(_lowerCamelCase ).groups()[0] if lookup_dict is not None: while len(_lowerCamelCase ) > 0: if attr_name in model_name_to_prefix.values(): __SCREAMING_SNAKE_CASE : List[str] = True break # Try again after removing the last word in the name __SCREAMING_SNAKE_CASE : Optional[Any] = """""".join(camel_case_split(_lowerCamelCase )[:-1] ) # Let's build that table! __SCREAMING_SNAKE_CASE : Optional[int] = list(model_name_to_config.keys() ) model_names.sort(key=str.lower ) __SCREAMING_SNAKE_CASE : List[Any] = ["""Model""", """Tokenizer slow""", """Tokenizer fast""", """PyTorch support""", """TensorFlow support""", """Flax Support"""] # We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side). __SCREAMING_SNAKE_CASE : int = [len(_lowerCamelCase ) + 2 for c in columns] __SCREAMING_SNAKE_CASE : Optional[Any] = max([len(_lowerCamelCase ) for name in model_names] ) + 2 # Build the table per se __SCREAMING_SNAKE_CASE : Optional[int] = """|""" + """|""".join([_center_text(_lowerCamelCase , _lowerCamelCase ) for c, w in zip(_lowerCamelCase , _lowerCamelCase )] ) + """|\n""" # Use ":-----:" format to center-aligned table cell texts table += "|" + "|".join([""":""" + """-""" * (w - 2) + """:""" for w in widths] ) + "|\n" __SCREAMING_SNAKE_CASE : List[Any] = {True: """✅""", False: """❌"""} for name in model_names: __SCREAMING_SNAKE_CASE : Dict = model_name_to_prefix[name] __SCREAMING_SNAKE_CASE : Optional[Any] = [ name, check[slow_tokenizers[prefix]], check[fast_tokenizers[prefix]], check[pt_models[prefix]], check[tf_models[prefix]], check[flax_models[prefix]], ] table += "|" + "|".join([_center_text(_lowerCamelCase , _lowerCamelCase ) for l, w in zip(_lowerCamelCase , _lowerCamelCase )] ) + "|\n" return table def lowerCAmelCase_ ( _lowerCamelCase: Optional[int]=False ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = _find_text_in_file( filename=os.path.join(_lowerCamelCase , """index.md""" ) , start_prompt="""<!--This table is updated automatically from the auto modules""" , end_prompt="""<!-- End table-->""" , ) __SCREAMING_SNAKE_CASE : Optional[Any] = get_model_table_from_auto_modules() if current_table != new_table: if overwrite: with open(os.path.join(_lowerCamelCase , """index.md""" ) , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f: f.writelines(lines[:start_index] + [new_table] + lines[end_index:] ) else: raise ValueError( """The model table in the `index.md` has not been updated. Run `make fix-copies` to fix this.""" ) if __name__ == "__main__": UpperCamelCase__ : Any = argparse.ArgumentParser() parser.add_argument('''--fix_and_overwrite''', action='''store_true''', help='''Whether to fix inconsistencies.''') UpperCamelCase__ : List[str] = parser.parse_args() check_model_table(args.fix_and_overwrite)
112
'''simple docstring''' from collections.abc import Iterable from typing import Any class _UpperCamelCase : '''simple docstring''' def __init__( self : Optional[int] , lowerCAmelCase__ : int | None = None ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = value __SCREAMING_SNAKE_CASE : Node | None = None # Added in order to delete a node easier __SCREAMING_SNAKE_CASE : Node | None = None __SCREAMING_SNAKE_CASE : Node | None = None def __repr__( self : Optional[Any] ): """simple docstring""" from pprint import pformat if self.left is None and self.right is None: return str(self.value ) return pformat({F"{self.value}": (self.left, self.right)} , indent=1 ) class _UpperCamelCase : '''simple docstring''' def __init__( self : Optional[int] , lowerCAmelCase__ : Node | None = None ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = root def __str__( self : Union[str, Any] ): """simple docstring""" return str(self.root ) def UpperCamelCase__ ( self : Dict , lowerCAmelCase__ : Node , lowerCAmelCase__ : Node | None ): """simple docstring""" if new_children is not None: # reset its kids __SCREAMING_SNAKE_CASE : List[str] = node.parent if node.parent is not None: # reset its parent if self.is_right(lowerCAmelCase__ ): # If it is the right children __SCREAMING_SNAKE_CASE : Any = new_children else: __SCREAMING_SNAKE_CASE : int = new_children else: __SCREAMING_SNAKE_CASE : int = new_children def UpperCamelCase__ ( self : str , lowerCAmelCase__ : Node ): """simple docstring""" if node.parent and node.parent.right: return node == node.parent.right return False def UpperCamelCase__ ( self : List[Any] ): """simple docstring""" return self.root is None def UpperCamelCase__ ( self : Optional[Any] , lowerCAmelCase__ : str ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = Node(lowerCAmelCase__ ) # create a new Node if self.empty(): # if Tree is empty __SCREAMING_SNAKE_CASE : Optional[int] = new_node # set its root else: # Tree is not empty __SCREAMING_SNAKE_CASE : Optional[int] = self.root # from root if parent_node is None: return while True: # While we don't get to a leaf if value < parent_node.value: # We go left if parent_node.left is None: __SCREAMING_SNAKE_CASE : List[str] = new_node # We insert the new node in a leaf break else: __SCREAMING_SNAKE_CASE : Any = parent_node.left else: if parent_node.right is None: __SCREAMING_SNAKE_CASE : Tuple = new_node break else: __SCREAMING_SNAKE_CASE : List[str] = parent_node.right __SCREAMING_SNAKE_CASE : Tuple = parent_node def UpperCamelCase__ ( self : str , *lowerCAmelCase__ : List[Any] ): """simple docstring""" for value in values: self.__insert(lowerCAmelCase__ ) def UpperCamelCase__ ( self : List[str] , lowerCAmelCase__ : Union[str, Any] ): """simple docstring""" if self.empty(): raise IndexError("""Warning: Tree is empty! please use another.""" ) else: __SCREAMING_SNAKE_CASE : List[Any] = self.root # use lazy evaluation here to avoid NoneType Attribute error while node is not None and node.value is not value: __SCREAMING_SNAKE_CASE : Any = node.left if value < node.value else node.right return node def UpperCamelCase__ ( self : List[Any] , lowerCAmelCase__ : Node | None = None ): """simple docstring""" if node is None: if self.root is None: return None __SCREAMING_SNAKE_CASE : Optional[Any] = self.root if not self.empty(): while node.right is not None: __SCREAMING_SNAKE_CASE : Tuple = node.right return node def UpperCamelCase__ ( self : Dict , lowerCAmelCase__ : Node | None = None ): """simple docstring""" if node is None: __SCREAMING_SNAKE_CASE : Union[str, Any] = self.root if self.root is None: return None if not self.empty(): __SCREAMING_SNAKE_CASE : Optional[Any] = self.root while node.left is not None: __SCREAMING_SNAKE_CASE : Any = node.left return node def UpperCamelCase__ ( self : str , lowerCAmelCase__ : int ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[str] = self.search(lowerCAmelCase__ ) # Look for the node with that label if node is not None: if node.left is None and node.right is None: # If it has no children self.__reassign_nodes(lowerCAmelCase__ , lowerCAmelCase__ ) elif node.left is None: # Has only right children self.__reassign_nodes(lowerCAmelCase__ , node.right ) elif node.right is None: # Has only left children self.__reassign_nodes(lowerCAmelCase__ , node.left ) else: __SCREAMING_SNAKE_CASE : Tuple = self.get_max( node.left ) # Gets the max value of the left branch self.remove(tmp_node.value ) # type: ignore __SCREAMING_SNAKE_CASE : Optional[Any] = ( tmp_node.value # type: ignore ) # Assigns the value to the node to delete and keep tree structure def UpperCamelCase__ ( self : Tuple , lowerCAmelCase__ : Node | None ): """simple docstring""" if node is not None: yield node # Preorder Traversal yield from self.preorder_traverse(node.left ) yield from self.preorder_traverse(node.right ) def UpperCamelCase__ ( self : Optional[int] , lowerCAmelCase__ : Optional[Any]=None ): """simple docstring""" if traversal_function is None: return self.preorder_traverse(self.root ) else: return traversal_function(self.root ) def UpperCamelCase__ ( self : str , lowerCAmelCase__ : list , lowerCAmelCase__ : Node | None ): """simple docstring""" if node: self.inorder(lowerCAmelCase__ , node.left ) arr.append(node.value ) self.inorder(lowerCAmelCase__ , node.right ) def UpperCamelCase__ ( self : int , lowerCAmelCase__ : int , lowerCAmelCase__ : Node ): """simple docstring""" __SCREAMING_SNAKE_CASE : list[int] = [] self.inorder(lowerCAmelCase__ , lowerCAmelCase__ ) # append all values to list using inorder traversal return arr[k - 1] def lowerCAmelCase_ ( _lowerCamelCase: Node | None ): __SCREAMING_SNAKE_CASE : Optional[Any] = [] if curr_node is not None: __SCREAMING_SNAKE_CASE : Optional[int] = postorder(curr_node.left ) + postorder(curr_node.right ) + [curr_node] return node_list def lowerCAmelCase_ ( ): __SCREAMING_SNAKE_CASE : str = (8, 3, 6, 1, 10, 14, 13, 4, 7) __SCREAMING_SNAKE_CASE : Dict = BinarySearchTree() for i in testlist: t.insert(_lowerCamelCase ) # Prints all the elements of the list in order traversal print(_lowerCamelCase ) if t.search(6 ) is not None: print("""The value 6 exists""" ) else: print("""The value 6 doesn't exist""" ) if t.search(-1 ) is not None: print("""The value -1 exists""" ) else: print("""The value -1 doesn't exist""" ) if not t.empty(): print("""Max Value: """ , t.get_max().value ) # type: ignore print("""Min Value: """ , t.get_min().value ) # type: ignore for i in testlist: t.remove(_lowerCamelCase ) print(_lowerCamelCase ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
112
1
import requests from bsa import BeautifulSoup def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : str = "https://www.worldometers.info/coronavirus") -> dict: '''simple docstring''' __UpperCamelCase : List[Any] = BeautifulSoup(requests.get(_lowerCamelCase).text , "html.parser") __UpperCamelCase : Union[str, Any] = soup.findAll("h1") __UpperCamelCase : Union[str, Any] = soup.findAll("div" , {"class": "maincounter-number"}) keys += soup.findAll("span" , {"class": "panel-title"}) values += soup.findAll("div" , {"class": "number-table-main"}) return {key.text.strip(): value.text.strip() for key, value in zip(_lowerCamelCase , _lowerCamelCase)} if __name__ == "__main__": print('\033[1m' + 'COVID-19 Status of the World' + '\033[0m\n') for key, value in world_covidaa_stats().items(): print(f"{key}\n{value}\n")
151
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 _SCREAMING_SNAKE_CASE ( _lowerCamelCase : Optional[int]) -> Dict: '''simple docstring''' return EnvironmentCommand() def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : Dict) -> Dict: '''simple docstring''' return EnvironmentCommand(args.accelerate_config_file) class lowerCamelCase__ ( __lowercase): '''simple docstring''' @staticmethod def _lowerCamelCase ( a :ArgumentParser ) -> str: __UpperCamelCase : List[Any] = 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 :Tuple , a :Dict , *a :List[str] ) -> None: __UpperCamelCase : List[str] = accelerate_config_file def _lowerCamelCase ( self :int ) -> Dict: __UpperCamelCase : int = "not installed" if is_safetensors_available(): import safetensors __UpperCamelCase : List[str] = safetensors.__version__ elif importlib.util.find_spec("safetensors" ) is not None: import safetensors __UpperCamelCase : Optional[Any] = f'{safetensors.__version__} but is ignored because of PyTorch version too old.' __UpperCamelCase : List[str] = "not installed" __UpperCamelCase : List[str] = "not found" if is_accelerate_available(): import accelerate from accelerate.commands.config import default_config_file, load_config_from_file __UpperCamelCase : Tuple = accelerate.__version__ # Get the default from the config file. if self._accelerate_config_file is not None or os.path.isfile(a ): __UpperCamelCase : Dict = load_config_from_file(self._accelerate_config_file ).to_dict() __UpperCamelCase : int = ( "\n".join([f'\t- {prop}: {val}' for prop, val in accelerate_config.items()] ) if isinstance(a , a ) else f'\t{accelerate_config}' ) __UpperCamelCase : List[Any] = "not installed" __UpperCamelCase : Dict = "NA" if is_torch_available(): import torch __UpperCamelCase : Optional[int] = torch.__version__ __UpperCamelCase : Optional[Any] = torch.cuda.is_available() __UpperCamelCase : Dict = "not installed" __UpperCamelCase : str = "NA" if is_tf_available(): import tensorflow as tf __UpperCamelCase : Optional[Any] = tf.__version__ try: # deprecated in v2.1 __UpperCamelCase : Dict = tf.test.is_gpu_available() except AttributeError: # returns list of devices, convert to bool __UpperCamelCase : Optional[Any] = bool(tf.config.list_physical_devices("GPU" ) ) __UpperCamelCase : List[Any] = "not installed" __UpperCamelCase : Any = "not installed" __UpperCamelCase : Tuple = "not installed" __UpperCamelCase : Optional[int] = "NA" if is_flax_available(): import flax import jax import jaxlib __UpperCamelCase : int = flax.__version__ __UpperCamelCase : Any = jax.__version__ __UpperCamelCase : Optional[int] = jaxlib.__version__ __UpperCamelCase : List[Any] = jax.lib.xla_bridge.get_backend().platform __UpperCamelCase : Optional[Any] = { "`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 _lowerCamelCase ( a :str ) -> int: return "\n".join([f'- {prop}: {val}' for prop, val in d.items()] ) + "\n"
151
1
"""simple docstring""" def a__ ( SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : list[int] , SCREAMING_SNAKE_CASE : int ): '''simple docstring''' def count_of_possible_combinations(SCREAMING_SNAKE_CASE : int ) -> int: if target < 0: return 0 if target == 0: return 1 return sum(count_of_possible_combinations(target - item ) for item in array ) return count_of_possible_combinations(SCREAMING_SNAKE_CASE ) def a__ ( SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : list[int] , SCREAMING_SNAKE_CASE : int ): '''simple docstring''' def count_of_possible_combinations_with_dp_array( SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : list[int] ) -> int: if target < 0: return 0 if target == 0: return 1 if dp_array[target] != -1: return dp_array[target] lowerCAmelCase : Optional[Any] = sum( count_of_possible_combinations_with_dp_array(target - item , SCREAMING_SNAKE_CASE ) for item in array ) lowerCAmelCase : Any = answer return answer lowerCAmelCase : List[Any] = [-1] * (target + 1) return count_of_possible_combinations_with_dp_array(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def a__ ( SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : list[int] , SCREAMING_SNAKE_CASE : int ): '''simple docstring''' lowerCAmelCase : Dict = [0] * (target + 1) lowerCAmelCase : Dict = 1 for i in range(1 , target + 1 ): for j in range(SCREAMING_SNAKE_CASE ): if i - array[j] >= 0: dp_array[i] += dp_array[i - array[j]] return dp_array[target] if __name__ == "__main__": import doctest doctest.testmod() lowerCAmelCase__ = 3 lowerCAmelCase__ = 5 lowerCAmelCase__ = [1, 2, 5] print(combination_sum_iv(n, array, target))
108
"""simple docstring""" import unittest from huggingface_hub import hf_hub_download from transformers import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VideoMAEFeatureExtractor from transformers.pipelines import VideoClassificationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_decord, require_tf, require_torch, require_torch_or_tf, require_vision, ) from .test_pipelines_common import ANY @is_pipeline_test @require_torch_or_tf @require_vision @require_decord class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): """simple docstring""" a : int =MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING def lowercase__ ( self , snake_case__ , snake_case__ , snake_case__ ): """simple docstring""" lowerCAmelCase : Tuple = hf_hub_download( repo_id="nateraw/video-demo" , filename="archery.mp4" , repo_type="dataset" ) lowerCAmelCase : Dict = VideoClassificationPipeline(model=snake_case__ , image_processor=snake_case__ , top_k=2 ) lowerCAmelCase : Any = [ example_video_filepath, "https://huggingface.co/datasets/nateraw/video-demo/resolve/main/archery.mp4", ] return video_classifier, examples def lowercase__ ( self , snake_case__ , snake_case__ ): """simple docstring""" for example in examples: lowerCAmelCase : str = video_classifier(snake_case__ ) self.assertEqual( snake_case__ , [ {"score": ANY(snake_case__ ), "label": ANY(snake_case__ )}, {"score": ANY(snake_case__ ), "label": ANY(snake_case__ )}, ] , ) @require_torch def lowercase__ ( self ): """simple docstring""" lowerCAmelCase : Union[str, Any] = "hf-internal-testing/tiny-random-VideoMAEForVideoClassification" lowerCAmelCase : str = VideoMAEFeatureExtractor( size={"shortest_edge": 10} , crop_size={"height": 10, "width": 10} ) lowerCAmelCase : int = pipeline( "video-classification" , model=snake_case__ , feature_extractor=snake_case__ , frame_sampling_rate=4 ) lowerCAmelCase : Optional[int] = hf_hub_download(repo_id="nateraw/video-demo" , filename="archery.mp4" , repo_type="dataset" ) lowerCAmelCase : Union[str, Any] = video_classifier(snake_case__ , top_k=2 ) self.assertEqual( nested_simplify(snake_case__ , decimals=4 ) , [{"score": 0.5199, "label": "LABEL_0"}, {"score": 0.4801, "label": "LABEL_1"}] , ) lowerCAmelCase : Tuple = video_classifier( [ video_file_path, video_file_path, ] , top_k=2 , ) self.assertEqual( nested_simplify(snake_case__ , decimals=4 ) , [ [{"score": 0.5199, "label": "LABEL_0"}, {"score": 0.4801, "label": "LABEL_1"}], [{"score": 0.5199, "label": "LABEL_0"}, {"score": 0.4801, "label": "LABEL_1"}], ] , ) @require_tf def lowercase__ ( self ): """simple docstring""" pass
108
1
import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import MaskaFormerConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel if is_vision_available(): from transformers import MaskaFormerImageProcessor if is_vision_available(): from PIL import Image class lowerCAmelCase_ : def __init__( self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_=2, SCREAMING_SNAKE_CASE_=True, SCREAMING_SNAKE_CASE_=False, SCREAMING_SNAKE_CASE_=10, SCREAMING_SNAKE_CASE_=3, SCREAMING_SNAKE_CASE_=32 * 8, SCREAMING_SNAKE_CASE_=32 * 8, SCREAMING_SNAKE_CASE_=4, SCREAMING_SNAKE_CASE_=64, ) -> List[Any]: UpperCamelCase : List[Any] = parent UpperCamelCase : Tuple = batch_size UpperCamelCase : Tuple = is_training UpperCamelCase : Optional[int] = use_auxiliary_loss UpperCamelCase : Optional[int] = num_queries UpperCamelCase : Any = num_channels UpperCamelCase : List[Any] = min_size UpperCamelCase : str = max_size UpperCamelCase : str = num_labels UpperCamelCase : Optional[int] = hidden_dim UpperCamelCase : Tuple = hidden_dim def snake_case_ ( self ) -> int: UpperCamelCase : List[Any] = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = torch.ones([self.batch_size, self.min_size, self.max_size], device=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size], device=SCREAMING_SNAKE_CASE_ ) > 0.5 ).float() UpperCamelCase : Optional[Any] = (torch.rand((self.batch_size, self.num_labels), device=SCREAMING_SNAKE_CASE_ ) > 0.5).long() UpperCamelCase : List[Any] = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def snake_case_ ( self ) -> int: UpperCamelCase : Optional[int] = MaskaFormerConfig( hidden_size=self.hidden_dim, ) UpperCamelCase : Optional[Any] = self.num_queries UpperCamelCase : int = self.num_labels UpperCamelCase : Optional[int] = [1, 1, 1, 1] UpperCamelCase : Union[str, Any] = self.num_channels UpperCamelCase : Union[str, Any] = 64 UpperCamelCase : List[Any] = 128 UpperCamelCase : Union[str, Any] = self.hidden_dim UpperCamelCase : List[Any] = self.hidden_dim UpperCamelCase : List[Any] = self.hidden_dim return config def snake_case_ ( self ) -> List[str]: UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase : List[str] = self.prepare_config_and_inputs() UpperCamelCase : str = {'pixel_values': pixel_values, 'pixel_mask': pixel_mask} return config, inputs_dict def snake_case_ ( self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) -> Tuple: UpperCamelCase : Optional[int] = output.encoder_hidden_states UpperCamelCase : Optional[Any] = output.pixel_decoder_hidden_states UpperCamelCase : Tuple = output.transformer_decoder_hidden_states self.parent.assertTrue(len(SCREAMING_SNAKE_CASE_ ), len(config.backbone_config.depths ) ) self.parent.assertTrue(len(SCREAMING_SNAKE_CASE_ ), len(config.backbone_config.depths ) ) self.parent.assertTrue(len(SCREAMING_SNAKE_CASE_ ), config.decoder_layers ) def snake_case_ ( self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_=False ) -> List[str]: with torch.no_grad(): UpperCamelCase : Tuple = MaskaFormerModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Optional[int] = model(pixel_values=SCREAMING_SNAKE_CASE_, pixel_mask=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE_, output_hidden_states=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape, (self.batch_size, self.num_queries, self.hidden_dim), ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) def snake_case_ ( self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) -> str: UpperCamelCase : List[str] = MaskaFormerForUniversalSegmentation(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() def comm_check_on_output(SCREAMING_SNAKE_CASE_ ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape, (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4), ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape, (self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): UpperCamelCase : List[Any] = model(pixel_values=SCREAMING_SNAKE_CASE_, pixel_mask=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = model(SCREAMING_SNAKE_CASE_ ) comm_check_on_output(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = model( pixel_values=SCREAMING_SNAKE_CASE_, pixel_mask=SCREAMING_SNAKE_CASE_, mask_labels=SCREAMING_SNAKE_CASE_, class_labels=SCREAMING_SNAKE_CASE_ ) comm_check_on_output(SCREAMING_SNAKE_CASE_ ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape, torch.Size([1] ) ) @require_torch class lowerCAmelCase_ ( a__ , a__ , unittest.TestCase ): UpperCAmelCase__ : Optional[Any] = (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else () UpperCAmelCase__ : Any = {"feature-extraction": MaskaFormerModel} if is_torch_available() else {} UpperCAmelCase__ : Optional[int] = False UpperCAmelCase__ : str = False UpperCAmelCase__ : Dict = False UpperCAmelCase__ : Dict = False def snake_case_ ( self ) -> Optional[int]: UpperCamelCase : List[str] = MaskaFormerModelTester(self ) UpperCamelCase : Dict = ConfigTester(self, config_class=SCREAMING_SNAKE_CASE_, has_text_modality=SCREAMING_SNAKE_CASE_ ) def snake_case_ ( self ) -> int: self.config_tester.run_common_tests() def snake_case_ ( self ) -> List[Any]: UpperCamelCase , UpperCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(SCREAMING_SNAKE_CASE_, **SCREAMING_SNAKE_CASE_, output_hidden_states=SCREAMING_SNAKE_CASE_ ) def snake_case_ ( self ) -> Dict: UpperCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*SCREAMING_SNAKE_CASE_ ) @unittest.skip(reason='Mask2Former does not use inputs_embeds' ) def snake_case_ ( self ) -> Optional[int]: pass @unittest.skip(reason='Mask2Former does not have a get_input_embeddings method' ) def snake_case_ ( self ) -> Any: pass @unittest.skip(reason='Mask2Former is not a generative model' ) def snake_case_ ( self ) -> int: pass @unittest.skip(reason='Mask2Former does not use token embeddings' ) def snake_case_ ( self ) -> List[str]: pass @require_torch_multi_gpu @unittest.skip( reason='Mask2Former has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`' ) def snake_case_ ( self ) -> List[str]: pass @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def snake_case_ ( self ) -> Tuple: pass def snake_case_ ( self ) -> Dict: UpperCamelCase , UpperCamelCase : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase : List[str] = model_class(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Dict = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase : int = [*signature.parameters.keys()] UpperCamelCase : List[Any] = ['pixel_values'] self.assertListEqual(arg_names[:1], SCREAMING_SNAKE_CASE_ ) @slow def snake_case_ ( self ) -> Union[str, Any]: for model_name in ["facebook/mask2former-swin-small-coco-instance"]: UpperCamelCase : int = MaskaFormerModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def snake_case_ ( self ) -> Dict: UpperCamelCase : Optional[Any] = (self.model_tester.min_size,) * 2 UpperCamelCase : str = { 'pixel_values': torch.randn((2, 3, *size), device=SCREAMING_SNAKE_CASE_ ), 'mask_labels': torch.randn((2, 10, *size), device=SCREAMING_SNAKE_CASE_ ), 'class_labels': torch.zeros(2, 10, device=SCREAMING_SNAKE_CASE_ ).long(), } UpperCamelCase : List[str] = self.model_tester.get_config() UpperCamelCase : Optional[int] = MaskaFormerForUniversalSegmentation(SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : int = model(**SCREAMING_SNAKE_CASE_ ) self.assertTrue(outputs.loss is not None ) def snake_case_ ( self ) -> Tuple: UpperCamelCase , UpperCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(SCREAMING_SNAKE_CASE_, **SCREAMING_SNAKE_CASE_, output_hidden_states=SCREAMING_SNAKE_CASE_ ) def snake_case_ ( self ) -> int: UpperCamelCase , UpperCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase : Tuple = model_class(SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[str] = model(**SCREAMING_SNAKE_CASE_, output_attentions=SCREAMING_SNAKE_CASE_ ) self.assertTrue(outputs.attentions is not None ) def snake_case_ ( self ) -> Optional[Any]: if not self.model_tester.is_training: return UpperCamelCase : Tuple = self.all_model_classes[1] UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs() UpperCamelCase : int = model_class(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.train() UpperCamelCase : List[Any] = model(SCREAMING_SNAKE_CASE_, mask_labels=SCREAMING_SNAKE_CASE_, class_labels=SCREAMING_SNAKE_CASE_ ).loss loss.backward() def snake_case_ ( self ) -> Optional[Any]: UpperCamelCase : int = self.all_model_classes[1] UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase : int = self.model_tester.prepare_config_and_inputs() UpperCamelCase : str = True UpperCamelCase : Union[str, Any] = True UpperCamelCase : List[Any] = model_class(SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ) model.train() UpperCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE_, mask_labels=SCREAMING_SNAKE_CASE_, class_labels=SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() UpperCamelCase : Union[str, Any] = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() UpperCamelCase : Optional[Any] = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() UpperCamelCase : Dict = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) __UpperCAmelCase = 1e-4 def UpperCamelCase ( ) -> str: UpperCamelCase : Union[str, Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_vision @slow class lowerCAmelCase_ ( unittest.TestCase ): @cached_property def snake_case_ ( self ) -> List[Any]: return "facebook/mask2former-swin-small-coco-instance" @cached_property def snake_case_ ( self ) -> Optional[int]: return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints ) if is_vision_available() else None def snake_case_ ( self ) -> Dict: UpperCamelCase : str = MaskaFormerModel.from_pretrained(self.model_checkpoints ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = self.default_image_processor UpperCamelCase : Any = prepare_img() UpperCamelCase : Union[str, Any] = image_processor(SCREAMING_SNAKE_CASE_, return_tensors='pt' ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = inputs['pixel_values'].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(SCREAMING_SNAKE_CASE_, (1, 3, 384, 384) ) with torch.no_grad(): UpperCamelCase : Tuple = model(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = torch.tensor( [[-0.27_90, -1.07_17, -1.16_68], [-0.51_28, -0.31_28, -0.49_87], [-0.58_32, 0.19_71, -0.01_97]] ).to(SCREAMING_SNAKE_CASE_ ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3], SCREAMING_SNAKE_CASE_, atol=SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase : Tuple = torch.tensor( [[0.89_73, 1.18_47, 1.17_76], [1.19_34, 1.50_40, 1.51_28], [1.11_53, 1.44_86, 1.49_51]] ).to(SCREAMING_SNAKE_CASE_ ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3], SCREAMING_SNAKE_CASE_, atol=SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase : int = torch.tensor( [[2.11_52, 1.70_00, -0.86_03], [1.58_08, 1.80_04, -0.93_53], [1.60_43, 1.74_95, -0.59_99]] ).to(SCREAMING_SNAKE_CASE_ ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3], SCREAMING_SNAKE_CASE_, atol=SCREAMING_SNAKE_CASE_ ) ) def snake_case_ ( self ) -> Optional[Any]: UpperCamelCase : Optional[int] = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(SCREAMING_SNAKE_CASE_ ).eval() UpperCamelCase : List[str] = self.default_image_processor UpperCamelCase : Any = prepare_img() UpperCamelCase : List[Any] = image_processor(SCREAMING_SNAKE_CASE_, return_tensors='pt' ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : List[Any] = inputs['pixel_values'].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(SCREAMING_SNAKE_CASE_, (1, 3, 384, 384) ) with torch.no_grad(): UpperCamelCase : str = model(**SCREAMING_SNAKE_CASE_ ) # masks_queries_logits UpperCamelCase : Dict = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape, (1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) ) UpperCamelCase : Any = [ [-8.78_39, -9.00_56, -8.81_21], [-7.41_04, -7.03_13, -6.54_01], [-6.61_05, -6.34_27, -6.46_75], ] UpperCamelCase : int = torch.tensor(SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3], SCREAMING_SNAKE_CASE_, atol=SCREAMING_SNAKE_CASE_ ) ) # class_queries_logits UpperCamelCase : Tuple = outputs.class_queries_logits self.assertEqual(class_queries_logits.shape, (1, model.config.num_queries, model.config.num_labels + 1) ) UpperCamelCase : Tuple = torch.tensor( [ [1.83_24, -8.08_35, -4.19_22], [0.84_50, -9.00_50, -3.60_53], [0.30_45, -7.72_93, -3.02_75], ] ).to(SCREAMING_SNAKE_CASE_ ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3], SCREAMING_SNAKE_CASE_, atol=SCREAMING_SNAKE_CASE_ ) ) def snake_case_ ( self ) -> Any: UpperCamelCase : Any = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(SCREAMING_SNAKE_CASE_ ).eval() UpperCamelCase : Optional[int] = self.default_image_processor UpperCamelCase : Any = image_processor( [np.zeros((3, 800, 1333) ), np.zeros((3, 800, 1333) )], segmentation_maps=[np.zeros((384, 384) ).astype(np.floataa ), np.zeros((384, 384) ).astype(np.floataa )], return_tensors='pt', ) UpperCamelCase : Dict = inputs['pixel_values'].to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = [el.to(SCREAMING_SNAKE_CASE_ ) for el in inputs['mask_labels']] UpperCamelCase : Optional[Any] = [el.to(SCREAMING_SNAKE_CASE_ ) for el in inputs['class_labels']] with torch.no_grad(): UpperCamelCase : Any = model(**SCREAMING_SNAKE_CASE_ ) self.assertTrue(outputs.loss is not None )
103
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 ViTImageProcessor class lowerCAmelCase_ ( unittest.TestCase ): def __init__( self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_=13, SCREAMING_SNAKE_CASE_=3, SCREAMING_SNAKE_CASE_=224, SCREAMING_SNAKE_CASE_=30, SCREAMING_SNAKE_CASE_=400, SCREAMING_SNAKE_CASE_=True, SCREAMING_SNAKE_CASE_=None, SCREAMING_SNAKE_CASE_=True, SCREAMING_SNAKE_CASE_=[0.5, 0.5, 0.5], SCREAMING_SNAKE_CASE_=[0.5, 0.5, 0.5], ) -> List[str]: UpperCamelCase : Optional[int] = size if size is not None else {'height': 18, 'width': 18} UpperCamelCase : List[Any] = parent UpperCamelCase : List[Any] = batch_size UpperCamelCase : int = num_channels UpperCamelCase : int = image_size UpperCamelCase : List[Any] = min_resolution UpperCamelCase : int = max_resolution UpperCamelCase : Any = do_resize UpperCamelCase : Optional[int] = size UpperCamelCase : List[str] = do_normalize UpperCamelCase : Optional[Any] = image_mean UpperCamelCase : Tuple = image_std def snake_case_ ( self ) -> List[Any]: return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class lowerCAmelCase_ ( a__ , unittest.TestCase ): UpperCAmelCase__ : Optional[Any] = ViTImageProcessor if is_vision_available() else None def snake_case_ ( self ) -> Any: UpperCamelCase : Dict = EfficientFormerImageProcessorTester(self ) @property def snake_case_ ( self ) -> List[Any]: return self.image_proc_tester.prepare_image_processor_dict() def snake_case_ ( self ) -> Optional[int]: UpperCamelCase : Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_, 'image_mean' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_, 'image_std' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_, 'do_normalize' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_, 'do_resize' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_, 'size' ) ) def snake_case_ ( self ) -> Any: pass def snake_case_ ( self ) -> int: # Initialize image_processor UpperCamelCase : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images UpperCamelCase : List[str] = prepare_image_inputs(self.image_proc_tester, equal_resolution=SCREAMING_SNAKE_CASE_ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE_, Image.Image ) # Test not batched input UpperCamelCase : str = image_processor(image_inputs[0], return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['height'], self.image_proc_tester.size['width'], ), ) # Test batched UpperCamelCase : Optional[Any] = image_processor(SCREAMING_SNAKE_CASE_, return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['height'], self.image_proc_tester.size['width'], ), ) def snake_case_ ( self ) -> str: # Initialize image_processor UpperCamelCase : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors UpperCamelCase : Union[str, Any] = prepare_image_inputs(self.image_proc_tester, equal_resolution=SCREAMING_SNAKE_CASE_, numpify=SCREAMING_SNAKE_CASE_ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE_, np.ndarray ) # Test not batched input UpperCamelCase : Dict = image_processor(image_inputs[0], return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['height'], self.image_proc_tester.size['width'], ), ) # Test batched UpperCamelCase : Dict = image_processor(SCREAMING_SNAKE_CASE_, return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['height'], self.image_proc_tester.size['width'], ), ) def snake_case_ ( self ) -> Tuple: # Initialize image_processor UpperCamelCase : Any = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors UpperCamelCase : int = prepare_image_inputs(self.image_proc_tester, equal_resolution=SCREAMING_SNAKE_CASE_, torchify=SCREAMING_SNAKE_CASE_ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE_, torch.Tensor ) # Test not batched input UpperCamelCase : Optional[int] = image_processor(image_inputs[0], return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['height'], self.image_proc_tester.size['width'], ), ) # Test batched UpperCamelCase : int = image_processor(SCREAMING_SNAKE_CASE_, return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['height'], self.image_proc_tester.size['width'], ), )
103
1
import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def __lowerCAmelCase ( a__ ) -> Any: monkeypatch.setattr('''datasets.utils.deprecation_utils._emitted_deprecation_warnings''' , set() ) @pytest.fixture def __lowerCAmelCase ( a__ ) -> List[str]: class __A: def __init__( self , _snake_case ) -> Dict: '''simple docstring''' __a = metric_id class __A: snake_case_ = [MetricMock(a ) for metric_id in ['''accuracy''', '''mse''', '''precision''', '''codeparrot/apps_metric''']] def SCREAMING_SNAKE_CASE_ ( self ) -> str: '''simple docstring''' return self._metrics monkeypatch.setattr('''datasets.inspect.huggingface_hub''' , HfhMock() ) @pytest.mark.parametrize( '''func, args''' , [(load_metric, ('''metrics/mse''',)), (list_metrics, ()), (inspect_metric, ('''metrics/mse''', '''tmp_path'''))] ) def __lowerCAmelCase ( a__ , a__ , a__ , a__ , a__ ) -> Optional[int]: if "tmp_path" in args: __a = tuple(arg if arg != '''tmp_path''' else tmp_path for arg in args ) with pytest.warns(a__ , match='''https://huggingface.co/docs/evaluate''' ): func(*a__ )
6
'''simple docstring''' from statistics import mean, stdev def UpperCamelCase_( snake_case : list , snake_case : int = 3 ): '''simple docstring''' snake_case_ = min(snake_case ) snake_case_ = max(snake_case ) # normalize data return [round((x - x_min) / (x_max - x_min) , snake_case ) for x in data] def UpperCamelCase_( snake_case : list , snake_case : int = 3 ): '''simple docstring''' snake_case_ = mean(snake_case ) snake_case_ = stdev(snake_case ) # standardize data return [round((x - mu) / (sigma) , snake_case ) for x in data]
85
0
def __snake_case ( _lowerCAmelCase : int ) -> int: if a < 0: raise ValueError("Input value must be a positive integer" ) elif isinstance(_lowerCAmelCase , _lowerCAmelCase ): raise TypeError("Input value must be a 'int' type" ) return bin(_lowerCAmelCase ).count("1" ) if __name__ == "__main__": import doctest doctest.testmod()
70
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowerCAmelCase : Any = { '''configuration_clap''': [ '''CLAP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ClapAudioConfig''', '''ClapConfig''', '''ClapTextConfig''', ], '''processing_clap''': ['''ClapProcessor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase : Tuple = [ '''CLAP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ClapModel''', '''ClapPreTrainedModel''', '''ClapTextModel''', '''ClapTextModelWithProjection''', '''ClapAudioModel''', '''ClapAudioModelWithProjection''', ] _lowerCAmelCase : int = ['''ClapFeatureExtractor'''] if TYPE_CHECKING: from .configuration_clap import ( CLAP_PRETRAINED_MODEL_ARCHIVE_LIST, ClapAudioConfig, ClapConfig, ClapTextConfig, ) from .processing_clap import ClapProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_clap import ClapFeatureExtractor from .modeling_clap import ( CLAP_PRETRAINED_MODEL_ARCHIVE_LIST, ClapAudioModel, ClapAudioModelWithProjection, ClapModel, ClapPreTrainedModel, ClapTextModel, ClapTextModelWithProjection, ) else: import sys _lowerCAmelCase : Union[str, Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
70
1
import tempfile import unittest import numpy as np from diffusers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionPipeline, PNDMScheduler, ) from diffusers.utils.testing_utils import is_onnx_available, nightly, require_onnxruntime, require_torch_gpu from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class __SCREAMING_SNAKE_CASE( UpperCAmelCase__ , unittest.TestCase ): _UpperCAmelCase = """hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline""" def lowerCAmelCase_ ( self: List[str] , UpperCamelCase: str=0 ) -> int: snake_case__ = np.random.RandomState(snake_case_ ) snake_case__ = { 'prompt': 'A painting of a squirrel eating a burger', 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def lowerCAmelCase_ ( self: Optional[int] ) -> Optional[Any]: snake_case__ = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) pipe.set_progress_bar_config(disable=snake_case_ ) snake_case__ = self.get_dummy_inputs() snake_case__ = pipe(**snake_case_ ).images snake_case__ = image[0, -3:, -3:, -1] assert image.shape == (1, 1_28, 1_28, 3) snake_case__ = np.array([0.65_072, 0.58_492, 0.48_219, 0.55_521, 0.53_180, 0.55_939, 0.50_697, 0.39_800, 0.46_455] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def lowerCAmelCase_ ( self: Dict ) -> Tuple: snake_case__ = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) snake_case__ = PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=snake_case_ ) pipe.set_progress_bar_config(disable=snake_case_ ) snake_case__ = self.get_dummy_inputs() snake_case__ = pipe(**snake_case_ ).images snake_case__ = image[0, -3:, -3:, -1] assert image.shape == (1, 1_28, 1_28, 3) snake_case__ = np.array([0.65_863, 0.59_425, 0.49_326, 0.56_313, 0.53_875, 0.56_627, 0.51_065, 0.39_777, 0.46_330] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def lowerCAmelCase_ ( self: Any ) -> Dict: snake_case__ = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) snake_case__ = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=snake_case_ ) snake_case__ = self.get_dummy_inputs() snake_case__ = pipe(**snake_case_ ).images snake_case__ = image[0, -3:, -3:, -1] assert image.shape == (1, 1_28, 1_28, 3) snake_case__ = np.array([0.53_755, 0.60_786, 0.47_402, 0.49_488, 0.51_869, 0.49_819, 0.47_985, 0.38_957, 0.44_279] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def lowerCAmelCase_ ( self: Optional[Any] ) -> Dict: snake_case__ = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) snake_case__ = EulerDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=snake_case_ ) snake_case__ = self.get_dummy_inputs() snake_case__ = pipe(**snake_case_ ).images snake_case__ = image[0, -3:, -3:, -1] assert image.shape == (1, 1_28, 1_28, 3) snake_case__ = np.array([0.53_755, 0.60_786, 0.47_402, 0.49_488, 0.51_869, 0.49_819, 0.47_985, 0.38_957, 0.44_279] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def lowerCAmelCase_ ( self: str ) -> Union[str, Any]: snake_case__ = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) snake_case__ = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=snake_case_ ) snake_case__ = self.get_dummy_inputs() snake_case__ = pipe(**snake_case_ ).images snake_case__ = image[0, -3:, -3:, -1] assert image.shape == (1, 1_28, 1_28, 3) snake_case__ = np.array([0.53_817, 0.60_812, 0.47_384, 0.49_530, 0.51_894, 0.49_814, 0.47_984, 0.38_958, 0.44_271] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def lowerCAmelCase_ ( self: Dict ) -> Tuple: snake_case__ = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) snake_case__ = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=snake_case_ ) snake_case__ = self.get_dummy_inputs() snake_case__ = pipe(**snake_case_ ).images snake_case__ = image[0, -3:, -3:, -1] assert image.shape == (1, 1_28, 1_28, 3) snake_case__ = np.array([0.53_895, 0.60_808, 0.47_933, 0.49_608, 0.51_886, 0.49_950, 0.48_053, 0.38_957, 0.44_200] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def lowerCAmelCase_ ( self: Union[str, Any] ) -> List[str]: snake_case__ = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) pipe.set_progress_bar_config(disable=snake_case_ ) snake_case__ = self.get_dummy_inputs() snake_case__ = 3 * [inputs['prompt']] # forward snake_case__ = pipe(**snake_case_ ) snake_case__ = output.images[0, -3:, -3:, -1] snake_case__ = self.get_dummy_inputs() snake_case__ = 3 * [inputs.pop('prompt' )] snake_case__ = pipe.tokenizer( snake_case_ , padding='max_length' , max_length=pipe.tokenizer.model_max_length , truncation=snake_case_ , return_tensors='np' , ) snake_case__ = text_inputs['input_ids'] snake_case__ = pipe.text_encoder(input_ids=text_inputs.astype(np.intaa ) )[0] snake_case__ = prompt_embeds # forward snake_case__ = pipe(**snake_case_ ) snake_case__ = output.images[0, -3:, -3:, -1] assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1e-4 def lowerCAmelCase_ ( self: Optional[Any] ) -> Any: snake_case__ = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) pipe.set_progress_bar_config(disable=snake_case_ ) snake_case__ = self.get_dummy_inputs() snake_case__ = 3 * ['this is a negative prompt'] snake_case__ = negative_prompt snake_case__ = 3 * [inputs['prompt']] # forward snake_case__ = pipe(**snake_case_ ) snake_case__ = output.images[0, -3:, -3:, -1] snake_case__ = self.get_dummy_inputs() snake_case__ = 3 * [inputs.pop('prompt' )] snake_case__ = [] for p in [prompt, negative_prompt]: snake_case__ = pipe.tokenizer( snake_case_ , padding='max_length' , max_length=pipe.tokenizer.model_max_length , truncation=snake_case_ , return_tensors='np' , ) snake_case__ = text_inputs['input_ids'] embeds.append(pipe.text_encoder(input_ids=text_inputs.astype(np.intaa ) )[0] ) snake_case__ = embeds # forward snake_case__ = pipe(**snake_case_ ) snake_case__ = output.images[0, -3:, -3:, -1] assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1e-4 @nightly @require_onnxruntime @require_torch_gpu class __SCREAMING_SNAKE_CASE( unittest.TestCase ): @property def lowerCAmelCase_ ( self: Any ) -> Optional[int]: return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def lowerCAmelCase_ ( self: Optional[int] ) -> Any: snake_case__ = ort.SessionOptions() snake_case__ = False return options def lowerCAmelCase_ ( self: Union[str, Any] ) -> List[Any]: snake_case__ = OnnxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='onnx' , safety_checker=snake_case_ , feature_extractor=snake_case_ , provider=self.gpu_provider , sess_options=self.gpu_options , ) sd_pipe.set_progress_bar_config(disable=snake_case_ ) snake_case__ = 'A painting of a squirrel eating a burger' np.random.seed(0 ) snake_case__ = sd_pipe([prompt] , guidance_scale=6.0 , num_inference_steps=10 , output_type='np' ) snake_case__ = output.images snake_case__ = image[0, -3:, -3:, -1] assert image.shape == (1, 5_12, 5_12, 3) snake_case__ = np.array([0.0_452, 0.0_390, 0.0_087, 0.0_350, 0.0_617, 0.0_364, 0.0_544, 0.0_523, 0.0_720] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def lowerCAmelCase_ ( self: int ) -> str: snake_case__ = DDIMScheduler.from_pretrained( 'runwayml/stable-diffusion-v1-5' , subfolder='scheduler' , revision='onnx' ) snake_case__ = OnnxStableDiffusionPipeline.from_pretrained( 'runwayml/stable-diffusion-v1-5' , revision='onnx' , scheduler=snake_case_ , safety_checker=snake_case_ , feature_extractor=snake_case_ , provider=self.gpu_provider , sess_options=self.gpu_options , ) sd_pipe.set_progress_bar_config(disable=snake_case_ ) snake_case__ = 'open neural network exchange' snake_case__ = np.random.RandomState(0 ) snake_case__ = sd_pipe([prompt] , guidance_scale=7.5 , num_inference_steps=10 , generator=snake_case_ , output_type='np' ) snake_case__ = output.images snake_case__ = image[0, -3:, -3:, -1] assert image.shape == (1, 5_12, 5_12, 3) snake_case__ = np.array([0.2_867, 0.1_974, 0.1_481, 0.7_294, 0.7_251, 0.6_667, 0.4_194, 0.5_642, 0.6_486] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def lowerCAmelCase_ ( self: Optional[int] ) -> List[str]: snake_case__ = LMSDiscreteScheduler.from_pretrained( 'runwayml/stable-diffusion-v1-5' , subfolder='scheduler' , revision='onnx' ) snake_case__ = OnnxStableDiffusionPipeline.from_pretrained( 'runwayml/stable-diffusion-v1-5' , revision='onnx' , scheduler=snake_case_ , safety_checker=snake_case_ , feature_extractor=snake_case_ , provider=self.gpu_provider , sess_options=self.gpu_options , ) sd_pipe.set_progress_bar_config(disable=snake_case_ ) snake_case__ = 'open neural network exchange' snake_case__ = np.random.RandomState(0 ) snake_case__ = sd_pipe([prompt] , guidance_scale=7.5 , num_inference_steps=10 , generator=snake_case_ , output_type='np' ) snake_case__ = output.images snake_case__ = image[0, -3:, -3:, -1] assert image.shape == (1, 5_12, 5_12, 3) snake_case__ = np.array([0.2_306, 0.1_959, 0.1_593, 0.6_549, 0.6_394, 0.5_408, 0.5_065, 0.6_010, 0.6_161] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def lowerCAmelCase_ ( self: int ) -> List[str]: snake_case__ = 0 def test_callback_fn(UpperCamelCase: Optional[Any] , UpperCamelCase: Any , UpperCamelCase: List[str] ) -> None: snake_case__ = True nonlocal number_of_steps number_of_steps += 1 if step == 0: assert latents.shape == (1, 4, 64, 64) snake_case__ = latents[0, -3:, -3:, -1] snake_case__ = np.array( [-0.6_772, -0.3_835, -1.2_456, 0.1_905, -1.0_974, 0.6_967, -1.9_353, 0.0_178, 1.0_167] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 1e-3 elif step == 5: assert latents.shape == (1, 4, 64, 64) snake_case__ = latents[0, -3:, -3:, -1] snake_case__ = np.array( [-0.3_351, 0.2_241, -0.1_837, -0.2_325, -0.6_577, 0.3_393, -0.0_241, 0.5_899, 1.3_875] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 1e-3 snake_case__ = False snake_case__ = OnnxStableDiffusionPipeline.from_pretrained( 'runwayml/stable-diffusion-v1-5' , revision='onnx' , safety_checker=snake_case_ , feature_extractor=snake_case_ , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=snake_case_ ) snake_case__ = 'Andromeda galaxy in a bottle' snake_case__ = np.random.RandomState(0 ) pipe( prompt=snake_case_ , num_inference_steps=5 , guidance_scale=7.5 , generator=snake_case_ , callback=snake_case_ , callback_steps=1 , ) assert test_callback_fn.has_been_called assert number_of_steps == 6 def lowerCAmelCase_ ( self: str ) -> Any: snake_case__ = OnnxStableDiffusionPipeline.from_pretrained( 'runwayml/stable-diffusion-v1-5' , revision='onnx' , safety_checker=snake_case_ , feature_extractor=snake_case_ , provider=self.gpu_provider , sess_options=self.gpu_options , ) assert isinstance(snake_case_ , snake_case_ ) assert pipe.safety_checker is None snake_case__ = pipe('example prompt' , num_inference_steps=2 ).images[0] assert image is not None # check that there's no error when saving a pipeline with one of the models being None with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(snake_case_ ) snake_case__ = OnnxStableDiffusionPipeline.from_pretrained(snake_case_ ) # sanity check that the pipeline still works assert pipe.safety_checker is None snake_case__ = pipe('example prompt' , num_inference_steps=2 ).images[0] assert image is not None
307
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available lowerCamelCase_ : int = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : Tuple = ['MLukeTokenizer'] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mluke import MLukeTokenizer else: import sys lowerCamelCase_ : List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
286
0
"""simple docstring""" import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DeiTConfig, DeiTForImageClassificationWithTeacher, DeiTImageProcessor from transformers.utils import logging logging.set_verbosity_info() a : Optional[int] = logging.get_logger(__name__) def lowercase__(A , A=False ) ->List[str]: """simple docstring""" lowercase__ : List[Any]= [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f'''blocks.{i}.norm1.weight''', f'''deit.encoder.layer.{i}.layernorm_before.weight''') ) rename_keys.append((f'''blocks.{i}.norm1.bias''', f'''deit.encoder.layer.{i}.layernorm_before.bias''') ) rename_keys.append((f'''blocks.{i}.attn.proj.weight''', f'''deit.encoder.layer.{i}.attention.output.dense.weight''') ) rename_keys.append((f'''blocks.{i}.attn.proj.bias''', f'''deit.encoder.layer.{i}.attention.output.dense.bias''') ) rename_keys.append((f'''blocks.{i}.norm2.weight''', f'''deit.encoder.layer.{i}.layernorm_after.weight''') ) rename_keys.append((f'''blocks.{i}.norm2.bias''', f'''deit.encoder.layer.{i}.layernorm_after.bias''') ) rename_keys.append((f'''blocks.{i}.mlp.fc1.weight''', f'''deit.encoder.layer.{i}.intermediate.dense.weight''') ) rename_keys.append((f'''blocks.{i}.mlp.fc1.bias''', f'''deit.encoder.layer.{i}.intermediate.dense.bias''') ) rename_keys.append((f'''blocks.{i}.mlp.fc2.weight''', f'''deit.encoder.layer.{i}.output.dense.weight''') ) rename_keys.append((f'''blocks.{i}.mlp.fc2.bias''', f'''deit.encoder.layer.{i}.output.dense.bias''') ) # projection layer + position embeddings rename_keys.extend( [ ("cls_token", "deit.embeddings.cls_token"), ("dist_token", "deit.embeddings.distillation_token"), ("patch_embed.proj.weight", "deit.embeddings.patch_embeddings.projection.weight"), ("patch_embed.proj.bias", "deit.embeddings.patch_embeddings.projection.bias"), ("pos_embed", "deit.embeddings.position_embeddings"), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ("norm.weight", "layernorm.weight"), ("norm.bias", "layernorm.bias"), ("pre_logits.fc.weight", "pooler.dense.weight"), ("pre_logits.fc.bias", "pooler.dense.bias"), ] ) # if just the base model, we should remove "deit" from all keys that start with "deit" lowercase__ : Any= [(pair[0], pair[1][4:]) if pair[1].startswith("deit" ) else pair for pair in rename_keys] else: # layernorm + classification heads rename_keys.extend( [ ("norm.weight", "deit.layernorm.weight"), ("norm.bias", "deit.layernorm.bias"), ("head.weight", "cls_classifier.weight"), ("head.bias", "cls_classifier.bias"), ("head_dist.weight", "distillation_classifier.weight"), ("head_dist.bias", "distillation_classifier.bias"), ] ) return rename_keys def lowercase__(A , A , A=False ) ->Union[str, Any]: """simple docstring""" for i in range(config.num_hidden_layers ): if base_model: lowercase__ : Any= "" else: lowercase__ : List[str]= "deit." # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) lowercase__ : Optional[Any]= state_dict.pop(f'''blocks.{i}.attn.qkv.weight''' ) lowercase__ : Tuple= state_dict.pop(f'''blocks.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict lowercase__ : Optional[int]= in_proj_weight[ : config.hidden_size, : ] lowercase__ : List[Any]= in_proj_bias[: config.hidden_size] lowercase__ : List[str]= in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] lowercase__ : Optional[int]= in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] lowercase__ : str= in_proj_weight[ -config.hidden_size :, : ] lowercase__ : Optional[Any]= in_proj_bias[-config.hidden_size :] def lowercase__(A , A , A ) ->Tuple: """simple docstring""" lowercase__ : str= dct.pop(A ) lowercase__ : Dict= val def lowercase__() ->Tuple: """simple docstring""" lowercase__ : Any= "http://images.cocodataset.org/val2017/000000039769.jpg" lowercase__ : str= Image.open(requests.get(A , stream=A ).raw ) return im @torch.no_grad() def lowercase__(A , A ) ->List[Any]: """simple docstring""" lowercase__ : Union[str, Any]= DeiTConfig() # all deit models have fine-tuned heads lowercase__ : List[str]= False # dataset (fine-tuned on ImageNet 2012), patch_size and image_size lowercase__ : Union[str, Any]= 1_000 lowercase__ : Optional[int]= "huggingface/label-files" lowercase__ : List[Any]= "imagenet-1k-id2label.json" lowercase__ : Optional[int]= json.load(open(hf_hub_download(A , A , repo_type="dataset" ) , "r" ) ) lowercase__ : str= {int(A ): v for k, v in idalabel.items()} lowercase__ : int= idalabel lowercase__ : Tuple= {v: k for k, v in idalabel.items()} lowercase__ : Any= int(deit_name[-6:-4] ) lowercase__ : Any= int(deit_name[-3:] ) # size of the architecture if deit_name[9:].startswith("tiny" ): lowercase__ : Optional[int]= 192 lowercase__ : Dict= 768 lowercase__ : List[str]= 12 lowercase__ : Tuple= 3 elif deit_name[9:].startswith("small" ): lowercase__ : Dict= 384 lowercase__ : int= 1_536 lowercase__ : List[Any]= 12 lowercase__ : List[Any]= 6 if deit_name[9:].startswith("base" ): pass elif deit_name[4:].startswith("large" ): lowercase__ : Tuple= 1_024 lowercase__ : Dict= 4_096 lowercase__ : List[str]= 24 lowercase__ : Tuple= 16 # load original model from timm lowercase__ : Optional[Any]= timm.create_model(A , pretrained=A ) timm_model.eval() # load state_dict of original model, remove and rename some keys lowercase__ : Optional[int]= timm_model.state_dict() lowercase__ : int= create_rename_keys(A , A ) for src, dest in rename_keys: rename_key(A , A , A ) read_in_q_k_v(A , A , A ) # load HuggingFace model lowercase__ : Dict= DeiTForImageClassificationWithTeacher(A ).eval() model.load_state_dict(A ) # Check outputs on an image, prepared by DeiTImageProcessor lowercase__ : Any= int( (256 / 224) * config.image_size ) # to maintain same ratio w.r.t. 224 images, see https://github.com/facebookresearch/deit/blob/ab5715372db8c6cad5740714b2216d55aeae052e/datasets.py#L103 lowercase__ : List[Any]= DeiTImageProcessor(size=A , crop_size=config.image_size ) lowercase__ : List[Any]= image_processor(images=prepare_img() , return_tensors="pt" ) lowercase__ : Dict= encoding["pixel_values"] lowercase__ : Any= model(A ) lowercase__ : Dict= timm_model(A ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(A , outputs.logits , atol=1e-3 ) Path(A ).mkdir(exist_ok=A ) print(f'''Saving model {deit_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(A ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(A ) if __name__ == "__main__": a : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--deit_name""", default="""vit_deit_base_distilled_patch16_224""", type=str, help="""Name of the DeiT timm model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) a : List[Any] = parser.parse_args() convert_deit_checkpoint(args.deit_name, args.pytorch_dump_folder_path)
150
"""simple docstring""" import json import os from functools import lru_cache from typing import Dict, List, Optional, Tuple, Union import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...tokenization_utils_base import BatchEncoding, EncodedInput from ...utils import PaddingStrategy, logging a : Dict = logging.get_logger(__name__) a : Optional[Any] = {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt"""} # See all LED models at https://huggingface.co/models?filter=LED a : List[str] = { """vocab_file""": { """allenai/led-base-16384""": """https://huggingface.co/allenai/led-base-16384/resolve/main/vocab.json""", }, """merges_file""": { """allenai/led-base-16384""": """https://huggingface.co/allenai/led-base-16384/resolve/main/merges.txt""", }, """tokenizer_file""": { """allenai/led-base-16384""": """https://huggingface.co/allenai/led-base-16384/resolve/main/tokenizer.json""", }, } a : Dict = { """allenai/led-base-16384""": 16384, } @lru_cache() # Copied from transformers.models.bart.tokenization_bart.bytes_to_unicode def lowercase__() ->List[Any]: """simple docstring""" lowercase__ : Optional[int]= ( list(range(ord("!" ) , ord("~" ) + 1 ) ) + list(range(ord("¡" ) , ord("¬" ) + 1 ) ) + list(range(ord("®" ) , ord("ÿ" ) + 1 ) ) ) lowercase__ : str= bs[:] lowercase__ : List[str]= 0 for b in range(2**8 ): if b not in bs: bs.append(A ) cs.append(2**8 + n ) n += 1 lowercase__ : Union[str, Any]= [chr(A ) for n in cs] return dict(zip(A , A ) ) def lowercase__(A ) ->str: """simple docstring""" lowercase__ : Optional[int]= set() lowercase__ : Optional[int]= word[0] for char in word[1:]: pairs.add((prev_char, char) ) lowercase__ : Tuple= char return pairs class __UpperCAmelCase( SCREAMING_SNAKE_CASE__ ): """simple docstring""" __lowerCamelCase = VOCAB_FILES_NAMES __lowerCamelCase = PRETRAINED_VOCAB_FILES_MAP __lowerCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCamelCase = ["input_ids", "attention_mask"] def __init__( self , snake_case__ , snake_case__ , snake_case__="replace" , snake_case__="<s>" , snake_case__="</s>" , snake_case__="</s>" , snake_case__="<s>" , snake_case__="<unk>" , snake_case__="<pad>" , snake_case__="<mask>" , snake_case__=False , **snake_case__ , ): '''simple docstring''' lowercase__ : Dict= AddedToken(snake_case__ , lstrip=snake_case__ , rstrip=snake_case__ ) if isinstance(snake_case__ , snake_case__ ) else bos_token lowercase__ : Dict= AddedToken(snake_case__ , lstrip=snake_case__ , rstrip=snake_case__ ) if isinstance(snake_case__ , snake_case__ ) else eos_token lowercase__ : str= AddedToken(snake_case__ , lstrip=snake_case__ , rstrip=snake_case__ ) if isinstance(snake_case__ , snake_case__ ) else sep_token lowercase__ : Optional[Any]= AddedToken(snake_case__ , lstrip=snake_case__ , rstrip=snake_case__ ) if isinstance(snake_case__ , snake_case__ ) else cls_token lowercase__ : List[str]= AddedToken(snake_case__ , lstrip=snake_case__ , rstrip=snake_case__ ) if isinstance(snake_case__ , snake_case__ ) else unk_token lowercase__ : Any= AddedToken(snake_case__ , lstrip=snake_case__ , rstrip=snake_case__ ) if isinstance(snake_case__ , snake_case__ ) else pad_token # Mask token behave like a normal word, i.e. include the space before it lowercase__ : int= AddedToken(snake_case__ , lstrip=snake_case__ , rstrip=snake_case__ ) if isinstance(snake_case__ , snake_case__ ) else mask_token super().__init__( errors=snake_case__ , bos_token=snake_case__ , eos_token=snake_case__ , unk_token=snake_case__ , sep_token=snake_case__ , cls_token=snake_case__ , pad_token=snake_case__ , mask_token=snake_case__ , add_prefix_space=snake_case__ , **snake_case__ , ) with open(snake_case__ , encoding="utf-8" ) as vocab_handle: lowercase__ : int= json.load(snake_case__ ) lowercase__ : List[str]= {v: k for k, v in self.encoder.items()} lowercase__ : Dict= errors # how to handle errors in decoding lowercase__ : Optional[int]= bytes_to_unicode() lowercase__ : str= {v: k for k, v in self.byte_encoder.items()} with open(snake_case__ , encoding="utf-8" ) as merges_handle: lowercase__ : Tuple= merges_handle.read().split("\n" )[1:-1] lowercase__ : List[str]= [tuple(merge.split() ) for merge in bpe_merges] lowercase__ : int= dict(zip(snake_case__ , range(len(snake_case__ ) ) ) ) lowercase__ : Optional[int]= {} lowercase__ : Tuple= add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions lowercase__ : Optional[int]= re.compile(r"'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+" ) @property # Copied from transformers.models.bart.tokenization_bart.BartTokenizer.vocab_size def UpperCAmelCase_ ( self ): '''simple docstring''' return len(self.encoder ) def UpperCAmelCase_ ( self ): '''simple docstring''' return dict(self.encoder , **self.added_tokens_encoder ) def UpperCAmelCase_ ( self , snake_case__ ): '''simple docstring''' if token in self.cache: return self.cache[token] lowercase__ : Any= tuple(snake_case__ ) lowercase__ : Union[str, Any]= get_pairs(snake_case__ ) if not pairs: return token while True: lowercase__ : Union[str, Any]= min(snake_case__ , key=lambda snake_case__ : self.bpe_ranks.get(snake_case__ , float("inf" ) ) ) if bigram not in self.bpe_ranks: break lowercase__, lowercase__ : Dict= bigram lowercase__ : Optional[Any]= [] lowercase__ : Optional[int]= 0 while i < len(snake_case__ ): try: lowercase__ : Optional[int]= word.index(snake_case__ , snake_case__ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) lowercase__ : List[Any]= j if word[i] == first and i < len(snake_case__ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 lowercase__ : Optional[int]= tuple(snake_case__ ) lowercase__ : List[Any]= new_word if len(snake_case__ ) == 1: break else: lowercase__ : Tuple= get_pairs(snake_case__ ) lowercase__ : Tuple= " ".join(snake_case__ ) lowercase__ : List[str]= word return word def UpperCAmelCase_ ( self , snake_case__ ): '''simple docstring''' lowercase__ : Optional[int]= [] for token in re.findall(self.pat , snake_case__ ): lowercase__ : int= "".join( self.byte_encoder[b] for b in token.encode("utf-8" ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(snake_case__ ).split(" " ) ) return bpe_tokens def UpperCAmelCase_ ( self , snake_case__ ): '''simple docstring''' return self.encoder.get(snake_case__ , self.encoder.get(self.unk_token ) ) def UpperCAmelCase_ ( self , snake_case__ ): '''simple docstring''' return self.decoder.get(snake_case__ ) def UpperCAmelCase_ ( self , snake_case__ ): '''simple docstring''' lowercase__ : Union[str, Any]= "".join(snake_case__ ) lowercase__ : Optional[int]= bytearray([self.byte_decoder[c] for c in text] ).decode("utf-8" , errors=self.errors ) return text def UpperCAmelCase_ ( self , snake_case__ , snake_case__ = None ): '''simple docstring''' if not os.path.isdir(snake_case__ ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return lowercase__ : Dict= os.path.join( snake_case__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) lowercase__ : Tuple= os.path.join( snake_case__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"] ) with open(snake_case__ , "w" , encoding="utf-8" ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=snake_case__ , ensure_ascii=snake_case__ ) + "\n" ) lowercase__ : Any= 0 with open(snake_case__ , "w" , encoding="utf-8" ) as writer: writer.write("#version: 0.2\n" ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda snake_case__ : kv[1] ): if index != token_index: logger.warning( F'''Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.''' " Please check that the tokenizer is not corrupted!" ) lowercase__ : Optional[Any]= token_index writer.write(" ".join(snake_case__ ) + "\n" ) index += 1 return vocab_file, merge_file def UpperCAmelCase_ ( self , snake_case__ , snake_case__ = None ): '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] lowercase__ : Any= [self.cls_token_id] lowercase__ : Dict= [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def UpperCAmelCase_ ( self , snake_case__ , snake_case__ = None , snake_case__ = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=snake_case__ , token_ids_a=snake_case__ , already_has_special_tokens=snake_case__ ) if token_ids_a is None: return [1] + ([0] * len(snake_case__ )) + [1] return [1] + ([0] * len(snake_case__ )) + [1, 1] + ([0] * len(snake_case__ )) + [1] def UpperCAmelCase_ ( self , snake_case__ , snake_case__ = None ): '''simple docstring''' lowercase__ : Tuple= [self.sep_token_id] lowercase__ : Optional[int]= [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def UpperCAmelCase_ ( self , snake_case__ , snake_case__=False , **snake_case__ ): '''simple docstring''' lowercase__ : str= kwargs.pop("add_prefix_space" , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(snake_case__ ) > 0 and not text[0].isspace()): lowercase__ : List[Any]= " " + text return (text, kwargs) def UpperCAmelCase_ ( self , snake_case__ , snake_case__ = None , snake_case__ = PaddingStrategy.DO_NOT_PAD , snake_case__ = None , snake_case__ = None , ): '''simple docstring''' lowercase__ : List[str]= super()._pad( encoded_inputs=snake_case__ , max_length=snake_case__ , padding_strategy=snake_case__ , pad_to_multiple_of=snake_case__ , return_attention_mask=snake_case__ , ) # Load from model defaults if return_attention_mask is None: lowercase__ : Tuple= "attention_mask" in self.model_input_names if return_attention_mask and "global_attention_mask" in encoded_inputs: lowercase__ : Any= encoded_inputs[self.model_input_names[0]] # `global_attention_mask` need to have the same length as other (sequential) inputs. lowercase__ : int= len(encoded_inputs["global_attention_mask"] ) != len(snake_case__ ) if needs_to_be_padded: lowercase__ : Dict= len(snake_case__ ) - len(encoded_inputs["global_attention_mask"] ) if self.padding_side == "right": # Use `-1` since `0` in `global_attention_mask` means `local attention` instead of `not to attend` lowercase__ : Tuple= ( encoded_inputs["global_attention_mask"] + [-1] * difference ) elif self.padding_side == "left": lowercase__ : Any= [-1] * difference + encoded_inputs[ "global_attention_mask" ] else: raise ValueError("Invalid padding strategy:" + str(self.padding_side ) ) return encoded_inputs
150
1
'''simple docstring''' import hashlib import unittest from transformers import MODEL_FOR_DEPTH_ESTIMATION_MAPPING, is_torch_available, is_vision_available from transformers.pipelines import DepthEstimationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_torch_available(): import torch if is_vision_available(): from PIL import Image else: class A_ : '''simple docstring''' @staticmethod def UpperCAmelCase_ ( *lowercase_ : Any , **lowercase_ : str ) -> Optional[Any]: pass def UpperCamelCase( UpperCAmelCase_ ): UpperCAmelCase : str = hashlib.mda(image.tobytes() ) return m.hexdigest() @is_pipeline_test @require_vision @require_timm @require_torch class A_ ( unittest.TestCase ): '''simple docstring''' UpperCAmelCase_ : Dict = MODEL_FOR_DEPTH_ESTIMATION_MAPPING def UpperCAmelCase_ ( self : Optional[Any] , lowercase_ : Dict , lowercase_ : str , lowercase_ : List[str] ) -> Dict: UpperCAmelCase : int = DepthEstimationPipeline(model=lowercase_ , image_processor=lowercase_ ) return depth_estimator, [ "./tests/fixtures/tests_samples/COCO/000000039769.png", "./tests/fixtures/tests_samples/COCO/000000039769.png", ] def UpperCAmelCase_ ( self : Tuple , lowercase_ : Any , lowercase_ : Optional[int] ) -> Dict: UpperCAmelCase : List[str] = depth_estimator('./tests/fixtures/tests_samples/COCO/000000039769.png' ) self.assertEqual({'predicted_depth': ANY(torch.Tensor ), 'depth': ANY(Image.Image )} , lowercase_ ) import datasets UpperCAmelCase : Tuple = datasets.load_dataset('hf-internal-testing/fixtures_image_utils' , 'image' , split='test' ) UpperCAmelCase : Any = depth_estimator( [ Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ), 'http://images.cocodataset.org/val2017/000000039769.jpg', # RGBA dataset[0]['file'], # LA dataset[1]['file'], # L dataset[2]['file'], ] ) self.assertEqual( [ {'predicted_depth': ANY(torch.Tensor ), 'depth': ANY(Image.Image )}, {'predicted_depth': ANY(torch.Tensor ), 'depth': ANY(Image.Image )}, {'predicted_depth': ANY(torch.Tensor ), 'depth': ANY(Image.Image )}, {'predicted_depth': ANY(torch.Tensor ), 'depth': ANY(Image.Image )}, {'predicted_depth': ANY(torch.Tensor ), 'depth': ANY(Image.Image )}, ] , lowercase_ , ) @require_tf @unittest.skip('Depth estimation is not implemented in TF' ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Any: pass @slow @require_torch def UpperCAmelCase_ ( self : Optional[int] ) -> str: UpperCAmelCase : Tuple = 'Intel/dpt-large' UpperCAmelCase : List[Any] = pipeline('depth-estimation' , model=lowercase_ ) UpperCAmelCase : Union[str, Any] = depth_estimator('http://images.cocodataset.org/val2017/000000039769.jpg' ) UpperCAmelCase : str = hashimage(outputs['depth'] ) # This seems flaky. # self.assertEqual(outputs["depth"], "1a39394e282e9f3b0741a90b9f108977") self.assertEqual(nested_simplify(outputs['predicted_depth'].max().item() ) , 29.304 ) self.assertEqual(nested_simplify(outputs['predicted_depth'].min().item() ) , 2.662 ) @require_torch def UpperCAmelCase_ ( self : int ) -> Optional[int]: # This is highly irregular to have no small tests. self.skipTest('There is not hf-internal-testing tiny model for either GLPN nor DPT' )
151
'''simple docstring''' import copy from dataclasses import dataclass from pathlib import Path from typing import Dict, Optional, Union @dataclass class A_ : '''simple docstring''' UpperCAmelCase_ : Optional[Union[str, Path]] = None UpperCAmelCase_ : bool = False UpperCAmelCase_ : bool = False UpperCAmelCase_ : bool = False UpperCAmelCase_ : Optional[Dict] = None UpperCAmelCase_ : Optional[str] = None UpperCAmelCase_ : bool = False UpperCAmelCase_ : bool = False UpperCAmelCase_ : bool = False UpperCAmelCase_ : bool = True UpperCAmelCase_ : Optional[int] = None UpperCAmelCase_ : int = 1 UpperCAmelCase_ : Optional[Union[str, bool]] = None UpperCAmelCase_ : bool = False UpperCAmelCase_ : Optional[Dict] = None UpperCAmelCase_ : Optional[str] = None def UpperCAmelCase_ ( self : Tuple ) -> "DownloadConfig": return self.__class__(**{k: copy.deepcopy(lowercase_ ) for k, v in self.__dict__.items()} )
151
1
'''simple docstring''' # Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available SCREAMING_SNAKE_CASE__ = { 'configuration_vivit': ['VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'VivitConfig'], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ = ['VivitImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ = [ 'VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'VivitModel', 'VivitPreTrainedModel', 'VivitForVideoClassification', ] if TYPE_CHECKING: from .configuration_vivit import VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, VivitConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_vivit import VivitImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vivit import ( VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST, VivitForVideoClassification, VivitModel, VivitPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
357
'''simple docstring''' from typing import Dict, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import flip_channel_order, resize, to_channel_dimension_format, to_pil_image from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_pytesseract_available, is_vision_available, logging, requires_backends if is_vision_available(): import PIL # soft dependency if is_pytesseract_available(): import pytesseract SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase )-> int: return [ int(1000 * (box[0] / width) ), int(1000 * (box[1] / height) ), int(1000 * (box[2] / width) ), int(1000 * (box[3] / height) ), ] def lowercase__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = None )-> Dict: UpperCamelCase = tesseract_config if tesseract_config is not None else """""" # apply OCR UpperCamelCase = to_pil_image(__UpperCamelCase ) UpperCamelCase ,UpperCamelCase = pil_image.size UpperCamelCase = pytesseract.image_to_data(__UpperCamelCase , lang=__UpperCamelCase , output_type="""dict""" , config=__UpperCamelCase ) UpperCamelCase ,UpperCamelCase ,UpperCamelCase ,UpperCamelCase ,UpperCamelCase = data["""text"""], data["""left"""], data["""top"""], data["""width"""], data["""height"""] # filter empty words and corresponding coordinates UpperCamelCase = [idx for idx, word in enumerate(__UpperCamelCase ) if not word.strip()] UpperCamelCase = [word for idx, word in enumerate(__UpperCamelCase ) if idx not in irrelevant_indices] UpperCamelCase = [coord for idx, coord in enumerate(__UpperCamelCase ) if idx not in irrelevant_indices] UpperCamelCase = [coord for idx, coord in enumerate(__UpperCamelCase ) if idx not in irrelevant_indices] UpperCamelCase = [coord for idx, coord in enumerate(__UpperCamelCase ) if idx not in irrelevant_indices] UpperCamelCase = [coord for idx, coord in enumerate(__UpperCamelCase ) if idx not in irrelevant_indices] # turn coordinates into (left, top, left+width, top+height) format UpperCamelCase = [] for x, y, w, h in zip(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ): UpperCamelCase = [x, y, x + w, y + h] actual_boxes.append(__UpperCamelCase ) # finally, normalize the bounding boxes UpperCamelCase = [] for box in actual_boxes: normalized_boxes.append(normalize_box(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) ) assert len(__UpperCamelCase ) == len(__UpperCamelCase ), "Not as many words as there are bounding boxes" return words, normalized_boxes class a_ ( lowerCamelCase ): lowercase = ["""pixel_values"""] def __init__( self , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = PILImageResampling.BILINEAR , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = "" , **_SCREAMING_SNAKE_CASE , ) -> None: """simple docstring""" super().__init__(**_SCREAMING_SNAKE_CASE ) UpperCamelCase = size if size is not None else {"""height""": 224, """width""": 224} UpperCamelCase = get_size_dict(_SCREAMING_SNAKE_CASE ) UpperCamelCase = do_resize UpperCamelCase = size UpperCamelCase = resample UpperCamelCase = apply_ocr UpperCamelCase = ocr_lang UpperCamelCase = tesseract_config def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = PILImageResampling.BILINEAR , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , ) -> np.ndarray: """simple docstring""" UpperCamelCase = get_size_dict(_SCREAMING_SNAKE_CASE ) if "height" not in size or "width" not in size: raise ValueError(F"The size dictionary must contain the keys 'height' and 'width'. Got {size.keys()}" ) UpperCamelCase = (size["""height"""], size["""width"""]) return resize(_SCREAMING_SNAKE_CASE , size=_SCREAMING_SNAKE_CASE , resample=_SCREAMING_SNAKE_CASE , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = ChannelDimension.FIRST , **_SCREAMING_SNAKE_CASE , ) -> PIL.Image.Image: """simple docstring""" UpperCamelCase = do_resize if do_resize is not None else self.do_resize UpperCamelCase = size if size is not None else self.size UpperCamelCase = get_size_dict(_SCREAMING_SNAKE_CASE ) UpperCamelCase = resample if resample is not None else self.resample UpperCamelCase = apply_ocr if apply_ocr is not None else self.apply_ocr UpperCamelCase = ocr_lang if ocr_lang is not None else self.ocr_lang UpperCamelCase = tesseract_config if tesseract_config is not None else self.tesseract_config UpperCamelCase = make_list_of_images(_SCREAMING_SNAKE_CASE ) if not valid_images(_SCREAMING_SNAKE_CASE ): 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.""" ) # All transformations expect numpy arrays. UpperCamelCase = [to_numpy_array(_SCREAMING_SNAKE_CASE ) for image in images] if apply_ocr: requires_backends(self , """pytesseract""" ) UpperCamelCase = [] UpperCamelCase = [] for image in images: UpperCamelCase ,UpperCamelCase = apply_tesseract(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) words_batch.append(_SCREAMING_SNAKE_CASE ) boxes_batch.append(_SCREAMING_SNAKE_CASE ) if do_resize: UpperCamelCase = [self.resize(image=_SCREAMING_SNAKE_CASE , size=_SCREAMING_SNAKE_CASE , resample=_SCREAMING_SNAKE_CASE ) for image in images] # flip color channels from RGB to BGR (as Detectron2 requires this) UpperCamelCase = [flip_channel_order(_SCREAMING_SNAKE_CASE ) for image in images] UpperCamelCase = [to_channel_dimension_format(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for image in images] UpperCamelCase = BatchFeature(data={"""pixel_values""": images} , tensor_type=_SCREAMING_SNAKE_CASE ) if apply_ocr: UpperCamelCase = words_batch UpperCamelCase = boxes_batch return data
183
0
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 ViTImageProcessor class __snake_case ( unittest.TestCase ): def __init__( self : int , A_ : Any , A_ : List[Any]=1_3 , A_ : Any=3 , A_ : List[str]=2_2_4 , A_ : Optional[Any]=3_0 , A_ : Optional[Any]=4_0_0 , A_ : Any=True , A_ : str=None , A_ : Tuple=True , A_ : str=[0.5, 0.5, 0.5] , A_ : Optional[int]=[0.5, 0.5, 0.5] , ): lowerCAmelCase_ : Optional[Any] = size if size is not None else {'''height''': 1_8, '''width''': 1_8} lowerCAmelCase_ : List[str] = parent lowerCAmelCase_ : str = batch_size lowerCAmelCase_ : List[str] = num_channels lowerCAmelCase_ : List[str] = image_size lowerCAmelCase_ : Dict = min_resolution lowerCAmelCase_ : Tuple = max_resolution lowerCAmelCase_ : List[Any] = do_resize lowerCAmelCase_ : Dict = size lowerCAmelCase_ : str = do_normalize lowerCAmelCase_ : Any = image_mean lowerCAmelCase_ : Optional[int] = image_std def UpperCAmelCase__ ( self : Optional[int]): return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class __snake_case ( UpperCamelCase_ ,unittest.TestCase ): _a = ViTImageProcessor if is_vision_available() else None def UpperCAmelCase__ ( self : List[Any]): lowerCAmelCase_ : Optional[int] = EfficientFormerImageProcessorTester(self) @property def UpperCAmelCase__ ( self : Optional[int]): return self.image_proc_tester.prepare_image_processor_dict() def UpperCAmelCase__ ( self : Optional[Any]): lowerCAmelCase_ : List[Any] = 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''')) def UpperCAmelCase__ ( self : List[str]): pass def UpperCAmelCase__ ( self : Optional[int]): # Initialize image_processor lowerCAmelCase_ : List[Any] = self.image_processing_class(**self.image_processor_dict) # create random PIL images lowerCAmelCase_ : Tuple = prepare_image_inputs(self.image_proc_tester , equal_resolution=A_) for image in image_inputs: self.assertIsInstance(A_ , Image.Image) # Test not batched input lowerCAmelCase_ : Optional[Any] = image_processor(image_inputs[0] , return_tensors='''pt''').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) # Test batched lowerCAmelCase_ : str = image_processor(A_ , return_tensors='''pt''').pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) def UpperCAmelCase__ ( self : str): # Initialize image_processor lowerCAmelCase_ : List[str] = self.image_processing_class(**self.image_processor_dict) # create random numpy tensors lowerCAmelCase_ : Tuple = prepare_image_inputs(self.image_proc_tester , equal_resolution=A_ , numpify=A_) for image in image_inputs: self.assertIsInstance(A_ , np.ndarray) # Test not batched input lowerCAmelCase_ : str = image_processor(image_inputs[0] , return_tensors='''pt''').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) # Test batched lowerCAmelCase_ : str = image_processor(A_ , return_tensors='''pt''').pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) def UpperCAmelCase__ ( self : str): # Initialize image_processor lowerCAmelCase_ : int = self.image_processing_class(**self.image_processor_dict) # create random PyTorch tensors lowerCAmelCase_ : Tuple = prepare_image_inputs(self.image_proc_tester , equal_resolution=A_ , torchify=A_) for image in image_inputs: self.assertIsInstance(A_ , torch.Tensor) # Test not batched input lowerCAmelCase_ : Dict = image_processor(image_inputs[0] , return_tensors='''pt''').pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) # Test batched lowerCAmelCase_ : Dict = image_processor(A_ , return_tensors='''pt''').pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , )
103
import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinvaConfig, SwinvaForImageClassification def UpperCamelCase( __UpperCamelCase : List[str] ): lowerCAmelCase_ : List[str] = SwinvaConfig() lowerCAmelCase_ : List[str] = swinva_name.split('''_''' ) lowerCAmelCase_ : str = name_split[1] if "to" in name_split[3]: lowerCAmelCase_ : List[Any] = int(name_split[3][-3:] ) else: lowerCAmelCase_ : List[Any] = int(name_split[3] ) if "to" in name_split[2]: lowerCAmelCase_ : List[str] = int(name_split[2][-2:] ) else: lowerCAmelCase_ : int = int(name_split[2][6:] ) if model_size == "tiny": lowerCAmelCase_ : Any = 96 lowerCAmelCase_ : List[str] = (2, 2, 6, 2) lowerCAmelCase_ : Union[str, Any] = (3, 6, 12, 24) elif model_size == "small": lowerCAmelCase_ : List[str] = 96 lowerCAmelCase_ : Any = (2, 2, 18, 2) lowerCAmelCase_ : Dict = (3, 6, 12, 24) elif model_size == "base": lowerCAmelCase_ : Union[str, Any] = 128 lowerCAmelCase_ : List[Any] = (2, 2, 18, 2) lowerCAmelCase_ : Tuple = (4, 8, 16, 32) else: lowerCAmelCase_ : Optional[Any] = 192 lowerCAmelCase_ : List[Any] = (2, 2, 18, 2) lowerCAmelCase_ : List[Any] = (6, 12, 24, 48) if "to" in swinva_name: lowerCAmelCase_ : Union[str, Any] = (12, 12, 12, 6) if ("22k" in swinva_name) and ("to" not in swinva_name): lowerCAmelCase_ : Optional[int] = 21841 lowerCAmelCase_ : Any = '''huggingface/label-files''' lowerCAmelCase_ : Tuple = '''imagenet-22k-id2label.json''' lowerCAmelCase_ : Any = json.load(open(hf_hub_download(__UpperCamelCase ,__UpperCamelCase ,repo_type='''dataset''' ) ,'''r''' ) ) lowerCAmelCase_ : Optional[Any] = {int(__UpperCamelCase ): v for k, v in idalabel.items()} lowerCAmelCase_ : str = idalabel lowerCAmelCase_ : List[str] = {v: k for k, v in idalabel.items()} else: lowerCAmelCase_ : Optional[int] = 1000 lowerCAmelCase_ : Tuple = '''huggingface/label-files''' lowerCAmelCase_ : Union[str, Any] = '''imagenet-1k-id2label.json''' lowerCAmelCase_ : Dict = json.load(open(hf_hub_download(__UpperCamelCase ,__UpperCamelCase ,repo_type='''dataset''' ) ,'''r''' ) ) lowerCAmelCase_ : int = {int(__UpperCamelCase ): v for k, v in idalabel.items()} lowerCAmelCase_ : List[str] = idalabel lowerCAmelCase_ : Optional[int] = {v: k for k, v in idalabel.items()} lowerCAmelCase_ : Optional[int] = img_size lowerCAmelCase_ : Dict = num_classes lowerCAmelCase_ : Dict = embed_dim lowerCAmelCase_ : Optional[Any] = depths lowerCAmelCase_ : Optional[int] = num_heads lowerCAmelCase_ : Dict = window_size return config def UpperCamelCase( __UpperCamelCase : List[str] ): if "patch_embed.proj" in name: lowerCAmelCase_ : Dict = name.replace('''patch_embed.proj''' ,'''embeddings.patch_embeddings.projection''' ) if "patch_embed.norm" in name: lowerCAmelCase_ : List[Any] = name.replace('''patch_embed.norm''' ,'''embeddings.norm''' ) if "layers" in name: lowerCAmelCase_ : int = '''encoder.''' + name if "attn.proj" in name: lowerCAmelCase_ : Union[str, Any] = name.replace('''attn.proj''' ,'''attention.output.dense''' ) if "attn" in name: lowerCAmelCase_ : Optional[Any] = name.replace('''attn''' ,'''attention.self''' ) if "norm1" in name: lowerCAmelCase_ : Union[str, Any] = name.replace('''norm1''' ,'''layernorm_before''' ) if "norm2" in name: lowerCAmelCase_ : Tuple = name.replace('''norm2''' ,'''layernorm_after''' ) if "mlp.fc1" in name: lowerCAmelCase_ : Optional[Any] = name.replace('''mlp.fc1''' ,'''intermediate.dense''' ) if "mlp.fc2" in name: lowerCAmelCase_ : Tuple = name.replace('''mlp.fc2''' ,'''output.dense''' ) if "q_bias" in name: lowerCAmelCase_ : Tuple = name.replace('''q_bias''' ,'''query.bias''' ) if "k_bias" in name: lowerCAmelCase_ : Tuple = name.replace('''k_bias''' ,'''key.bias''' ) if "v_bias" in name: lowerCAmelCase_ : int = name.replace('''v_bias''' ,'''value.bias''' ) if "cpb_mlp" in name: lowerCAmelCase_ : Any = name.replace('''cpb_mlp''' ,'''continuous_position_bias_mlp''' ) if name == "norm.weight": lowerCAmelCase_ : Dict = '''layernorm.weight''' if name == "norm.bias": lowerCAmelCase_ : Any = '''layernorm.bias''' if "head" in name: lowerCAmelCase_ : int = name.replace('''head''' ,'''classifier''' ) else: lowerCAmelCase_ : Union[str, Any] = '''swinv2.''' + name return name def UpperCamelCase( __UpperCamelCase : Any ,__UpperCamelCase : Optional[int] ): for key in orig_state_dict.copy().keys(): lowerCAmelCase_ : Optional[int] = orig_state_dict.pop(__UpperCamelCase ) if "mask" in key: continue elif "qkv" in key: lowerCAmelCase_ : Dict = key.split('''.''' ) lowerCAmelCase_ : Any = int(key_split[1] ) lowerCAmelCase_ : Optional[int] = int(key_split[3] ) lowerCAmelCase_ : Dict = model.swinva.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: lowerCAmelCase_ : Optional[Any] = val[:dim, :] lowerCAmelCase_ : Any = val[dim : dim * 2, :] lowerCAmelCase_ : List[Any] = val[-dim:, :] else: lowerCAmelCase_ : Dict = val[:dim] lowerCAmelCase_ : Union[str, Any] = val[ dim : dim * 2 ] lowerCAmelCase_ : Dict = val[-dim:] else: lowerCAmelCase_ : Optional[Any] = val return orig_state_dict def UpperCamelCase( __UpperCamelCase : int ,__UpperCamelCase : Dict ): lowerCAmelCase_ : Optional[Any] = timm.create_model(__UpperCamelCase ,pretrained=__UpperCamelCase ) timm_model.eval() lowerCAmelCase_ : List[str] = get_swinva_config(__UpperCamelCase ) lowerCAmelCase_ : Union[str, Any] = SwinvaForImageClassification(__UpperCamelCase ) model.eval() lowerCAmelCase_ : str = convert_state_dict(timm_model.state_dict() ,__UpperCamelCase ) model.load_state_dict(__UpperCamelCase ) lowerCAmelCase_ : List[Any] = '''http://images.cocodataset.org/val2017/000000039769.jpg''' lowerCAmelCase_ : Tuple = AutoImageProcessor.from_pretrained('''microsoft/{}'''.format(swinva_name.replace('''_''' ,'''-''' ) ) ) lowerCAmelCase_ : Union[str, Any] = Image.open(requests.get(__UpperCamelCase ,stream=__UpperCamelCase ).raw ) lowerCAmelCase_ : Optional[Any] = image_processor(images=__UpperCamelCase ,return_tensors='''pt''' ) lowerCAmelCase_ : List[str] = timm_model(inputs['''pixel_values'''] ) lowerCAmelCase_ : Union[str, Any] = model(**__UpperCamelCase ).logits assert torch.allclose(__UpperCamelCase ,__UpperCamelCase ,atol=1e-3 ) print(f"""Saving model {swinva_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(__UpperCamelCase ) print(f"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(__UpperCamelCase ) model.push_to_hub( repo_path_or_name=Path(__UpperCamelCase ,__UpperCamelCase ) ,organization='''nandwalritik''' ,commit_message='''Add model''' ,) if __name__ == "__main__": A__ : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--swinv2_name''', default='''swinv2_tiny_patch4_window8_256''', type=str, help='''Name of the Swinv2 timm model you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) A__ : Optional[Any] = parser.parse_args() convert_swinva_checkpoint(args.swinva_name, args.pytorch_dump_folder_path)
103
1
"""simple docstring""" from __future__ import annotations import unittest from transformers import EsmConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import numpy import tensorflow as tf from transformers.models.esm.modeling_tf_esm import ( TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST, TFEsmForMaskedLM, TFEsmForSequenceClassification, TFEsmForTokenClassification, TFEsmModel, ) class _lowerCamelCase : def __init__(self , __a , ) -> Union[str, Any]: UpperCamelCase = parent UpperCamelCase = 13 UpperCamelCase = 7 UpperCamelCase = True UpperCamelCase = True UpperCamelCase = True UpperCamelCase = 99 UpperCamelCase = 32 UpperCamelCase = 2 UpperCamelCase = 4 UpperCamelCase = 37 UpperCamelCase = "gelu" UpperCamelCase = 0.1 UpperCamelCase = 0.1 UpperCamelCase = 5_12 UpperCamelCase = 16 UpperCamelCase = 2 UpperCamelCase = 0.02 UpperCamelCase = 3 UpperCamelCase = 4 UpperCamelCase = None def snake_case_ (self ) -> Optional[Any]: UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase = None if self.use_input_mask: UpperCamelCase = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase = None UpperCamelCase = None UpperCamelCase = None if self.use_labels: UpperCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase = EsmConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , pad_token_id=1 , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def snake_case_ (self ) -> int: ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) = self.prepare_config_and_inputs() UpperCamelCase = True UpperCamelCase = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def snake_case_ (self , __a , __a , __a , __a , __a , __a ) -> Union[str, Any]: UpperCamelCase = TFEsmModel(config=__a ) UpperCamelCase = {"input_ids": input_ids, "attention_mask": input_mask} UpperCamelCase = model(__a ) UpperCamelCase = [input_ids, input_mask] UpperCamelCase = model(__a ) UpperCamelCase = model(__a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def snake_case_ (self , __a , __a , __a , __a , __a , __a , __a , __a , ) -> Union[str, Any]: UpperCamelCase = True UpperCamelCase = TFEsmModel(config=__a ) UpperCamelCase = { "input_ids": input_ids, "attention_mask": input_mask, "encoder_hidden_states": encoder_hidden_states, "encoder_attention_mask": encoder_attention_mask, } UpperCamelCase = model(__a ) UpperCamelCase = [input_ids, input_mask] UpperCamelCase = model(__a , encoder_hidden_states=__a ) # Also check the case where encoder outputs are not passed UpperCamelCase = model(__a , attention_mask=__a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def snake_case_ (self , __a , __a , __a , __a , __a , __a ) -> List[Any]: UpperCamelCase = TFEsmForMaskedLM(config=__a ) UpperCamelCase = model([input_ids, input_mask] ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def snake_case_ (self , __a , __a , __a , __a , __a , __a ) -> int: UpperCamelCase = self.num_labels UpperCamelCase = TFEsmForTokenClassification(config=__a ) UpperCamelCase = {"input_ids": input_ids, "attention_mask": input_mask} UpperCamelCase = model(__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def snake_case_ (self ) -> List[Any]: UpperCamelCase = self.prepare_config_and_inputs() ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) = config_and_inputs UpperCamelCase = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_tf class _lowerCamelCase ( _lowercase , _lowercase , unittest.TestCase ): UpperCAmelCase_ = ( ( TFEsmModel, TFEsmForMaskedLM, TFEsmForSequenceClassification, TFEsmForTokenClassification, ) if is_tf_available() else () ) UpperCAmelCase_ = ( { "feature-extraction": TFEsmModel, "fill-mask": TFEsmForMaskedLM, "text-classification": TFEsmForSequenceClassification, "token-classification": TFEsmForTokenClassification, "zero-shot": TFEsmForSequenceClassification, } if is_tf_available() else {} ) UpperCAmelCase_ = False UpperCAmelCase_ = False def snake_case_ (self ) -> str: UpperCamelCase = TFEsmModelTester(self ) UpperCamelCase = ConfigTester(self , config_class=__a , hidden_size=37 ) def snake_case_ (self ) -> Optional[Any]: self.config_tester.run_common_tests() def snake_case_ (self ) -> Optional[Any]: UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__a ) def snake_case_ (self ) -> List[Any]: UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*__a ) def snake_case_ (self ) -> List[str]: UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*__a ) def snake_case_ (self ) -> List[Any]: UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__a ) @slow def snake_case_ (self ) -> str: for model_name in TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase = TFEsmModel.from_pretrained(__a ) self.assertIsNotNone(__a ) @unittest.skip("Protein models do not support embedding resizing." ) def snake_case_ (self ) -> Any: pass @unittest.skip("Protein models do not support embedding resizing." ) def snake_case_ (self ) -> List[str]: pass def snake_case_ (self ) -> Optional[Any]: UpperCamelCase , UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase = model_class(__a ) assert isinstance(model.get_input_embeddings() , tf.keras.layers.Layer ) if model_class is TFEsmForMaskedLM: # Output embedding test differs from the main test because they're a matrix, not a layer UpperCamelCase = model.get_bias() assert isinstance(__a , __a ) for k, v in name.items(): assert isinstance(__a , tf.Variable ) else: UpperCamelCase = model.get_output_embeddings() assert x is None UpperCamelCase = model.get_bias() assert name is None @require_tf class _lowerCamelCase ( unittest.TestCase ): @slow def snake_case_ (self ) -> int: UpperCamelCase = TFEsmForMaskedLM.from_pretrained("facebook/esm2_t6_8M_UR50D" ) UpperCamelCase = tf.constant([[0, 1, 2, 3, 4, 5]] ) UpperCamelCase = model(__a )[0] UpperCamelCase = [1, 6, 33] self.assertEqual(list(output.numpy().shape ) , __a ) # compare the actual values for a slice. UpperCamelCase = tf.constant( [ [ [8.921518, -10.589814, -6.4671307], [-6.3967156, -13.911377, -1.1211915], [-7.781247, -13.951557, -3.740592], ] ] ) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1e-2 ) ) @slow def snake_case_ (self ) -> Union[str, Any]: UpperCamelCase = TFEsmModel.from_pretrained("facebook/esm2_t6_8M_UR50D" ) UpperCamelCase = tf.constant([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] ) UpperCamelCase = model(__a )[0] # compare the actual values for a slice. UpperCamelCase = tf.constant( [ [ [0.14443092, 0.54125327, 0.3247739], [0.30340484, 0.00526676, 0.31077722], [0.32278043, -0.24987096, 0.3414628], ] ] ) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1e-4 ) )
244
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = '''▁''' lowerCAmelCase__ = {'''vocab_file''': '''sentencepiece.bpe.model'''} lowerCAmelCase__ = { '''vocab_file''': { '''facebook/mbart-large-en-ro''': ( '''https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/sentencepiece.bpe.model''' ), '''facebook/mbart-large-cc25''': ( '''https://huggingface.co/facebook/mbart-large-cc25/resolve/main/sentencepiece.bpe.model''' ), } } lowerCAmelCase__ = { '''facebook/mbart-large-en-ro''': 1_024, '''facebook/mbart-large-cc25''': 1_024, } # fmt: off lowerCAmelCase__ = ['''ar_AR''', '''cs_CZ''', '''de_DE''', '''en_XX''', '''es_XX''', '''et_EE''', '''fi_FI''', '''fr_XX''', '''gu_IN''', '''hi_IN''', '''it_IT''', '''ja_XX''', '''kk_KZ''', '''ko_KR''', '''lt_LT''', '''lv_LV''', '''my_MM''', '''ne_NP''', '''nl_XX''', '''ro_RO''', '''ru_RU''', '''si_LK''', '''tr_TR''', '''vi_VN''', '''zh_CN'''] class _lowerCamelCase ( _lowercase ): UpperCAmelCase_ = VOCAB_FILES_NAMES UpperCAmelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase_ = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase_ = ["input_ids", "attention_mask"] UpperCAmelCase_ = [] UpperCAmelCase_ = [] def __init__(self , __a , __a="<s>" , __a="</s>" , __a="</s>" , __a="<s>" , __a="<unk>" , __a="<pad>" , __a="<mask>" , __a=None , __a=None , __a=None , __a = None , __a=None , **__a , ) -> Dict: # Mask token behave like a normal word, i.e. include the space before it UpperCamelCase = AddedToken(__a , lstrip=__a , rstrip=__a ) if isinstance(__a , __a ) else mask_token UpperCamelCase = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__a , eos_token=__a , unk_token=__a , sep_token=__a , cls_token=__a , pad_token=__a , mask_token=__a , tokenizer_file=__a , src_lang=__a , tgt_lang=__a , additional_special_tokens=__a , sp_model_kwargs=self.sp_model_kwargs , **__a , ) UpperCamelCase = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__a ) ) UpperCamelCase = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # Mimic fairseq token-to-id alignment for the first 4 token UpperCamelCase = {"<s>": 0, "<pad>": 1, "</s>": 2, "<unk>": 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab UpperCamelCase = 1 UpperCamelCase = len(self.sp_model ) UpperCamelCase = { code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(__a ) } UpperCamelCase = {v: k for k, v in self.lang_code_to_id.items()} UpperCamelCase = len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset self.fairseq_tokens_to_ids.update(self.lang_code_to_id ) UpperCamelCase = {v: k for k, v in self.fairseq_tokens_to_ids.items()} UpperCamelCase = list(self.lang_code_to_id.keys() ) if additional_special_tokens is not None: # Only add those special tokens if they are not already there. self._additional_special_tokens.extend( [t for t in additional_special_tokens if t not in self._additional_special_tokens] ) UpperCamelCase = src_lang if src_lang is not None else "en_XX" UpperCamelCase = self.lang_code_to_id[self._src_lang] UpperCamelCase = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) def __getstate__(self ) -> Any: UpperCamelCase = self.__dict__.copy() UpperCamelCase = None UpperCamelCase = self.sp_model.serialized_model_proto() return state def __setstate__(self , __a ) -> Tuple: UpperCamelCase = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): UpperCamelCase = {} UpperCamelCase = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) @property def snake_case_ (self ) -> Any: return len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset + 1 # Plus 1 for the mask token @property def snake_case_ (self ) -> str: return self._src_lang @src_lang.setter def snake_case_ (self , __a ) -> None: UpperCamelCase = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def snake_case_ (self , __a , __a = None , __a = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__a , token_ids_a=__a , already_has_special_tokens=__a ) UpperCamelCase = [1] * len(self.prefix_tokens ) UpperCamelCase = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(__a )) + suffix_ones return prefix_ones + ([0] * len(__a )) + ([0] * len(__a )) + suffix_ones def snake_case_ (self , __a , __a = None ) -> List[int]: if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def snake_case_ (self , __a , __a = None ) -> List[int]: UpperCamelCase = [self.sep_token_id] UpperCamelCase = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def snake_case_ (self , __a , __a , __a , __a , **__a ) -> Optional[int]: if src_lang is None or tgt_lang is None: raise ValueError("Translation requires a `src_lang` and a `tgt_lang` for this model" ) UpperCamelCase = src_lang UpperCamelCase = self(__a , add_special_tokens=__a , return_tensors=__a , **__a ) UpperCamelCase = self.convert_tokens_to_ids(__a ) UpperCamelCase = tgt_lang_id return inputs def snake_case_ (self ) -> List[str]: UpperCamelCase = {self.convert_ids_to_tokens(__a ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def snake_case_ (self , __a ) -> List[str]: return self.sp_model.encode(__a , out_type=__a ) def snake_case_ (self , __a ) -> Tuple: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] UpperCamelCase = self.sp_model.PieceToId(__a ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def snake_case_ (self , __a ) -> Optional[int]: if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def snake_case_ (self , __a ) -> Optional[int]: UpperCamelCase = "".join(__a ).replace(__a , " " ).strip() return out_string def snake_case_ (self , __a , __a = None ) -> Tuple[str]: if not os.path.isdir(__a ): logger.error(F"Vocabulary path ({save_directory}) should be a directory" ) return UpperCamelCase = os.path.join( __a , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__a ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __a ) elif not os.path.isfile(self.vocab_file ): with open(__a , "wb" ) as fi: UpperCamelCase = self.sp_model.serialized_model_proto() fi.write(__a ) return (out_vocab_file,) def snake_case_ (self , __a , __a = "en_XX" , __a = None , __a = "ro_RO" , **__a , ) -> BatchEncoding: UpperCamelCase = src_lang UpperCamelCase = tgt_lang return super().prepare_seqaseq_batch(__a , __a , **__a ) def snake_case_ (self ) -> str: return self.set_src_lang_special_tokens(self.src_lang ) def snake_case_ (self ) -> Optional[int]: return self.set_tgt_lang_special_tokens(self.tgt_lang ) def snake_case_ (self , __a ) -> None: UpperCamelCase = self.lang_code_to_id[src_lang] UpperCamelCase = [] UpperCamelCase = [self.eos_token_id, self.cur_lang_code] def snake_case_ (self , __a ) -> None: UpperCamelCase = self.lang_code_to_id[lang] UpperCamelCase = [] UpperCamelCase = [self.eos_token_id, self.cur_lang_code]
244
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) A__ : str ={ '''configuration_blip''': [ '''BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BlipConfig''', '''BlipTextConfig''', '''BlipVisionConfig''', ], '''processing_blip''': ['''BlipProcessor'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Union[str, Any] =['''BlipImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : List[str] =[ '''BLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BlipModel''', '''BlipPreTrainedModel''', '''BlipForConditionalGeneration''', '''BlipForQuestionAnswering''', '''BlipVisionModel''', '''BlipTextModel''', '''BlipForImageTextRetrieval''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Optional[Any] =[ '''TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFBlipModel''', '''TFBlipPreTrainedModel''', '''TFBlipForConditionalGeneration''', '''TFBlipForQuestionAnswering''', '''TFBlipVisionModel''', '''TFBlipTextModel''', '''TFBlipForImageTextRetrieval''', ] if TYPE_CHECKING: from .configuration_blip import BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipConfig, BlipTextConfig, BlipVisionConfig from .processing_blip import BlipProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_blip import BlipImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blip import ( BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, BlipModel, BlipPreTrainedModel, BlipTextModel, BlipVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blip import ( TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFBlipForConditionalGeneration, TFBlipForImageTextRetrieval, TFBlipForQuestionAnswering, TFBlipModel, TFBlipPreTrainedModel, TFBlipTextModel, TFBlipVisionModel, ) else: import sys A__ : Optional[int] =_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
70
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A__ : Optional[Any] ={ '''configuration_bigbird_pegasus''': [ '''BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BigBirdPegasusConfig''', '''BigBirdPegasusOnnxConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Union[str, Any] =[ '''BIGBIRD_PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BigBirdPegasusForCausalLM''', '''BigBirdPegasusForConditionalGeneration''', '''BigBirdPegasusForQuestionAnswering''', '''BigBirdPegasusForSequenceClassification''', '''BigBirdPegasusModel''', '''BigBirdPegasusPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_bigbird_pegasus import ( BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP, BigBirdPegasusConfig, BigBirdPegasusOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bigbird_pegasus import ( BIGBIRD_PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST, BigBirdPegasusForCausalLM, BigBirdPegasusForConditionalGeneration, BigBirdPegasusForQuestionAnswering, BigBirdPegasusForSequenceClassification, BigBirdPegasusModel, BigBirdPegasusPreTrainedModel, ) else: import sys A__ : Optional[Any] =_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
70
1
"""simple docstring""" from typing import Dict, List, Optional, Tuple, Union import torch from ...models import AutoencoderKL, TransformeraDModel from ...schedulers import KarrasDiffusionSchedulers from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class A__ ( lowerCamelCase__ ): '''simple docstring''' def __init__( self: int , _SCREAMING_SNAKE_CASE: TransformeraDModel , _SCREAMING_SNAKE_CASE: AutoencoderKL , _SCREAMING_SNAKE_CASE: KarrasDiffusionSchedulers , _SCREAMING_SNAKE_CASE: Optional[Dict[int, str]] = None , ) -> Any: """simple docstring""" super().__init__() self.register_modules(transformer=__A , vae=__A , scheduler=__A) # create a imagenet -> id dictionary for easier use __lowerCAmelCase : Union[str, Any] = {} if idalabel is not None: for key, value in idalabel.items(): for label in value.split(","): __lowerCAmelCase : Optional[Any] = int(__A) __lowerCAmelCase : Union[str, Any] = dict(sorted(self.labels.items())) def _SCREAMING_SNAKE_CASE ( self: Dict , _SCREAMING_SNAKE_CASE: Union[str, List[str]]) -> Tuple: """simple docstring""" if not isinstance(__A , __A): __lowerCAmelCase : List[Any] = list(__A) for l in label: if l not in self.labels: raise ValueError( F"""{l} does not exist. Please make sure to select one of the following labels: \n {self.labels}.""") return [self.labels[l] for l in label] @torch.no_grad() def __call__( self: Optional[int] , _SCREAMING_SNAKE_CASE: List[int] , _SCREAMING_SNAKE_CASE: float = 4.0 , _SCREAMING_SNAKE_CASE: Optional[Union[torch.Generator, List[torch.Generator]]] = None , _SCREAMING_SNAKE_CASE: int = 50 , _SCREAMING_SNAKE_CASE: Optional[str] = "pil" , _SCREAMING_SNAKE_CASE: bool = True , ) -> Any: """simple docstring""" __lowerCAmelCase : str = len(__A) __lowerCAmelCase : Dict = self.transformer.config.sample_size __lowerCAmelCase : List[Any] = self.transformer.config.in_channels __lowerCAmelCase : Union[str, Any] = randn_tensor( shape=(batch_size, latent_channels, latent_size, latent_size) , generator=__A , device=self.device , dtype=self.transformer.dtype , ) __lowerCAmelCase : Tuple = torch.cat([latents] * 2) if guidance_scale > 1 else latents __lowerCAmelCase : Any = torch.tensor(__A , device=self.device).reshape(-1) __lowerCAmelCase : Union[str, Any] = torch.tensor([1000] * batch_size , device=self.device) __lowerCAmelCase : Optional[int] = torch.cat([class_labels, class_null] , 0) if guidance_scale > 1 else class_labels # set step values self.scheduler.set_timesteps(__A) for t in self.progress_bar(self.scheduler.timesteps): if guidance_scale > 1: __lowerCAmelCase : Dict = latent_model_input[: len(__A) // 2] __lowerCAmelCase : Union[str, Any] = torch.cat([half, half] , dim=0) __lowerCAmelCase : Tuple = self.scheduler.scale_model_input(__A , __A) __lowerCAmelCase : int = t if not torch.is_tensor(__A): # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can # This would be a good case for the `match` statement (Python 3.10+) __lowerCAmelCase : Optional[Any] = latent_model_input.device.type == '''mps''' if isinstance(__A , __A): __lowerCAmelCase : List[str] = torch.floataa if is_mps else torch.floataa else: __lowerCAmelCase : Dict = torch.intaa if is_mps else torch.intaa __lowerCAmelCase : Optional[Any] = torch.tensor([timesteps] , dtype=__A , device=latent_model_input.device) elif len(timesteps.shape) == 0: __lowerCAmelCase : Optional[int] = timesteps[None].to(latent_model_input.device) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML __lowerCAmelCase : Any = timesteps.expand(latent_model_input.shape[0]) # predict noise model_output __lowerCAmelCase : Any = self.transformer( __A , timestep=__A , class_labels=__A).sample # perform guidance if guidance_scale > 1: __lowerCAmelCase : Union[str, Any] = noise_pred[:, :latent_channels], noise_pred[:, latent_channels:] __lowerCAmelCase : str = torch.split(__A , len(__A) // 2 , dim=0) __lowerCAmelCase : Optional[Any] = uncond_eps + guidance_scale * (cond_eps - uncond_eps) __lowerCAmelCase : Union[str, Any] = torch.cat([half_eps, half_eps] , dim=0) __lowerCAmelCase : Optional[Any] = torch.cat([eps, rest] , dim=1) # learned sigma if self.transformer.config.out_channels // 2 == latent_channels: __lowerCAmelCase : Dict = torch.split(__A , __A , dim=1) else: __lowerCAmelCase : int = noise_pred # compute previous image: x_t -> x_t-1 __lowerCAmelCase : List[str] = self.scheduler.step(__A , __A , __A).prev_sample if guidance_scale > 1: __lowerCAmelCase : Optional[int] = latent_model_input.chunk(2 , dim=0) else: __lowerCAmelCase : int = latent_model_input __lowerCAmelCase : List[Any] = 1 / self.vae.config.scaling_factor * latents __lowerCAmelCase : Dict = self.vae.decode(__A).sample __lowerCAmelCase : Optional[Any] = (samples / 2 + 0.5).clamp(0 , 1) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 __lowerCAmelCase : Union[str, Any] = samples.cpu().permute(0 , 2 , 3 , 1).float().numpy() if output_type == "pil": __lowerCAmelCase : List[str] = self.numpy_to_pil(__A) if not return_dict: return (samples,) return ImagePipelineOutput(images=__A)
360
"""simple docstring""" from typing import Dict, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import flip_channel_order, resize, to_channel_dimension_format, to_pil_image from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_pytesseract_available, is_vision_available, logging, requires_backends if is_vision_available(): import PIL # soft dependency if is_pytesseract_available(): import pytesseract __snake_case : Tuple = logging.get_logger(__name__) def _lowercase ( __snake_case ,__snake_case ,__snake_case ) -> Any: return [ int(1_000 * (box[0] / width) ), int(1_000 * (box[1] / height) ), int(1_000 * (box[2] / width) ), int(1_000 * (box[3] / height) ), ] def _lowercase ( __snake_case ,__snake_case ,__snake_case = None ) -> Tuple: __lowerCAmelCase : Tuple = tesseract_config if tesseract_config is not None else "" # apply OCR __lowerCAmelCase : List[str] = to_pil_image(__snake_case ) __lowerCAmelCase , __lowerCAmelCase : Optional[int] = pil_image.size __lowerCAmelCase : str = pytesseract.image_to_data(__snake_case ,lang=__snake_case ,output_type="dict" ,config=__snake_case ) __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase : Tuple = data["text"], data["left"], data["top"], data["width"], data["height"] # filter empty words and corresponding coordinates __lowerCAmelCase : List[str] = [idx for idx, word in enumerate(__snake_case ) if not word.strip()] __lowerCAmelCase : Any = [word for idx, word in enumerate(__snake_case ) if idx not in irrelevant_indices] __lowerCAmelCase : Any = [coord for idx, coord in enumerate(__snake_case ) if idx not in irrelevant_indices] __lowerCAmelCase : List[Any] = [coord for idx, coord in enumerate(__snake_case ) if idx not in irrelevant_indices] __lowerCAmelCase : List[Any] = [coord for idx, coord in enumerate(__snake_case ) if idx not in irrelevant_indices] __lowerCAmelCase : List[str] = [coord for idx, coord in enumerate(__snake_case ) if idx not in irrelevant_indices] # turn coordinates into (left, top, left+width, top+height) format __lowerCAmelCase : List[Any] = [] for x, y, w, h in zip(__snake_case ,__snake_case ,__snake_case ,__snake_case ): __lowerCAmelCase : Optional[Any] = [x, y, x + w, y + h] actual_boxes.append(__snake_case ) # finally, normalize the bounding boxes __lowerCAmelCase : Optional[Any] = [] for box in actual_boxes: normalized_boxes.append(normalize_box(__snake_case ,__snake_case ,__snake_case ) ) assert len(__snake_case ) == len(__snake_case ), "Not as many words as there are bounding boxes" return words, normalized_boxes class A__ ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' SCREAMING_SNAKE_CASE = ['pixel_values'] def __init__( self: List[str] , _SCREAMING_SNAKE_CASE: bool = True , _SCREAMING_SNAKE_CASE: Dict[str, int] = None , _SCREAMING_SNAKE_CASE: PILImageResampling = PILImageResampling.BILINEAR , _SCREAMING_SNAKE_CASE: bool = True , _SCREAMING_SNAKE_CASE: Optional[str] = None , _SCREAMING_SNAKE_CASE: Optional[str] = "" , **_SCREAMING_SNAKE_CASE: Union[str, Any] , ) -> None: """simple docstring""" super().__init__(**_SCREAMING_SNAKE_CASE) __lowerCAmelCase : Optional[int] = size if size is not None else {"height": 224, "width": 224} __lowerCAmelCase : List[str] = get_size_dict(_SCREAMING_SNAKE_CASE) __lowerCAmelCase : Dict = do_resize __lowerCAmelCase : Optional[int] = size __lowerCAmelCase : Union[str, Any] = resample __lowerCAmelCase : Dict = apply_ocr __lowerCAmelCase : Dict = ocr_lang __lowerCAmelCase : List[str] = tesseract_config def _SCREAMING_SNAKE_CASE ( self: int , _SCREAMING_SNAKE_CASE: np.ndarray , _SCREAMING_SNAKE_CASE: Dict[str, int] , _SCREAMING_SNAKE_CASE: PILImageResampling = PILImageResampling.BILINEAR , _SCREAMING_SNAKE_CASE: Optional[Union[str, ChannelDimension]] = None , **_SCREAMING_SNAKE_CASE: Any , ) -> np.ndarray: """simple docstring""" __lowerCAmelCase : List[Any] = get_size_dict(_SCREAMING_SNAKE_CASE) 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()}""") __lowerCAmelCase : Dict = (size["height"], size["width"]) return resize(_SCREAMING_SNAKE_CASE , size=_SCREAMING_SNAKE_CASE , resample=_SCREAMING_SNAKE_CASE , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE) def _SCREAMING_SNAKE_CASE ( self: Any , _SCREAMING_SNAKE_CASE: ImageInput , _SCREAMING_SNAKE_CASE: bool = None , _SCREAMING_SNAKE_CASE: Dict[str, int] = None , _SCREAMING_SNAKE_CASE: PILImageResampling = None , _SCREAMING_SNAKE_CASE: bool = None , _SCREAMING_SNAKE_CASE: Optional[str] = None , _SCREAMING_SNAKE_CASE: Optional[str] = None , _SCREAMING_SNAKE_CASE: Optional[Union[str, TensorType]] = None , _SCREAMING_SNAKE_CASE: ChannelDimension = ChannelDimension.FIRST , **_SCREAMING_SNAKE_CASE: List[str] , ) -> PIL.Image.Image: """simple docstring""" __lowerCAmelCase : str = do_resize if do_resize is not None else self.do_resize __lowerCAmelCase : Optional[int] = size if size is not None else self.size __lowerCAmelCase : int = get_size_dict(_SCREAMING_SNAKE_CASE) __lowerCAmelCase : str = resample if resample is not None else self.resample __lowerCAmelCase : Any = apply_ocr if apply_ocr is not None else self.apply_ocr __lowerCAmelCase : List[str] = ocr_lang if ocr_lang is not None else self.ocr_lang __lowerCAmelCase : Tuple = tesseract_config if tesseract_config is not None else self.tesseract_config __lowerCAmelCase : str = make_list_of_images(_SCREAMING_SNAKE_CASE) if not valid_images(_SCREAMING_SNAKE_CASE): 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.") # All transformations expect numpy arrays. __lowerCAmelCase : List[str] = [to_numpy_array(_SCREAMING_SNAKE_CASE) for image in images] if apply_ocr: requires_backends(self , "pytesseract") __lowerCAmelCase : Tuple = [] __lowerCAmelCase : Optional[int] = [] for image in images: __lowerCAmelCase , __lowerCAmelCase : Any = apply_tesseract(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE) words_batch.append(_SCREAMING_SNAKE_CASE) boxes_batch.append(_SCREAMING_SNAKE_CASE) if do_resize: __lowerCAmelCase : Optional[int] = [self.resize(image=_SCREAMING_SNAKE_CASE , size=_SCREAMING_SNAKE_CASE , resample=_SCREAMING_SNAKE_CASE) for image in images] # flip color channels from RGB to BGR (as Detectron2 requires this) __lowerCAmelCase : List[str] = [flip_channel_order(_SCREAMING_SNAKE_CASE) for image in images] __lowerCAmelCase : str = [to_channel_dimension_format(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE) for image in images] __lowerCAmelCase : int = BatchFeature(data={"pixel_values": images} , tensor_type=_SCREAMING_SNAKE_CASE) if apply_ocr: __lowerCAmelCase : Optional[int] = words_batch __lowerCAmelCase : Optional[int] = boxes_batch return data
58
0
"""simple docstring""" from pathlib import Path import fire from tqdm import tqdm def lowerCAmelCase__ ( _UpperCamelCase : Any="ro" , _UpperCamelCase : Optional[Any]="en" , _UpperCamelCase : Any="wmt16" , _UpperCamelCase : Tuple=None ) -> None: """simple docstring""" try: import datasets except (ModuleNotFoundError, ImportError): raise ImportError('run pip install datasets' ) snake_case = f"""{src_lang}-{tgt_lang}""" print(f"""Converting {dataset}-{pair}""" ) snake_case = datasets.load_dataset(_UpperCamelCase , _UpperCamelCase ) if save_dir is None: snake_case = f"""{dataset}-{pair}""" snake_case = Path(_UpperCamelCase ) save_dir.mkdir(exist_ok=_UpperCamelCase ) for split in ds.keys(): print(f"""Splitting {split} with {ds[split].num_rows} records""" ) # to save to val.source, val.target like summary datasets snake_case = 'val' if split == 'validation' else split snake_case = save_dir.joinpath(f"""{fn}.source""" ) snake_case = save_dir.joinpath(f"""{fn}.target""" ) snake_case = src_path.open('w+' ) snake_case = tgt_path.open('w+' ) # reader is the bottleneck so writing one record at a time doesn't slow things down for x in tqdm(ds[split] ): snake_case = x['translation'] src_fp.write(ex[src_lang] + '\n' ) tgt_fp.write(ex[tgt_lang] + '\n' ) print(f"""Saved {dataset} dataset to {save_dir}""" ) if __name__ == "__main__": fire.Fire(download_wmt_dataset)
150
"""simple docstring""" from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_pool from google.protobuf import symbol_database as _symbol_database from google.protobuf.internal import builder as _builder # @@protoc_insertion_point(imports) SCREAMING_SNAKE_CASE__ = _symbol_database.Default() SCREAMING_SNAKE_CASE__ = _descriptor_pool.Default().AddSerializedFile( b"\n\x19sentencepiece_model.proto\x12\rsentencepiece\"\x80\x0c\n\x0bTrainerSpec\x12\r\n\x05input\x18\x01 \x03(\t\x12\x14\n\x0cinput_format\x18\x07 \x01(\t\x12\x14\n\x0cmodel_prefix\x18\x02 \x01(\t\x12\x41\n\nmodel_type\x18\x03 \x01(\x0e\x32$.sentencepiece.TrainerSpec.ModelType:\x07UNIGRAM\x12\x18\n\nvocab_size\x18\x04 \x01(\x05:\x04\x38\x30\x30\x30\x12\x17\n\x0f\x61\x63\x63\x65pt_language\x18\x05 \x03(\t\x12 \n\x15self_test_sample_size\x18\x06 \x01(\x05:\x01\x30\x12*\n\x1b\x65nable_differential_privacy\x18\x32 \x01(\x08:\x05\x66\x61lse\x12+\n differential_privacy_noise_level\x18\x33 \x01(\x02:\x01\x30\x12\x32\n\'differential_privacy_clipping_threshold\x18\x34 \x01(\x04:\x01\x30\x12\"\n\x12\x63haracter_coverage\x18\n \x01(\x02:\x06\x30.9995\x12\x1e\n\x13input_sentence_size\x18\x0b \x01(\x04:\x01\x30\x12$\n\x16shuffle_input_sentence\x18\x13 \x01(\x08:\x04true\x12 \n\x14mining_sentence_size\x18\x0c \x01(\x05\x42\x02\x18\x01\x12\"\n\x16training_sentence_size\x18\r \x01(\x05\x42\x02\x18\x01\x12(\n\x17seed_sentencepiece_size\x18\x0e \x01(\x05:\x07\x31\x30\x30\x30\x30\x30\x30\x12\x1e\n\x10shrinking_factor\x18\x0f \x01(\x02:\x04\x30.75\x12!\n\x13max_sentence_length\x18\x12 \x01(\x05:\x04\x34\x31\x39\x32\x12\x17\n\x0bnum_threads\x18\x10 \x01(\x05:\x02\x31\x36\x12\x1d\n\x12num_sub_iterations\x18\x11 \x01(\x05:\x01\x32\x12$\n\x18max_sentencepiece_length\x18\x14 \x01(\x05:\x02\x31\x36\x12%\n\x17split_by_unicode_script\x18\x15 \x01(\x08:\x04true\x12\x1d\n\x0fsplit_by_number\x18\x17 \x01(\x08:\x04true\x12!\n\x13split_by_whitespace\x18\x16 \x01(\x08:\x04true\x12)\n\x1atreat_whitespace_as_suffix\x18\x18 \x01(\x08:\x05\x66\x61lse\x12+\n\x1c\x61llow_whitespace_only_pieces\x18\x1a \x01(\x08:\x05\x66\x61lse\x12\x1b\n\x0csplit_digits\x18\x19 \x01(\x08:\x05\x66\x61lse\x12#\n\x19pretokenization_delimiter\x18\x35 \x01(\t:\x00\x12\x17\n\x0f\x63ontrol_symbols\x18\x1e \x03(\t\x12\x1c\n\x14user_defined_symbols\x18\x1f \x03(\t\x12\x16\n\x0erequired_chars\x18$ \x01(\t\x12\x1c\n\rbyte_fallback\x18# \x01(\x08:\x05\x66\x61lse\x12+\n\x1dvocabulary_output_piece_score\x18 \x01(\x08:\x04true\x12\x1e\n\x10hard_vocab_limit\x18! \x01(\x08:\x04true\x12\x1c\n\ruse_all_vocab\x18\" \x01(\x08:\x05\x66\x61lse\x12\x11\n\x06unk_id\x18( \x01(\x05:\x01\x30\x12\x11\n\x06\x62os_id\x18) \x01(\x05:\x01\x31\x12\x11\n\x06\x65os_id\x18* \x01(\x05:\x01\x32\x12\x12\n\x06pad_id\x18+ \x01(\x05:\x02-1\x12\x18\n\tunk_piece\x18- \x01(\t:\x05<unk>\x12\x16\n\tbos_piece\x18. \x01(\t:\x03<s>\x12\x17\n\teos_piece\x18/ \x01(\t:\x04</s>\x12\x18\n\tpad_piece\x18\x30 \x01(\t:\x05<pad>\x12\x1a\n\x0bunk_surface\x18, \x01(\t:\x05 \xe2\x81\x87 \x12+\n\x1ctrain_extremely_large_corpus\x18\x31 \x01(\x08:\x05\x66\x61lse\"5\n\tModelType\x12\x0b\n\x07UNIGRAM\x10\x01\x12\x07\n\x03\x42PE\x10\x02\x12\x08\n\x04WORD\x10\x03\x12\x08\n\x04\x43HAR\x10\x04*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\"\xd1\x01\n\x0eNormalizerSpec\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x1c\n\x14precompiled_charsmap\x18\x02 \x01(\x0c\x12\x1e\n\x10\x61\x64\x64_dummy_prefix\x18\x03 \x01(\x08:\x04true\x12&\n\x18remove_extra_whitespaces\x18\x04 \x01(\x08:\x04true\x12 \n\x12\x65scape_whitespaces\x18\x05 \x01(\x08:\x04true\x12\x1e\n\x16normalization_rule_tsv\x18\x06 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\"y\n\x0cSelfTestData\x12\x33\n\x07samples\x18\x01 \x03(\x0b\x32\".sentencepiece.SelfTestData.Sample\x1a)\n\x06Sample\x12\r\n\x05input\x18\x01 \x01(\t\x12\x10\n\x08\x65xpected\x18\x02 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\"\xfe\x03\n\nModelProto\x12\x37\n\x06pieces\x18\x01 \x03(\x0b\x32\'.sentencepiece.ModelProto.SentencePiece\x12\x30\n\x0ctrainer_spec\x18\x02 \x01(\x0b\x32\x1a.sentencepiece.TrainerSpec\x12\x36\n\x0fnormalizer_spec\x18\x03 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x12\x33\n\x0eself_test_data\x18\x04 \x01(\x0b\x32\x1b.sentencepiece.SelfTestData\x12\x38\n\x11\x64\x65normalizer_spec\x18\x05 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x1a\xd2\x01\n\rSentencePiece\x12\r\n\x05piece\x18\x01 \x01(\t\x12\r\n\x05score\x18\x02 \x01(\x02\x12\x42\n\x04type\x18\x03 \x01(\x0e\x32,.sentencepiece.ModelProto.SentencePiece.Type:\x06NORMAL\"T\n\x04Type\x12\n\n\x06NORMAL\x10\x01\x12\x0b\n\x07UNKNOWN\x10\x02\x12\x0b\n\x07\x43ONTROL\x10\x03\x12\x10\n\x0cUSER_DEFINED\x10\x04\x12\x08\n\x04\x42YTE\x10\x06\x12\n\n\x06UNUSED\x10\x05*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\x42\x02H\x03" ) SCREAMING_SNAKE_CASE__ = globals() _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, "sentencepiece_model_pb2", _globals) if _descriptor._USE_C_DESCRIPTORS is False: SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = b"H\003" # (generated by protobuf compiler, but `_TRAINERSPEC` is not defined) # _TRAINERSPEC.fields_by_name["mining_sentence_size"]._options = None # _TRAINERSPEC.fields_by_name["mining_sentence_size"]._serialized_options = b"\030\001" # _TRAINERSPEC.fields_by_name["training_sentence_size"]._options = None # _TRAINERSPEC.fields_by_name["training_sentence_size"]._serialized_options = b"\030\001" SCREAMING_SNAKE_CASE__ = 45 SCREAMING_SNAKE_CASE__ = 1_581 SCREAMING_SNAKE_CASE__ = 1_517 SCREAMING_SNAKE_CASE__ = 1_570 SCREAMING_SNAKE_CASE__ = 1_584 SCREAMING_SNAKE_CASE__ = 1_793 SCREAMING_SNAKE_CASE__ = 1_795 SCREAMING_SNAKE_CASE__ = 1_916 SCREAMING_SNAKE_CASE__ = 1_864 SCREAMING_SNAKE_CASE__ = 1_905 SCREAMING_SNAKE_CASE__ = 1_919 SCREAMING_SNAKE_CASE__ = 2_429 SCREAMING_SNAKE_CASE__ = 2_208 SCREAMING_SNAKE_CASE__ = 2_418 SCREAMING_SNAKE_CASE__ = 2_323 SCREAMING_SNAKE_CASE__ = 2_407 # @@protoc_insertion_point(module_scope)
150
1
import os import tempfile import unittest from transformers.models.marian.convert_marian_tatoeba_to_pytorch import DEFAULT_REPO, TatoebaConverter from transformers.testing_utils import slow from transformers.utils import cached_property @unittest.skipUnless(os.path.exists(UpperCamelCase ) , "Tatoeba directory does not exist." ) class _lowerCamelCase ( unittest.TestCase ): """simple docstring""" @cached_property def _snake_case ( self )->Optional[int]: '''simple docstring''' A_ : Tuple = tempfile.mkdtemp() return TatoebaConverter(save_dir=_SCREAMING_SNAKE_CASE ) @slow def _snake_case ( self )->Dict: '''simple docstring''' self.resolver.convert_models(['''heb-eng'''] ) @slow def _snake_case ( self )->Tuple: '''simple docstring''' A_ : Tuple = self.resolver.write_model_card('''opus-mt-he-en''' , dry_run=_SCREAMING_SNAKE_CASE ) assert mmeta["long_pair"] == "heb-eng"
368
import math import random def _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = False ): if deriv: return value * (1 - value) return 1 / (1 + math.exp(-value )) # Initial Value UpperCamelCase = 0.02 def _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): A_ : str = float(2 * (random.randint(1 , 100 )) - 1 ) for _ in range(SCREAMING_SNAKE_CASE ): # Forward propagation A_ : Optional[Any] = sigmoid_function(INITIAL_VALUE * weight ) # How much did we miss? A_ : Any = (expected / 100) - layer_a # Error delta A_ : List[str] = layer_1_error * sigmoid_function(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # Update weight weight += INITIAL_VALUE * layer_1_delta return layer_a * 100 if __name__ == "__main__": import doctest doctest.testmod() UpperCamelCase = int(input("""Expected value: """)) UpperCamelCase = int(input("""Number of propagations: """)) print(forward_propagation(expected, number_propagations))
65
0
"""simple docstring""" import requests UpperCAmelCase__ : Optional[Any] = 'YOUR API KEY' def lowercase_ ( _snake_case ,_snake_case = giphy_api_key ): SCREAMING_SNAKE_CASE__ : Tuple = """+""".join(query.split() ) SCREAMING_SNAKE_CASE__ : Optional[int] = f'''https://api.giphy.com/v1/gifs/search?q={formatted_query}&api_key={api_key}''' SCREAMING_SNAKE_CASE__ : List[Any] = requests.get(_snake_case ).json()["""data"""] return [gif["url"] for gif in gifs] if __name__ == "__main__": print('\n'.join(get_gifs('space ship')))
25
"""simple docstring""" def lowerCamelCase__ ( _lowerCamelCase : int , _lowerCamelCase : int ) -> int: lowerCamelCase_ = 1 # To kept the Calculated Value # Since C(n, k) = C(n, n-k) if k > (n - k): lowerCamelCase_ = n - k # Calculate C(n,k) for i in range(_lowerCamelCase ): result *= n - i result //= i + 1 return result def lowerCamelCase__ ( _lowerCamelCase : int ) -> int: return binomial_coefficient(2 * node_count , _lowerCamelCase ) // (node_count + 1) def lowerCamelCase__ ( _lowerCamelCase : int ) -> int: if n < 0: raise ValueError('factorial() not defined for negative values' ) lowerCamelCase_ = 1 for i in range(1 , n + 1 ): result *= i return result def lowerCamelCase__ ( _lowerCamelCase : int ) -> int: return catalan_number(_lowerCamelCase ) * factorial(_lowerCamelCase ) if __name__ == "__main__": _SCREAMING_SNAKE_CASE : int = int(input('''Enter the number of nodes: ''').strip() or 0) if node_count <= 0: raise ValueError('''We need some nodes to work with.''') print( F'''Given {node_count} nodes, there are {binary_tree_count(node_count)} ''' F'''binary trees and {catalan_number(node_count)} binary search trees.''' )
183
0
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices A_ : Any = logging.get_logger(__name__) A_ : int = { 'google/bit-50': 'https://huggingface.co/google/bit-50/resolve/main/config.json', } class _a (__magic_name__ , __magic_name__ ): '''simple docstring''' UpperCAmelCase__: Union[str, Any] = '''bit''' UpperCAmelCase__: Tuple = ['''preactivation''', '''bottleneck'''] UpperCAmelCase__: Optional[Any] = ['''SAME''', '''VALID'''] def __init__( self , A__=3 , A__=64 , A__=[256, 512, 1024, 2048] , A__=[3, 4, 6, 3] , A__="preactivation" , A__="relu" , A__=None , A__=32 , A__=0.0 , A__=False , A__=32 , A__=1 , A__=None , A__=None , **A__ , ): super().__init__(**A__ ) if layer_type not in self.layer_types: raise ValueError(F"""layer_type={layer_type} is not one of {','.join(self.layer_types )}""" ) if global_padding is not None: if global_padding.upper() in self.supported_padding: A__ : Union[str, Any] = global_padding.upper() else: raise ValueError(F"""Padding strategy {global_padding} not supported""" ) A__ : List[Any] = num_channels A__ : str = embedding_size A__ : Tuple = hidden_sizes A__ : Optional[Any] = depths A__ : List[str] = layer_type A__ : Any = hidden_act A__ : List[Any] = global_padding A__ : str = num_groups A__ : List[str] = drop_path_rate A__ : Tuple = embedding_dynamic_padding A__ : str = output_stride A__ : Optional[int] = width_factor A__ : int = ["""stem"""] + [F"""stage{idx}""" for idx in range(1 , len(A__ ) + 1 )] A__ , A__ : Optional[int] = get_aligned_output_features_output_indices( out_features=A__ , out_indices=A__ , stage_names=self.stage_names )
141
import gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaImgaImgPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class _a (__magic_name__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__: Any = KandinskyVaaImgaImgPipeline UpperCAmelCase__: Optional[Any] = ['''image_embeds''', '''negative_image_embeds''', '''image'''] UpperCAmelCase__: str = [ '''image_embeds''', '''negative_image_embeds''', '''image''', ] UpperCAmelCase__: int = [ '''generator''', '''height''', '''width''', '''strength''', '''guidance_scale''', '''num_inference_steps''', '''return_dict''', '''guidance_scale''', '''num_images_per_prompt''', '''output_type''', '''return_dict''', ] UpperCAmelCase__: Union[str, Any] = False @property def __A ( self ): return 32 @property def __A ( self ): return 32 @property def __A ( self ): return self.time_input_dim @property def __A ( self ): return self.time_input_dim * 4 @property def __A ( self ): return 100 @property def __A ( self ): torch.manual_seed(0 ) A__ : Dict = { """in_channels""": 4, # Out channels is double in channels because predicts mean and variance """out_channels""": 8, """addition_embed_type""": """image""", """down_block_types""": ("""ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D"""), """up_block_types""": ("""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""), """mid_block_type""": """UNetMidBlock2DSimpleCrossAttn""", """block_out_channels""": (self.block_out_channels_a, self.block_out_channels_a * 2), """layers_per_block""": 1, """encoder_hid_dim""": self.text_embedder_hidden_size, """encoder_hid_dim_type""": """image_proj""", """cross_attention_dim""": self.cross_attention_dim, """attention_head_dim""": 4, """resnet_time_scale_shift""": """scale_shift""", """class_embed_type""": None, } A__ : List[str] = UNetaDConditionModel(**A__ ) return model @property def __A ( self ): return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def __A ( self ): torch.manual_seed(0 ) A__ : Tuple = VQModel(**self.dummy_movq_kwargs ) return model def __A ( self ): A__ : Optional[int] = self.dummy_unet A__ : Dict = self.dummy_movq A__ : List[Any] = { """num_train_timesteps""": 1000, """beta_schedule""": """linear""", """beta_start""": 0.0_0_0_8_5, """beta_end""": 0.0_1_2, """clip_sample""": False, """set_alpha_to_one""": False, """steps_offset""": 0, """prediction_type""": """epsilon""", """thresholding""": False, } A__ : List[str] = DDIMScheduler(**A__ ) A__ : List[str] = { """unet""": unet, """scheduler""": scheduler, """movq""": movq, } return components def __A ( self , A__ , A__=0 ): A__ : List[str] = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(A__ ) ).to(A__ ) A__ : Any = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( A__ ) # create init_image A__ : Dict = floats_tensor((1, 3, 64, 64) , rng=random.Random(A__ ) ).to(A__ ) A__ : Optional[int] = image.cpu().permute(0 , 2 , 3 , 1 )[0] A__ : Dict = Image.fromarray(np.uinta(A__ ) ).convert("""RGB""" ).resize((256, 256) ) if str(A__ ).startswith("""mps""" ): A__ : Any = torch.manual_seed(A__ ) else: A__ : List[Any] = torch.Generator(device=A__ ).manual_seed(A__ ) A__ : Optional[int] = { """image""": init_image, """image_embeds""": image_embeds, """negative_image_embeds""": negative_image_embeds, """generator""": generator, """height""": 64, """width""": 64, """num_inference_steps""": 10, """guidance_scale""": 7.0, """strength""": 0.2, """output_type""": """np""", } return inputs def __A ( self ): A__ : str = """cpu""" A__ : Any = self.get_dummy_components() A__ : Union[str, Any] = self.pipeline_class(**A__ ) A__ : List[str] = pipe.to(A__ ) pipe.set_progress_bar_config(disable=A__ ) A__ : Dict = pipe(**self.get_dummy_inputs(A__ ) ) A__ : Any = output.images A__ : List[str] = pipe( **self.get_dummy_inputs(A__ ) , return_dict=A__ , )[0] A__ : Optional[int] = image[0, -3:, -3:, -1] A__ : str = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) A__ : str = np.array( [0.6_1_9_9_7_7_8, 0.6_3_9_8_4_4_0_6, 0.4_6_1_4_5_7_8_5, 0.6_2_9_4_4_9_8_4, 0.5_6_2_2_2_1_5, 0.4_7_3_0_6_1_3_2, 0.4_7_4_4_1_4_5_6, 0.4_6_0_7_6_0_6, 0.4_8_7_1_9_2_6_3] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), F""" expected_slice {expected_slice}, but got {image_slice.flatten()}""" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), F""" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}""" @slow @require_torch_gpu class _a (unittest.TestCase ): '''simple docstring''' def __A ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __A ( self ): A__ : Optional[int] = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinskyv22/kandinskyv22_img2img_frog.npy""" ) A__ : List[Any] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/cat.png""" ) A__ : str = """A red cartoon frog, 4k""" A__ : int = KandinskyVaaPriorPipeline.from_pretrained( """kandinsky-community/kandinsky-2-2-prior""" , torch_dtype=torch.floataa ) pipe_prior.to(A__ ) A__ : List[Any] = KandinskyVaaImgaImgPipeline.from_pretrained( """kandinsky-community/kandinsky-2-2-decoder""" , torch_dtype=torch.floataa ) A__ : List[str] = pipeline.to(A__ ) pipeline.set_progress_bar_config(disable=A__ ) A__ : Tuple = torch.Generator(device="""cpu""" ).manual_seed(0 ) A__ , A__ : Optional[Any] = pipe_prior( A__ , generator=A__ , num_inference_steps=5 , negative_prompt="""""" , ).to_tuple() A__ : str = pipeline( image=A__ , image_embeds=A__ , negative_image_embeds=A__ , generator=A__ , num_inference_steps=100 , height=768 , width=768 , strength=0.2 , output_type="""np""" , ) A__ : Optional[int] = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(A__ , A__ )
141
1
from typing import TYPE_CHECKING from ..utils import _LazyModule lowerCamelCase_ = { '''config''': [ '''EXTERNAL_DATA_FORMAT_SIZE_LIMIT''', '''OnnxConfig''', '''OnnxConfigWithPast''', '''OnnxSeq2SeqConfigWithPast''', '''PatchingSpec''', ], '''convert''': ['''export''', '''validate_model_outputs'''], '''features''': ['''FeaturesManager'''], '''utils''': ['''ParameterFormat''', '''compute_serialized_parameters_size'''], } if TYPE_CHECKING: from .config import ( EXTERNAL_DATA_FORMAT_SIZE_LIMIT, OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast, PatchingSpec, ) from .convert import export, validate_model_outputs from .features import FeaturesManager from .utils import ParameterFormat, compute_serialized_parameters_size else: import sys lowerCamelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
244
from typing import Any, Callable, Dict, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker lowerCamelCase_ = '''CompVis/stable-diffusion-v1-1''' lowerCamelCase_ = '''CompVis/stable-diffusion-v1-2''' lowerCamelCase_ = '''CompVis/stable-diffusion-v1-3''' lowerCamelCase_ = '''CompVis/stable-diffusion-v1-4''' class __A( __lowerCamelCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = True , ): super()._init_() UpperCamelCase__ = StableDiffusionPipeline.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = StableDiffusionPipeline.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = StableDiffusionPipeline.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = StableDiffusionPipeline( vae=SCREAMING_SNAKE_CASE_ , text_encoder=SCREAMING_SNAKE_CASE_ , tokenizer=SCREAMING_SNAKE_CASE_ , unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ , safety_checker=SCREAMING_SNAKE_CASE_ , feature_extractor=SCREAMING_SNAKE_CASE_ , requires_safety_checker=SCREAMING_SNAKE_CASE_ , ) self.register_modules(pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea ) @property def UpperCAmelCase_ (self ): return {k: getattr(self , SCREAMING_SNAKE_CASE_ ) for k in self.config.keys() if not k.startswith("""_""" )} def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ = "auto" ): if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory UpperCamelCase__ = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): self.enable_attention_slicing(SCREAMING_SNAKE_CASE_ ) @torch.no_grad() def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 5_12 , SCREAMING_SNAKE_CASE_ = 5_12 , SCREAMING_SNAKE_CASE_ = 50 , SCREAMING_SNAKE_CASE_ = 7.5 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "pil" , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , **SCREAMING_SNAKE_CASE_ , ): return self.pipea( prompt=SCREAMING_SNAKE_CASE_ , height=SCREAMING_SNAKE_CASE_ , width=SCREAMING_SNAKE_CASE_ , num_inference_steps=SCREAMING_SNAKE_CASE_ , guidance_scale=SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ , num_images_per_prompt=SCREAMING_SNAKE_CASE_ , eta=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , latents=SCREAMING_SNAKE_CASE_ , output_type=SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ , callback=SCREAMING_SNAKE_CASE_ , callback_steps=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) @torch.no_grad() def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 5_12 , SCREAMING_SNAKE_CASE_ = 5_12 , SCREAMING_SNAKE_CASE_ = 50 , SCREAMING_SNAKE_CASE_ = 7.5 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "pil" , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , **SCREAMING_SNAKE_CASE_ , ): return self.pipea( prompt=SCREAMING_SNAKE_CASE_ , height=SCREAMING_SNAKE_CASE_ , width=SCREAMING_SNAKE_CASE_ , num_inference_steps=SCREAMING_SNAKE_CASE_ , guidance_scale=SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ , num_images_per_prompt=SCREAMING_SNAKE_CASE_ , eta=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , latents=SCREAMING_SNAKE_CASE_ , output_type=SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ , callback=SCREAMING_SNAKE_CASE_ , callback_steps=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) @torch.no_grad() def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 5_12 , SCREAMING_SNAKE_CASE_ = 5_12 , SCREAMING_SNAKE_CASE_ = 50 , SCREAMING_SNAKE_CASE_ = 7.5 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "pil" , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , **SCREAMING_SNAKE_CASE_ , ): return self.pipea( prompt=SCREAMING_SNAKE_CASE_ , height=SCREAMING_SNAKE_CASE_ , width=SCREAMING_SNAKE_CASE_ , num_inference_steps=SCREAMING_SNAKE_CASE_ , guidance_scale=SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ , num_images_per_prompt=SCREAMING_SNAKE_CASE_ , eta=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , latents=SCREAMING_SNAKE_CASE_ , output_type=SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ , callback=SCREAMING_SNAKE_CASE_ , callback_steps=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) @torch.no_grad() def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 5_12 , SCREAMING_SNAKE_CASE_ = 5_12 , SCREAMING_SNAKE_CASE_ = 50 , SCREAMING_SNAKE_CASE_ = 7.5 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "pil" , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , **SCREAMING_SNAKE_CASE_ , ): return self.pipea( prompt=SCREAMING_SNAKE_CASE_ , height=SCREAMING_SNAKE_CASE_ , width=SCREAMING_SNAKE_CASE_ , num_inference_steps=SCREAMING_SNAKE_CASE_ , guidance_scale=SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ , num_images_per_prompt=SCREAMING_SNAKE_CASE_ , eta=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , latents=SCREAMING_SNAKE_CASE_ , output_type=SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ , callback=SCREAMING_SNAKE_CASE_ , callback_steps=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) @torch.no_grad() def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 5_12 , SCREAMING_SNAKE_CASE_ = 5_12 , SCREAMING_SNAKE_CASE_ = 50 , SCREAMING_SNAKE_CASE_ = 7.5 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "pil" , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , **SCREAMING_SNAKE_CASE_ , ): UpperCamelCase__ = """cuda""" if torch.cuda.is_available() else """cpu""" self.to(SCREAMING_SNAKE_CASE_ ) # Checks if the height and width are divisible by 8 or not if height % 8 != 0 or width % 8 != 0: raise ValueError(F"`height` and `width` must be divisible by 8 but are {height} and {width}." ) # Get first result from Stable Diffusion Checkpoint v1.1 UpperCamelCase__ = self.textaimg_sda_a( prompt=SCREAMING_SNAKE_CASE_ , height=SCREAMING_SNAKE_CASE_ , width=SCREAMING_SNAKE_CASE_ , num_inference_steps=SCREAMING_SNAKE_CASE_ , guidance_scale=SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ , num_images_per_prompt=SCREAMING_SNAKE_CASE_ , eta=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , latents=SCREAMING_SNAKE_CASE_ , output_type=SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ , callback=SCREAMING_SNAKE_CASE_ , callback_steps=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) # Get first result from Stable Diffusion Checkpoint v1.2 UpperCamelCase__ = self.textaimg_sda_a( prompt=SCREAMING_SNAKE_CASE_ , height=SCREAMING_SNAKE_CASE_ , width=SCREAMING_SNAKE_CASE_ , num_inference_steps=SCREAMING_SNAKE_CASE_ , guidance_scale=SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ , num_images_per_prompt=SCREAMING_SNAKE_CASE_ , eta=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , latents=SCREAMING_SNAKE_CASE_ , output_type=SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ , callback=SCREAMING_SNAKE_CASE_ , callback_steps=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) # Get first result from Stable Diffusion Checkpoint v1.3 UpperCamelCase__ = self.textaimg_sda_a( prompt=SCREAMING_SNAKE_CASE_ , height=SCREAMING_SNAKE_CASE_ , width=SCREAMING_SNAKE_CASE_ , num_inference_steps=SCREAMING_SNAKE_CASE_ , guidance_scale=SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ , num_images_per_prompt=SCREAMING_SNAKE_CASE_ , eta=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , latents=SCREAMING_SNAKE_CASE_ , output_type=SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ , callback=SCREAMING_SNAKE_CASE_ , callback_steps=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) # Get first result from Stable Diffusion Checkpoint v1.4 UpperCamelCase__ = self.textaimg_sda_a( prompt=SCREAMING_SNAKE_CASE_ , height=SCREAMING_SNAKE_CASE_ , width=SCREAMING_SNAKE_CASE_ , num_inference_steps=SCREAMING_SNAKE_CASE_ , guidance_scale=SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ , num_images_per_prompt=SCREAMING_SNAKE_CASE_ , eta=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , latents=SCREAMING_SNAKE_CASE_ , output_type=SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ , callback=SCREAMING_SNAKE_CASE_ , callback_steps=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) # Get all result images into a single list and pass it via StableDiffusionPipelineOutput for final result return StableDiffusionPipelineOutput([resa[0], resa[0], resa[0], resa[0]] )
244
1
"""simple docstring""" import argparse import os from . import ( ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BART_PRETRAINED_MODEL_ARCHIVE_LIST, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, AlbertConfig, BartConfig, BertConfig, CamembertConfig, CTRLConfig, DistilBertConfig, DPRConfig, ElectraConfig, FlaubertConfig, GPTaConfig, LayoutLMConfig, LxmertConfig, OpenAIGPTConfig, RobertaConfig, TaConfig, TFAlbertForPreTraining, TFBartForConditionalGeneration, TFBartForSequenceClassification, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFCamembertForMaskedLM, TFCTRLLMHeadModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, TFElectraForPreTraining, TFFlaubertWithLMHeadModel, TFGPTaLMHeadModel, TFLayoutLMForMaskedLM, TFLxmertForPreTraining, TFLxmertVisualFeatureEncoder, TFOpenAIGPTLMHeadModel, TFRobertaForCausalLM, TFRobertaForMaskedLM, TFRobertaForSequenceClassification, TFTaForConditionalGeneration, TFTransfoXLLMHeadModel, TFWavaVecaModel, TFXLMRobertaForMaskedLM, TFXLMWithLMHeadModel, TFXLNetLMHeadModel, TransfoXLConfig, WavaVecaConfig, WavaVecaModel, XLMConfig, XLMRobertaConfig, XLNetConfig, is_torch_available, load_pytorch_checkpoint_in_tfa_model, ) from .utils import CONFIG_NAME, WEIGHTS_NAME, cached_file, logging if is_torch_available(): import numpy as np import torch from . import ( AlbertForPreTraining, BartForConditionalGeneration, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, CamembertForMaskedLM, CTRLLMHeadModel, DistilBertForMaskedLM, DistilBertForQuestionAnswering, DPRContextEncoder, DPRQuestionEncoder, DPRReader, ElectraForPreTraining, FlaubertWithLMHeadModel, GPTaLMHeadModel, LayoutLMForMaskedLM, LxmertForPreTraining, LxmertVisualFeatureEncoder, OpenAIGPTLMHeadModel, RobertaForMaskedLM, RobertaForSequenceClassification, TaForConditionalGeneration, TransfoXLLMHeadModel, XLMRobertaForMaskedLM, XLMWithLMHeadModel, XLNetLMHeadModel, ) logging.set_verbosity_info() __SCREAMING_SNAKE_CASE ={ "bart": ( BartConfig, TFBartForConditionalGeneration, TFBartForSequenceClassification, BartForConditionalGeneration, BART_PRETRAINED_MODEL_ARCHIVE_LIST, ), "bert": ( BertConfig, TFBertForPreTraining, BertForPreTraining, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "bert-large-uncased-whole-word-masking-finetuned-squad": ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "bert-large-cased-whole-word-masking-finetuned-squad": ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "bert-base-cased-finetuned-mrpc": ( BertConfig, TFBertForSequenceClassification, BertForSequenceClassification, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "dpr": ( DPRConfig, TFDPRQuestionEncoder, TFDPRContextEncoder, TFDPRReader, DPRQuestionEncoder, DPRContextEncoder, DPRReader, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ), "gpt2": ( GPTaConfig, TFGPTaLMHeadModel, GPTaLMHeadModel, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "xlnet": ( XLNetConfig, TFXLNetLMHeadModel, XLNetLMHeadModel, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "xlm": ( XLMConfig, TFXLMWithLMHeadModel, XLMWithLMHeadModel, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "xlm-roberta": ( XLMRobertaConfig, TFXLMRobertaForMaskedLM, XLMRobertaForMaskedLM, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "transfo-xl": ( TransfoXLConfig, TFTransfoXLLMHeadModel, TransfoXLLMHeadModel, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "openai-gpt": ( OpenAIGPTConfig, TFOpenAIGPTLMHeadModel, OpenAIGPTLMHeadModel, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "roberta": ( RobertaConfig, TFRobertaForCausalLM, TFRobertaForMaskedLM, RobertaForMaskedLM, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "layoutlm": ( LayoutLMConfig, TFLayoutLMForMaskedLM, LayoutLMForMaskedLM, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, ), "roberta-large-mnli": ( RobertaConfig, TFRobertaForSequenceClassification, RobertaForSequenceClassification, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "camembert": ( CamembertConfig, TFCamembertForMaskedLM, CamembertForMaskedLM, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "flaubert": ( FlaubertConfig, TFFlaubertWithLMHeadModel, FlaubertWithLMHeadModel, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "distilbert": ( DistilBertConfig, TFDistilBertForMaskedLM, DistilBertForMaskedLM, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "distilbert-base-distilled-squad": ( DistilBertConfig, TFDistilBertForQuestionAnswering, DistilBertForQuestionAnswering, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "lxmert": ( LxmertConfig, TFLxmertForPreTraining, LxmertForPreTraining, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "lxmert-visual-feature-encoder": ( LxmertConfig, TFLxmertVisualFeatureEncoder, LxmertVisualFeatureEncoder, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "ctrl": ( CTRLConfig, TFCTRLLMHeadModel, CTRLLMHeadModel, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "albert": ( AlbertConfig, TFAlbertForPreTraining, AlbertForPreTraining, ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "t5": ( TaConfig, TFTaForConditionalGeneration, TaForConditionalGeneration, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "electra": ( ElectraConfig, TFElectraForPreTraining, ElectraForPreTraining, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "wav2vec2": ( WavaVecaConfig, TFWavaVecaModel, WavaVecaModel, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), } def lowercase__( __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : str=False , __SCREAMING_SNAKE_CASE : Tuple=True ): if model_type not in MODEL_CLASSES: raise ValueError(F'''Unrecognized model type, should be one of {list(MODEL_CLASSES.keys() )}.''' ) lowercase_ : Tuple = MODEL_CLASSES[model_type] # Initialise TF model if config_file in aws_config_map: lowercase_ : Optional[Any] = cached_file(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , force_download=not use_cached_models ) lowercase_ : int = config_class.from_json_file(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = True lowercase_ : int = True print(F'''Building TensorFlow model from configuration: {config}''' ) lowercase_ : Union[str, Any] = model_class(__SCREAMING_SNAKE_CASE ) # Load weights from tf checkpoint if pytorch_checkpoint_path in aws_config_map.keys(): lowercase_ : Union[str, Any] = cached_file( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , force_download=not use_cached_models ) # Load PyTorch checkpoint in tf2 model: lowercase_ : List[Any] = load_pytorch_checkpoint_in_tfa_model(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if compare_with_pt_model: lowercase_ : Optional[Any] = tf_model(tf_model.dummy_inputs , training=__SCREAMING_SNAKE_CASE ) # build the network lowercase_ : List[str] = torch.load(__SCREAMING_SNAKE_CASE , map_location='cpu' ) lowercase_ : str = pt_model_class.from_pretrained( pretrained_model_name_or_path=__SCREAMING_SNAKE_CASE , config=__SCREAMING_SNAKE_CASE , state_dict=__SCREAMING_SNAKE_CASE ) with torch.no_grad(): lowercase_ : List[Any] = pt_model(**pt_model.dummy_inputs ) lowercase_ : Optional[int] = pto[0].numpy() lowercase_ : Optional[Any] = tfo[0].numpy() lowercase_ : str = np.amax(np.abs(np_pt - np_tf ) ) print(F'''Max absolute difference between models outputs {diff}''' ) assert diff <= 2E-2, F'''Error, model absolute difference is >2e-2: {diff}''' # Save pytorch-model print(F'''Save TensorFlow model to {tf_dump_path}''' ) tf_model.save_weights(__SCREAMING_SNAKE_CASE , save_format='h5' ) def lowercase__( __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : str=None , __SCREAMING_SNAKE_CASE : Any=None , __SCREAMING_SNAKE_CASE : Union[str, Any]=False , __SCREAMING_SNAKE_CASE : int=False , __SCREAMING_SNAKE_CASE : List[Any]=False , __SCREAMING_SNAKE_CASE : Dict=False , ): if args_model_type is None: lowercase_ : Dict = list(MODEL_CLASSES.keys() ) else: lowercase_ : Optional[int] = [args_model_type] for j, model_type in enumerate(__SCREAMING_SNAKE_CASE , start=1 ): print('=' * 1_00 ) print(F''' Converting model type {j}/{len(__SCREAMING_SNAKE_CASE )}: {model_type}''' ) print('=' * 1_00 ) if model_type not in MODEL_CLASSES: raise ValueError(F'''Unrecognized model type {model_type}, should be one of {list(MODEL_CLASSES.keys() )}.''' ) lowercase_ : List[Any] = MODEL_CLASSES[model_type] if model_shortcut_names_or_path is None: lowercase_ : str = list(aws_model_maps.keys() ) if config_shortcut_names_or_path is None: lowercase_ : Any = model_shortcut_names_or_path for i, (model_shortcut_name, config_shortcut_name) in enumerate( zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , start=1 ): print('-' * 1_00 ) if "-squad" in model_shortcut_name or "-mrpc" in model_shortcut_name or "-mnli" in model_shortcut_name: if not only_convert_finetuned_models: print(F''' Skipping finetuned checkpoint {model_shortcut_name}''' ) continue lowercase_ : Any = model_shortcut_name elif only_convert_finetuned_models: print(F''' Skipping not finetuned checkpoint {model_shortcut_name}''' ) continue print( F''' Converting checkpoint {i}/{len(__SCREAMING_SNAKE_CASE )}: {model_shortcut_name} - model_type {model_type}''' ) print('-' * 1_00 ) if config_shortcut_name in aws_config_map: lowercase_ : Dict = cached_file(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , force_download=not use_cached_models ) else: lowercase_ : Optional[int] = config_shortcut_name if model_shortcut_name in aws_model_maps: lowercase_ : Optional[int] = cached_file(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , force_download=not use_cached_models ) else: lowercase_ : Any = model_shortcut_name if os.path.isfile(__SCREAMING_SNAKE_CASE ): lowercase_ : Union[str, Any] = 'converted_model' convert_pt_checkpoint_to_tf( model_type=__SCREAMING_SNAKE_CASE , pytorch_checkpoint_path=__SCREAMING_SNAKE_CASE , config_file=__SCREAMING_SNAKE_CASE , tf_dump_path=os.path.join(__SCREAMING_SNAKE_CASE , model_shortcut_name + '-tf_model.h5' ) , compare_with_pt_model=__SCREAMING_SNAKE_CASE , ) if remove_cached_files: os.remove(__SCREAMING_SNAKE_CASE ) os.remove(__SCREAMING_SNAKE_CASE ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE =argparse.ArgumentParser() # Required parameters parser.add_argument( "--tf_dump_path", default=None, type=str, required=True, help="Path to the output Tensorflow dump file." ) parser.add_argument( "--model_type", default=None, type=str, help=( F"Model type selected in the list of {list(MODEL_CLASSES.keys())}. If not given, will download and " "convert all the models from AWS." ), ) parser.add_argument( "--pytorch_checkpoint_path", default=None, type=str, help=( "Path to the PyTorch checkpoint path or shortcut name to download from AWS. " "If not given, will download and convert all the checkpoints from AWS." ), ) parser.add_argument( "--config_file", default=None, type=str, help=( "The config json file corresponding to the pre-trained model. \n" "This specifies the model architecture. If not given and " "--pytorch_checkpoint_path is not given or is a shortcut name " "use the configuration associated to the shortcut name on the AWS" ), ) parser.add_argument( "--compare_with_pt_model", action="store_true", help="Compare Tensorflow and PyTorch model predictions." ) parser.add_argument( "--use_cached_models", action="store_true", help="Use cached models if possible instead of updating to latest checkpoint versions.", ) parser.add_argument( "--remove_cached_files", action="store_true", help="Remove pytorch models after conversion (save memory when converting in batches).", ) parser.add_argument("--only_convert_finetuned_models", action="store_true", help="Only convert finetuned models.") __SCREAMING_SNAKE_CASE =parser.parse_args() # if args.pytorch_checkpoint_path is not None: # convert_pt_checkpoint_to_tf(args.model_type.lower(), # args.pytorch_checkpoint_path, # args.config_file if args.config_file is not None else args.pytorch_checkpoint_path, # args.tf_dump_path, # compare_with_pt_model=args.compare_with_pt_model, # use_cached_models=args.use_cached_models) # else: convert_all_pt_checkpoints_to_tf( args.model_type.lower() if args.model_type is not None else None, args.tf_dump_path, model_shortcut_names_or_path=[args.pytorch_checkpoint_path] if args.pytorch_checkpoint_path is not None else None, config_shortcut_names_or_path=[args.config_file] if args.config_file is not None else None, compare_with_pt_model=args.compare_with_pt_model, use_cached_models=args.use_cached_models, remove_cached_files=args.remove_cached_files, only_convert_finetuned_models=args.only_convert_finetuned_models, )
357
"""simple docstring""" def lowercase__( __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : list[int] , __SCREAMING_SNAKE_CASE : int ): def count_of_possible_combinations(__SCREAMING_SNAKE_CASE : int ) -> int: if target < 0: return 0 if target == 0: return 1 return sum(count_of_possible_combinations(target - item ) for item in array ) return count_of_possible_combinations(__SCREAMING_SNAKE_CASE ) def lowercase__( __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : list[int] , __SCREAMING_SNAKE_CASE : int ): def count_of_possible_combinations_with_dp_array( __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : list[int] ) -> int: if target < 0: return 0 if target == 0: return 1 if dp_array[target] != -1: return dp_array[target] lowercase_ : str = sum( count_of_possible_combinations_with_dp_array(target - item , __SCREAMING_SNAKE_CASE ) for item in array ) lowercase_ : Tuple = answer return answer lowercase_ : Optional[Any] = [-1] * (target + 1) return count_of_possible_combinations_with_dp_array(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def lowercase__( __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : list[int] , __SCREAMING_SNAKE_CASE : int ): lowercase_ : Dict = [0] * (target + 1) lowercase_ : Dict = 1 for i in range(1 , target + 1 ): for j in range(__SCREAMING_SNAKE_CASE ): if i - array[j] >= 0: dp_array[i] += dp_array[i - array[j]] return dp_array[target] if __name__ == "__main__": import doctest doctest.testmod() __SCREAMING_SNAKE_CASE =3 __SCREAMING_SNAKE_CASE =5 __SCREAMING_SNAKE_CASE =[1, 2, 5] print(combination_sum_iv(n, array, target))
321
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) __snake_case = { '''configuration_owlvit''': [ '''OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''OwlViTConfig''', '''OwlViTOnnxConfig''', '''OwlViTTextConfig''', '''OwlViTVisionConfig''', ], '''processing_owlvit''': ['''OwlViTProcessor'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = ['''OwlViTFeatureExtractor'''] __snake_case = ['''OwlViTImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = [ '''OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''OwlViTModel''', '''OwlViTPreTrainedModel''', '''OwlViTTextModel''', '''OwlViTVisionModel''', '''OwlViTForObjectDetection''', ] if TYPE_CHECKING: from .configuration_owlvit import ( OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, OwlViTConfig, OwlViTOnnxConfig, OwlViTTextConfig, OwlViTVisionConfig, ) from .processing_owlvit import OwlViTProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_owlvit import OwlViTFeatureExtractor from .image_processing_owlvit import OwlViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_owlvit import ( OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST, OwlViTForObjectDetection, OwlViTModel, OwlViTPreTrainedModel, OwlViTTextModel, OwlViTVisionModel, ) else: import sys __snake_case = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
97
'''simple docstring''' import importlib.metadata import operator import re import sys from typing import Optional from packaging import version lowercase_ = { """<""": operator.lt, """<=""": operator.le, """==""": operator.eq, """!=""": operator.ne, """>=""": operator.ge, """>""": operator.gt, } def lowerCamelCase ( __lowerCamelCase : Tuple , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Dict , __lowerCamelCase : List[Any] , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[Any] ) ->Tuple: if got_ver is None or want_ver is None: raise ValueError( F'Unable to compare versions for {requirement}: need={want_ver} found={got_ver}. This is unusual. Consider' F' reinstalling {pkg}.' ) if not ops[op](version.parse(__lowerCamelCase ) , version.parse(__lowerCamelCase ) ): raise ImportError( F'{requirement} is required for a normal functioning of this module, but found {pkg}=={got_ver}.{hint}' ) def lowerCamelCase ( __lowerCamelCase : str , __lowerCamelCase : Optional[str] = None ) ->None: _SCREAMING_SNAKE_CASE = F'\n{hint}' if hint is not None else """""" # non-versioned check if re.match(R"""^[\w_\-\d]+$""" , __lowerCamelCase ): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = requirement, None, None else: _SCREAMING_SNAKE_CASE = re.findall(R"""^([^!=<>\s]+)([\s!=<>]{1,2}.+)""" , __lowerCamelCase ) if not match: raise ValueError( """requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23, but""" F' got {requirement}' ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = match[0] _SCREAMING_SNAKE_CASE = want_full.split(""",""" ) # there could be multiple requirements _SCREAMING_SNAKE_CASE = {} for w in want_range: _SCREAMING_SNAKE_CASE = re.findall(R"""^([\s!=<>]{1,2})(.+)""" , __lowerCamelCase ) if not match: raise ValueError( """requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23,""" F' but got {requirement}' ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = match[0] _SCREAMING_SNAKE_CASE = want_ver if op not in ops: raise ValueError(F'{requirement}: need one of {list(ops.keys() )}, but got {op}' ) # special case if pkg == "python": _SCREAMING_SNAKE_CASE = """.""".join([str(__lowerCamelCase ) for x in sys.version_info[:3]] ) for op, want_ver in wanted.items(): _compare_versions(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) return # check if any version is installed try: _SCREAMING_SNAKE_CASE = importlib.metadata.version(__lowerCamelCase ) except importlib.metadata.PackageNotFoundError: raise importlib.metadata.PackageNotFoundError( F'The \'{requirement}\' distribution was not found and is required by this application. {hint}' ) # check that the right version is installed if version number or a range was provided if want_ver is not None: for op, want_ver in wanted.items(): _compare_versions(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) def lowerCamelCase ( __lowerCamelCase : Union[str, Any] ) ->str: _SCREAMING_SNAKE_CASE = """Try: pip install transformers -U or pip install -e '.[dev]' if you're working with git main""" return require_version(__lowerCamelCase , __lowerCamelCase )
58
0
import json import os import unittest from transformers.models.gptsan_japanese.tokenization_gptsan_japanese import ( VOCAB_FILES_NAMES, GPTSanJapaneseTokenizer, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class A ( UpperCAmelCase_ , unittest.TestCase ): __UpperCAmelCase : Union[str, Any] = GPTSanJapaneseTokenizer __UpperCAmelCase : Dict = False __UpperCAmelCase : List[str] = {'do_clean_text': False, 'add_prefix_space': False} def lowercase_ (self : Dict ) -> Union[str, Any]: """simple docstring""" super().setUp() # fmt: off UpperCAmelCase__ = ["こん", "こんに", "にちは", "ばんは", "世界,㔺界", "、", "。", "<BR>", "<SP>", "<TAB>", "<URL>", "<EMAIL>", "<TEL>", "<DATE>", "<PRICE>", "<BLOCK>", "<KIGOU>", "<U2000U2BFF>", "<|emoji1|>", "<unk>", "<|bagoftoken|>", "<|endoftext|>"] # fmt: on UpperCAmelCase__ = {"emoji": {"\ud83d\ude00": "<|emoji1|>"}, "emoji_inv": {"<|emoji1|>": "\ud83d\ude00"}} # 😀 UpperCAmelCase__ = {"unk_token": "<unk>"} UpperCAmelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) UpperCAmelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["emoji_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) with open(self.emoji_file , "w" ) as emoji_writer: emoji_writer.write(json.dumps(__UpperCAmelCase ) ) def lowercase_ (self : List[str] , **__UpperCAmelCase : Union[str, Any] ) -> List[str]: """simple docstring""" kwargs.update(self.special_tokens_map ) return GPTSanJapaneseTokenizer.from_pretrained(self.tmpdirname , **__UpperCAmelCase ) def lowercase_ (self : Dict , __UpperCAmelCase : Any ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase__ = "こんにちは、世界。 \nこんばんは、㔺界。😀" UpperCAmelCase__ = "こんにちは、世界。 \nこんばんは、世界。😀" return input_text, output_text def lowercase_ (self : str , __UpperCAmelCase : Tuple ) -> List[Any]: """simple docstring""" UpperCAmelCase__ , UpperCAmelCase__ = self.get_input_output_texts(__UpperCAmelCase ) UpperCAmelCase__ = tokenizer.encode(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase ) UpperCAmelCase__ = tokenizer.decode(__UpperCAmelCase , clean_up_tokenization_spaces=__UpperCAmelCase ) return text, ids def lowercase_ (self : Union[str, Any] ) -> List[Any]: """simple docstring""" pass # TODO add if relevant def lowercase_ (self : Optional[Any] ) -> int: """simple docstring""" pass # TODO add if relevant def lowercase_ (self : List[Any] ) -> Optional[Any]: """simple docstring""" pass # TODO add if relevant def lowercase_ (self : List[str] ) -> str: """simple docstring""" UpperCAmelCase__ = self.get_tokenizer() # Testing tokenization UpperCAmelCase__ = "こんにちは、世界。 こんばんは、㔺界。" UpperCAmelCase__ = ["こん", "にちは", "、", "世界", "。", "<SP>", "こん", "ばんは", "、", "㔺界", "。"] UpperCAmelCase__ = tokenizer.tokenize(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) # Testing conversion to ids without special tokens UpperCAmelCase__ = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6] UpperCAmelCase__ = tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) # Testing conversion to ids with special tokens UpperCAmelCase__ = tokens + [tokenizer.unk_token] UpperCAmelCase__ = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6, 1_9] UpperCAmelCase__ = tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) def lowercase_ (self : List[str] ) -> List[Any]: """simple docstring""" UpperCAmelCase__ = self.get_tokenizer() # Testing tokenization UpperCAmelCase__ = "こんにちは、<|bagoftoken|>世界。こんばんは、<|bagoftoken|>㔺界。" UpperCAmelCase__ = "こんにちは、、、、世界。こんばんは、、、、世界。" UpperCAmelCase__ = tokenizer.encode(__UpperCAmelCase ) UpperCAmelCase__ = tokenizer.decode(__UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) @slow def lowercase_ (self : str ) -> Tuple: """simple docstring""" UpperCAmelCase__ = self.tokenizer_class.from_pretrained("Tanrei/GPTSAN-japanese" ) # Testing tokenization UpperCAmelCase__ = "こんにちは、世界。" UpperCAmelCase__ = "こんばんは、㔺界。😀" UpperCAmelCase__ = "こんにちは、世界。こんばんは、世界。😀" UpperCAmelCase__ = tokenizer.encode(prefix_text + input_text ) UpperCAmelCase__ = tokenizer.encode("" , prefix_text=prefix_text + input_text ) UpperCAmelCase__ = tokenizer.encode(__UpperCAmelCase , prefix_text=__UpperCAmelCase ) UpperCAmelCase__ = tokenizer.decode(__UpperCAmelCase ) UpperCAmelCase__ = tokenizer.decode(__UpperCAmelCase ) UpperCAmelCase__ = tokenizer.decode(__UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) @slow def lowercase_ (self : int ) -> Optional[Any]: """simple docstring""" UpperCAmelCase__ = self.tokenizer_class.from_pretrained("Tanrei/GPTSAN-japanese" ) # Testing tokenization UpperCAmelCase__ = "こんにちは、世界。" UpperCAmelCase__ = "こんばんは、㔺界。😀" UpperCAmelCase__ = len(tokenizer.encode(__UpperCAmelCase ) ) - 2 UpperCAmelCase__ = len(tokenizer.encode(__UpperCAmelCase ) ) - 2 UpperCAmelCase__ = [1] + [0] * (len_prefix + len_text + 1) UpperCAmelCase__ = [1] * (len_prefix + len_text + 1) + [0] UpperCAmelCase__ = [1] + [1] * (len_prefix) + [0] * (len_text + 1) UpperCAmelCase__ = tokenizer(prefix_text + input_text ).token_type_ids UpperCAmelCase__ = tokenizer("" , prefix_text=prefix_text + input_text ).token_type_ids UpperCAmelCase__ = tokenizer(__UpperCAmelCase , prefix_text=__UpperCAmelCase ).token_type_ids self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) @slow def lowercase_ (self : Optional[int] ) -> Optional[Any]: """simple docstring""" UpperCAmelCase__ = self.tokenizer_class.from_pretrained("Tanrei/GPTSAN-japanese" ) UpperCAmelCase__ = tokenizer.encode("あンいワ" ) UpperCAmelCase__ = tokenizer.encode("" , prefix_text="あンいワ" ) UpperCAmelCase__ = tokenizer.encode("いワ" , prefix_text="あン" ) self.assertEqual(tokenizer.decode(__UpperCAmelCase ) , tokenizer.decode(__UpperCAmelCase ) ) self.assertEqual(tokenizer.decode(__UpperCAmelCase ) , tokenizer.decode(__UpperCAmelCase ) ) self.assertNotEqual(__UpperCAmelCase , __UpperCAmelCase ) self.assertNotEqual(__UpperCAmelCase , __UpperCAmelCase ) self.assertEqual(x_token_a[1] , x_token_a[-1] ) # SEG token self.assertEqual(x_token_a[1] , x_token_a[3] ) # SEG token @slow def lowercase_ (self : int ) -> int: """simple docstring""" UpperCAmelCase__ = self.tokenizer_class.from_pretrained("Tanrei/GPTSAN-japanese" ) UpperCAmelCase__ = [["武田信玄", "は、"], ["織田信長", "の配下の、"]] UpperCAmelCase__ = tokenizer(__UpperCAmelCase , padding=__UpperCAmelCase ) UpperCAmelCase__ = tokenizer.batch_encode_plus(__UpperCAmelCase , padding=__UpperCAmelCase ) # fmt: off UpperCAmelCase__ = [[3_5_9_9_3, 8_6_4_0, 2_5_9_4_8, 3_5_9_9_8, 3_0_6_4_7, 3_5_6_7_5, 3_5_9_9_9, 3_5_9_9_9], [3_5_9_9_3, 1_0_3_8_2, 9_8_6_8, 3_5_9_9_8, 3_0_6_4_6, 9_4_5_9, 3_0_6_4_6, 3_5_6_7_5]] UpperCAmelCase__ = [[1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0]] UpperCAmelCase__ = [[1, 1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1]] # fmt: on self.assertListEqual(x_token.input_ids , __UpperCAmelCase ) self.assertListEqual(x_token.token_type_ids , __UpperCAmelCase ) self.assertListEqual(x_token.attention_mask , __UpperCAmelCase ) self.assertListEqual(x_token_a.input_ids , __UpperCAmelCase ) self.assertListEqual(x_token_a.token_type_ids , __UpperCAmelCase ) self.assertListEqual(x_token_a.attention_mask , __UpperCAmelCase ) def lowercase_ (self : Optional[int] ) -> Any: """simple docstring""" pass def lowercase_ (self : List[str] ) -> str: """simple docstring""" pass
367
from __future__ import annotations import unittest from transformers import DistilBertConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.distilbert.modeling_tf_distilbert import ( TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDistilBertForMaskedLM, TFDistilBertForMultipleChoice, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertModel, ) class A : def __init__(self : Tuple , __UpperCAmelCase : str , ) -> Dict: """simple docstring""" UpperCAmelCase__ = parent UpperCAmelCase__ = 1_3 UpperCAmelCase__ = 7 UpperCAmelCase__ = True UpperCAmelCase__ = True UpperCAmelCase__ = False UpperCAmelCase__ = True UpperCAmelCase__ = 9_9 UpperCAmelCase__ = 3_2 UpperCAmelCase__ = 2 UpperCAmelCase__ = 4 UpperCAmelCase__ = 3_7 UpperCAmelCase__ = "gelu" UpperCAmelCase__ = 0.1 UpperCAmelCase__ = 0.1 UpperCAmelCase__ = 5_1_2 UpperCAmelCase__ = 1_6 UpperCAmelCase__ = 2 UpperCAmelCase__ = 0.02 UpperCAmelCase__ = 3 UpperCAmelCase__ = 4 UpperCAmelCase__ = None def lowercase_ (self : int ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCAmelCase__ = None if self.use_input_mask: UpperCAmelCase__ = random_attention_mask([self.batch_size, self.seq_length] ) UpperCAmelCase__ = None UpperCAmelCase__ = None UpperCAmelCase__ = None if self.use_labels: UpperCAmelCase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCAmelCase__ = ids_tensor([self.batch_size] , self.num_choices ) UpperCAmelCase__ = DistilBertConfig( vocab_size=self.vocab_size , dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , hidden_dim=self.intermediate_size , hidden_act=self.hidden_act , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , ) return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def lowercase_ (self : int , __UpperCAmelCase : int , __UpperCAmelCase : Tuple , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Tuple , __UpperCAmelCase : Tuple ) -> Tuple: """simple docstring""" UpperCAmelCase__ = TFDistilBertModel(config=__UpperCAmelCase ) UpperCAmelCase__ = {"input_ids": input_ids, "attention_mask": input_mask} UpperCAmelCase__ = model(__UpperCAmelCase ) UpperCAmelCase__ = [input_ids, input_mask] UpperCAmelCase__ = model(__UpperCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowercase_ (self : str , __UpperCAmelCase : int , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : List[Any] , __UpperCAmelCase : Any , __UpperCAmelCase : Dict ) -> List[Any]: """simple docstring""" UpperCAmelCase__ = TFDistilBertForMaskedLM(config=__UpperCAmelCase ) UpperCAmelCase__ = {"input_ids": input_ids, "attention_mask": input_mask} UpperCAmelCase__ = model(__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowercase_ (self : int , __UpperCAmelCase : Dict , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : str , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : List[Any] , __UpperCAmelCase : List[str] ) -> List[Any]: """simple docstring""" UpperCAmelCase__ = TFDistilBertForQuestionAnswering(config=__UpperCAmelCase ) UpperCAmelCase__ = { "input_ids": input_ids, "attention_mask": input_mask, } UpperCAmelCase__ = model(__UpperCAmelCase ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def lowercase_ (self : Optional[int] , __UpperCAmelCase : str , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : List[str] , __UpperCAmelCase : Dict , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : List[str] ) -> str: """simple docstring""" UpperCAmelCase__ = self.num_labels UpperCAmelCase__ = TFDistilBertForSequenceClassification(__UpperCAmelCase ) UpperCAmelCase__ = {"input_ids": input_ids, "attention_mask": input_mask} UpperCAmelCase__ = model(__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowercase_ (self : Optional[int] , __UpperCAmelCase : List[Any] , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Dict , __UpperCAmelCase : List[Any] , __UpperCAmelCase : str , __UpperCAmelCase : Any ) -> int: """simple docstring""" UpperCAmelCase__ = self.num_choices UpperCAmelCase__ = TFDistilBertForMultipleChoice(__UpperCAmelCase ) UpperCAmelCase__ = tf.tile(tf.expand_dims(__UpperCAmelCase , 1 ) , (1, self.num_choices, 1) ) UpperCAmelCase__ = tf.tile(tf.expand_dims(__UpperCAmelCase , 1 ) , (1, self.num_choices, 1) ) UpperCAmelCase__ = { "input_ids": multiple_choice_inputs_ids, "attention_mask": multiple_choice_input_mask, } UpperCAmelCase__ = model(__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def lowercase_ (self : Dict , __UpperCAmelCase : Tuple , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : Tuple , __UpperCAmelCase : List[str] , __UpperCAmelCase : Any , __UpperCAmelCase : Optional[int] ) -> List[Any]: """simple docstring""" UpperCAmelCase__ = self.num_labels UpperCAmelCase__ = TFDistilBertForTokenClassification(__UpperCAmelCase ) UpperCAmelCase__ = {"input_ids": input_ids, "attention_mask": input_mask} UpperCAmelCase__ = model(__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowercase_ (self : Any ) -> Dict: """simple docstring""" UpperCAmelCase__ = self.prepare_config_and_inputs() ((UpperCAmelCase__) , (UpperCAmelCase__) , (UpperCAmelCase__) , (UpperCAmelCase__) , (UpperCAmelCase__) , (UpperCAmelCase__)) = config_and_inputs UpperCAmelCase__ = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_tf class A ( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase ): __UpperCAmelCase : Union[str, Any] = ( ( TFDistilBertModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertForMultipleChoice, ) if is_tf_available() else None ) __UpperCAmelCase : Optional[int] = ( { 'feature-extraction': TFDistilBertModel, 'fill-mask': TFDistilBertForMaskedLM, 'question-answering': TFDistilBertForQuestionAnswering, 'text-classification': TFDistilBertForSequenceClassification, 'token-classification': TFDistilBertForTokenClassification, 'zero-shot': TFDistilBertForSequenceClassification, } if is_tf_available() else {} ) __UpperCAmelCase : Tuple = False __UpperCAmelCase : str = False def lowercase_ (self : Union[str, Any] ) -> str: """simple docstring""" UpperCAmelCase__ = TFDistilBertModelTester(self ) UpperCAmelCase__ = ConfigTester(self , config_class=__UpperCAmelCase , dim=3_7 ) def lowercase_ (self : Any ) -> int: """simple docstring""" self.config_tester.run_common_tests() def lowercase_ (self : int ) -> int: """simple docstring""" UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_model(*__UpperCAmelCase ) def lowercase_ (self : Optional[int] ) -> int: """simple docstring""" UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_masked_lm(*__UpperCAmelCase ) def lowercase_ (self : Any ) -> Optional[int]: """simple docstring""" UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_question_answering(*__UpperCAmelCase ) def lowercase_ (self : List[str] ) -> str: """simple docstring""" UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_sequence_classification(*__UpperCAmelCase ) def lowercase_ (self : Dict ) -> List[str]: """simple docstring""" UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_multiple_choice(*__UpperCAmelCase ) def lowercase_ (self : str ) -> List[Any]: """simple docstring""" UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_token_classification(*__UpperCAmelCase ) @slow def lowercase_ (self : Optional[int] ) -> Optional[int]: """simple docstring""" for model_name in list(TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1] ): UpperCAmelCase__ = TFDistilBertModel.from_pretrained(__UpperCAmelCase ) self.assertIsNotNone(__UpperCAmelCase ) @require_tf class A ( unittest.TestCase ): @slow def lowercase_ (self : List[Any] ) -> Dict: """simple docstring""" UpperCAmelCase__ = TFDistilBertModel.from_pretrained("distilbert-base-uncased" ) UpperCAmelCase__ = tf.constant([[0, 1, 2, 3, 4, 5]] ) UpperCAmelCase__ = model(__UpperCAmelCase )[0] UpperCAmelCase__ = [1, 6, 7_6_8] self.assertEqual(output.shape , __UpperCAmelCase ) UpperCAmelCase__ = tf.constant( [ [ [0.19261885, -0.13732955, 0.4119799], [0.22150156, -0.07422661, 0.39037204], [0.22756018, -0.0896414, 0.3701467], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , __UpperCAmelCase , atol=1E-4 )
143
0
"""simple docstring""" import json import os import re import sys import urllib.request import requests from bsa import BeautifulSoup lowerCamelCase_ = { '''User-Agent''': '''Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36''' ''' (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582''' } def snake_case ( A__ = "dhaka" ,A__ = 5 ): UpperCAmelCase_ : List[str] = min(__A ,50 ) # Prevent abuse! UpperCAmelCase_ : List[str] = { "q": query, "tbm": "isch", "hl": "en", "ijn": "0", } UpperCAmelCase_ : Optional[Any] = requests.get("https://www.google.com/search" ,params=__A ,headers=__A ) UpperCAmelCase_ : str = BeautifulSoup(html.text ,"html.parser" ) UpperCAmelCase_ : Any = "".join( re.findall(r"AF_initDataCallback\(([^<]+)\);" ,str(soup.select("script" ) ) ) ) UpperCAmelCase_ : List[Any] = json.dumps(__A ) UpperCAmelCase_ : str = json.loads(__A ) UpperCAmelCase_ : List[str] = re.findall( r"\[\"GRID_STATE0\",null,\[\[1,\[0,\".*?\",(.*),\"All\"," ,__A ,) if not matched_google_image_data: return 0 UpperCAmelCase_ : str = re.sub( r"\[\"(https\:\/\/encrypted-tbn0\.gstatic\.com\/images\?.*?)\",\d+,\d+\]" ,"" ,str(__A ) ,) UpperCAmelCase_ : int = re.findall( r"(?:'|,),\[\"(https:|http.*?)\",\d+,\d+\]" ,__A ,) for index, fixed_full_res_image in enumerate(__A ): if index >= max_images: return index UpperCAmelCase_ : List[str] = bytes(__A ,"ascii" ).decode( "unicode-escape" ) UpperCAmelCase_ : List[Any] = bytes(__A ,"ascii" ).decode( "unicode-escape" ) UpperCAmelCase_ : List[str] = urllib.request.build_opener() UpperCAmelCase_ : Any = [ ( "User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" " (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582", ) ] urllib.request.install_opener(__A ) UpperCAmelCase_ : int = F"""query_{query.replace(' ' ,'_' )}""" if not os.path.exists(__A ): os.makedirs(__A ) urllib.request.urlretrieve( # noqa: S310 __A ,F"""{path_name}/original_size_img_{index}.jpg""" ) return index if __name__ == "__main__": try: lowerCamelCase_ = download_images_from_google_query(sys.argv[1]) print(f'{image_count} images were downloaded to disk.') except IndexError: print('''Please provide a search term.''') raise
268
import inspect import os import unittest import torch import accelerate from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_multi_gpu from accelerate.utils import patch_environment class A ( unittest.TestCase ): def lowercase_ (self : Union[str, Any] ) -> str: """simple docstring""" UpperCAmelCase__ = inspect.getfile(accelerate.test_utils ) UpperCAmelCase__ = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ["scripts", "test_script.py"] ) UpperCAmelCase__ = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ["scripts", "test_distributed_data_loop.py"] ) UpperCAmelCase__ = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ["scripts", "test_ops.py"] ) @require_multi_gpu def lowercase_ (self : List[str] ) -> Any: """simple docstring""" print(f"""Found {torch.cuda.device_count()} devices.""" ) UpperCAmelCase__ = ["torchrun", f"""--nproc_per_node={torch.cuda.device_count()}""", self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__UpperCAmelCase , env=os.environ.copy() ) @require_multi_gpu def lowercase_ (self : str ) -> str: """simple docstring""" print(f"""Found {torch.cuda.device_count()} devices.""" ) UpperCAmelCase__ = ["torchrun", f"""--nproc_per_node={torch.cuda.device_count()}""", self.operation_file_path] print(f"""Command: {cmd}""" ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__UpperCAmelCase , env=os.environ.copy() ) @require_multi_gpu def lowercase_ (self : Tuple ) -> int: """simple docstring""" UpperCAmelCase__ = ["torchrun", f"""--nproc_per_node={torch.cuda.device_count()}""", inspect.getfile(self.__class__ )] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__UpperCAmelCase , env=os.environ.copy() ) @require_multi_gpu def lowercase_ (self : Dict ) -> str: """simple docstring""" print(f"""Found {torch.cuda.device_count()} devices, using 2 devices only""" ) UpperCAmelCase__ = ["torchrun", f"""--nproc_per_node={torch.cuda.device_count()}""", self.data_loop_file_path] with patch_environment(omp_num_threads=1 , cuda_visible_devices="0,1" ): execute_subprocess_async(__UpperCAmelCase , env=os.environ.copy() ) if __name__ == "__main__": UpperCamelCase__ = Accelerator() UpperCamelCase__ = (accelerator.state.process_index + 2, 1_0) UpperCamelCase__ = torch.randint(0, 1_0, shape).to(accelerator.device) UpperCamelCase__ = '' UpperCamelCase__ = accelerator.pad_across_processes(tensor) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0): error_msg += "Padding was not done with the right value (0)." UpperCamelCase__ = accelerator.pad_across_processes(tensor, pad_first=True) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." UpperCamelCase__ = accelerator.state.num_processes - accelerator.state.process_index - 1 if not torch.equal(tensora[index:], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[:index] == 0): error_msg += "Padding was not done with the right value (0)." # Raise error at the end to make sure we don't stop at the first failure. if len(error_msg) > 0: raise ValueError(error_msg)
65
0
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DetaImageProcessor class SCREAMING_SNAKE_CASE ( unittest.TestCase ): """simple docstring""" def __init__( self : List[Any] , lowerCAmelCase : Dict , lowerCAmelCase : Any=7 , lowerCAmelCase : Any=3 , lowerCAmelCase : List[str]=30 , lowerCAmelCase : List[str]=4_00 , lowerCAmelCase : Any=True , lowerCAmelCase : Dict=None , lowerCAmelCase : List[str]=True , lowerCAmelCase : Optional[Any]=[0.5, 0.5, 0.5] , lowerCAmelCase : Any=[0.5, 0.5, 0.5] , lowerCAmelCase : Optional[Any]=True , lowerCAmelCase : int=1 / 2_55 , lowerCAmelCase : int=True , ) -> Optional[int]: """simple docstring""" __lowerCAmelCase : Tuple = size if size is not None else {"""shortest_edge""": 18, """longest_edge""": 13_33} __lowerCAmelCase : int = parent __lowerCAmelCase : str = batch_size __lowerCAmelCase : Optional[int] = num_channels __lowerCAmelCase : Tuple = min_resolution __lowerCAmelCase : Optional[int] = max_resolution __lowerCAmelCase : Optional[int] = do_resize __lowerCAmelCase : Optional[Any] = size __lowerCAmelCase : Optional[Any] = do_normalize __lowerCAmelCase : List[Any] = image_mean __lowerCAmelCase : Dict = image_std __lowerCAmelCase : Optional[int] = do_rescale __lowerCAmelCase : Any = rescale_factor __lowerCAmelCase : List[Any] = do_pad def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Optional[int]: """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def SCREAMING_SNAKE_CASE ( self : Dict , lowerCAmelCase : Dict , lowerCAmelCase : str=False ) -> int: """simple docstring""" if not batched: __lowerCAmelCase : Optional[int] = image_inputs[0] if isinstance(lowerCAmelCase , Image.Image ): __lowerCAmelCase ,__lowerCAmelCase : Any = image.size else: __lowerCAmelCase ,__lowerCAmelCase : Optional[int] = image.shape[1], image.shape[2] if w < h: __lowerCAmelCase : Optional[Any] = int(self.size["""shortest_edge"""] * h / w ) __lowerCAmelCase : Tuple = self.size["""shortest_edge"""] elif w > h: __lowerCAmelCase : Any = self.size["""shortest_edge"""] __lowerCAmelCase : int = int(self.size["""shortest_edge"""] * w / h ) else: __lowerCAmelCase : List[str] = self.size["""shortest_edge"""] __lowerCAmelCase : Union[str, Any] = self.size["""shortest_edge"""] else: __lowerCAmelCase : int = [] for image in image_inputs: __lowerCAmelCase ,__lowerCAmelCase : int = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __lowerCAmelCase : Dict = max(lowerCAmelCase , key=lambda lowerCAmelCase : item[0] )[0] __lowerCAmelCase : Optional[int] = max(lowerCAmelCase , key=lambda lowerCAmelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class SCREAMING_SNAKE_CASE ( a_ , unittest.TestCase ): """simple docstring""" lowerCamelCase : Union[str, Any] =DetaImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> str: """simple docstring""" __lowerCAmelCase : int = DetaImageProcessingTester(self ) @property def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[Any]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: """simple docstring""" __lowerCAmelCase : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowerCAmelCase , """image_mean""" ) ) self.assertTrue(hasattr(lowerCAmelCase , """image_std""" ) ) self.assertTrue(hasattr(lowerCAmelCase , """do_normalize""" ) ) self.assertTrue(hasattr(lowerCAmelCase , """do_resize""" ) ) self.assertTrue(hasattr(lowerCAmelCase , """do_rescale""" ) ) self.assertTrue(hasattr(lowerCAmelCase , """do_pad""" ) ) self.assertTrue(hasattr(lowerCAmelCase , """size""" ) ) def SCREAMING_SNAKE_CASE ( self : int ) -> str: """simple docstring""" __lowerCAmelCase : Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""shortest_edge""": 18, """longest_edge""": 13_33} ) self.assertEqual(image_processor.do_pad , lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Optional[int]: """simple docstring""" pass def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Any: """simple docstring""" __lowerCAmelCase : List[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __lowerCAmelCase : str = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCAmelCase ) for image in image_inputs: self.assertIsInstance(lowerCAmelCase , Image.Image ) # Test not batched input __lowerCAmelCase : str = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values __lowerCAmelCase ,__lowerCAmelCase : List[str] = self.image_processor_tester.get_expected_values(lowerCAmelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __lowerCAmelCase ,__lowerCAmelCase : str = self.image_processor_tester.get_expected_values(lowerCAmelCase , batched=lowerCAmelCase ) __lowerCAmelCase : Dict = image_processing(lowerCAmelCase , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Dict: """simple docstring""" __lowerCAmelCase : List[Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __lowerCAmelCase : Optional[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCAmelCase , numpify=lowerCAmelCase ) for image in image_inputs: self.assertIsInstance(lowerCAmelCase , np.ndarray ) # Test not batched input __lowerCAmelCase : Optional[Any] = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values __lowerCAmelCase ,__lowerCAmelCase : Optional[int] = self.image_processor_tester.get_expected_values(lowerCAmelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __lowerCAmelCase : List[str] = image_processing(lowerCAmelCase , return_tensors="""pt""" ).pixel_values __lowerCAmelCase ,__lowerCAmelCase : int = self.image_processor_tester.get_expected_values(lowerCAmelCase , batched=lowerCAmelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE ( self : Tuple ) -> int: """simple docstring""" __lowerCAmelCase : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __lowerCAmelCase : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCAmelCase , torchify=lowerCAmelCase ) for image in image_inputs: self.assertIsInstance(lowerCAmelCase , torch.Tensor ) # Test not batched input __lowerCAmelCase : Dict = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values __lowerCAmelCase ,__lowerCAmelCase : List[str] = self.image_processor_tester.get_expected_values(lowerCAmelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __lowerCAmelCase : str = image_processing(lowerCAmelCase , return_tensors="""pt""" ).pixel_values __lowerCAmelCase ,__lowerCAmelCase : Dict = self.image_processor_tester.get_expected_values(lowerCAmelCase , batched=lowerCAmelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Optional[int]: """simple docstring""" __lowerCAmelCase : List[Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) with open("""./tests/fixtures/tests_samples/COCO/coco_annotations.txt""" , """r""" ) as f: __lowerCAmelCase : Optional[int] = json.loads(f.read() ) __lowerCAmelCase : int = {"""image_id""": 3_97_69, """annotations""": target} # encode them __lowerCAmelCase : Optional[int] = DetaImageProcessor() __lowerCAmelCase : Optional[int] = image_processing(images=lowerCAmelCase , annotations=lowerCAmelCase , return_tensors="""pt""" ) # verify pixel values __lowerCAmelCase : Optional[int] = torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding["""pixel_values"""].shape , lowerCAmelCase ) __lowerCAmelCase : str = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding["""pixel_values"""][0, 0, 0, :3] , lowerCAmelCase , atol=1e-4 ) ) # verify area __lowerCAmelCase : Tuple = torch.tensor([5887.9600, 1_1250.2061, 48_9353.8438, 83_7122.7500, 14_7967.5156, 16_5732.3438] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""area"""] , lowerCAmelCase ) ) # verify boxes __lowerCAmelCase : List[str] = torch.Size([6, 4] ) self.assertEqual(encoding["""labels"""][0]["""boxes"""].shape , lowerCAmelCase ) __lowerCAmelCase : List[str] = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""boxes"""][0] , lowerCAmelCase , atol=1e-3 ) ) # verify image_id __lowerCAmelCase : Tuple = torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""image_id"""] , lowerCAmelCase ) ) # verify is_crowd __lowerCAmelCase : Union[str, Any] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""iscrowd"""] , lowerCAmelCase ) ) # verify class_labels __lowerCAmelCase : int = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""class_labels"""] , lowerCAmelCase ) ) # verify orig_size __lowerCAmelCase : Dict = torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""orig_size"""] , lowerCAmelCase ) ) # verify size __lowerCAmelCase : Optional[int] = torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""size"""] , lowerCAmelCase ) ) @slow def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Union[str, Any]: """simple docstring""" __lowerCAmelCase : List[str] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) with open("""./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt""" , """r""" ) as f: __lowerCAmelCase : Optional[Any] = json.loads(f.read() ) __lowerCAmelCase : List[str] = {"""file_name""": """000000039769.png""", """image_id""": 3_97_69, """segments_info""": target} __lowerCAmelCase : Union[str, Any] = pathlib.Path("""./tests/fixtures/tests_samples/COCO/coco_panoptic""" ) # encode them __lowerCAmelCase : int = DetaImageProcessor(format="""coco_panoptic""" ) __lowerCAmelCase : str = image_processing(images=lowerCAmelCase , annotations=lowerCAmelCase , masks_path=lowerCAmelCase , return_tensors="""pt""" ) # verify pixel values __lowerCAmelCase : List[Any] = torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding["""pixel_values"""].shape , lowerCAmelCase ) __lowerCAmelCase : Dict = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding["""pixel_values"""][0, 0, 0, :3] , lowerCAmelCase , atol=1e-4 ) ) # verify area __lowerCAmelCase : str = torch.tensor([14_7979.6875, 16_5527.0469, 48_4638.5938, 1_1292.9375, 5879.6562, 7634.1147] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""area"""] , lowerCAmelCase ) ) # verify boxes __lowerCAmelCase : Tuple = torch.Size([6, 4] ) self.assertEqual(encoding["""labels"""][0]["""boxes"""].shape , lowerCAmelCase ) __lowerCAmelCase : str = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""boxes"""][0] , lowerCAmelCase , atol=1e-3 ) ) # verify image_id __lowerCAmelCase : List[str] = torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""image_id"""] , lowerCAmelCase ) ) # verify is_crowd __lowerCAmelCase : int = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""iscrowd"""] , lowerCAmelCase ) ) # verify class_labels __lowerCAmelCase : Any = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""class_labels"""] , lowerCAmelCase ) ) # verify masks __lowerCAmelCase : Any = 82_28_73 self.assertEqual(encoding["""labels"""][0]["""masks"""].sum().item() , lowerCAmelCase ) # verify orig_size __lowerCAmelCase : Dict = torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""orig_size"""] , lowerCAmelCase ) ) # verify size __lowerCAmelCase : Dict = torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""size"""] , lowerCAmelCase ) )
139
import numpy as np import qiskit def snake_case_ (__A : int = 8 , __A : int | None = None ) -> str: __lowerCAmelCase : List[Any] = np.random.default_rng(seed=__A ) # Roughly 25% of the qubits will contribute to the key. # So we take more than we need. __lowerCAmelCase : Tuple = 6 * key_len # Measurement basis for Alice's qubits. __lowerCAmelCase : List[Any] = rng.integers(2 , size=__A ) # The set of states Alice will prepare. __lowerCAmelCase : List[str] = rng.integers(2 , size=__A ) # Measurement basis for Bob's qubits. __lowerCAmelCase : List[Any] = rng.integers(2 , size=__A ) # Quantum Circuit to simulate BB84 __lowerCAmelCase : int = qiskit.QuantumCircuit(__A , name="""BB84""" ) # Alice prepares her qubits according to rules above. for index, _ in enumerate(__A ): if alice_state[index] == 1: bbaa_circ.x(__A ) if alice_basis[index] == 1: bbaa_circ.h(__A ) bbaa_circ.barrier() # Bob measures the received qubits according to rules above. for index, _ in enumerate(__A ): if bob_basis[index] == 1: bbaa_circ.h(__A ) bbaa_circ.barrier() bbaa_circ.measure_all() # Simulate the quantum circuit. __lowerCAmelCase : Optional[Any] = qiskit.Aer.get_backend("""aer_simulator""" ) # We only need to run one shot because the key is unique. # Multiple shots will produce the same key. __lowerCAmelCase : Optional[Any] = qiskit.execute(__A , __A , shots=1 , seed_simulator=__A ) # Returns the result of measurement. __lowerCAmelCase : List[Any] = job.result().get_counts(__A ).most_frequent() # Extracting the generated key from the simulation results. # Only keep measurement results where Alice and Bob chose the same basis. __lowerCAmelCase : Optional[int] = """""".join( [ result_bit for alice_basis_bit, bob_basis_bit, result_bit in zip( __A , __A , __A ) if alice_basis_bit == bob_basis_bit ] ) # Get final key. Pad with 0 if too short, otherwise truncate. __lowerCAmelCase : Tuple = gen_key[:key_len] if len(__A ) >= key_len else gen_key.ljust(__A , """0""" ) return key if __name__ == "__main__": print(F'The generated key is : {bbaa(8, seed=0)}') from doctest import testmod testmod()
139
1
'''simple docstring''' from __future__ import annotations import random import unittest from transformers import TransfoXLConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST, TFTransfoXLForSequenceClassification, TFTransfoXLLMHeadModel, TFTransfoXLModel, ) class lowerCAmelCase : def __init__( self : Optional[int] , __lowercase : List[Any] , ): """simple docstring""" __lowercase =parent __lowercase =13 __lowercase =7 __lowercase =30 __lowercase =self.seq_length + self.mem_len __lowercase =15 __lowercase =True __lowercase =True __lowercase =99 __lowercase =[10, 50, 80] __lowercase =32 __lowercase =32 __lowercase =4 __lowercase =8 __lowercase =128 __lowercase =2 __lowercase =2 __lowercase =None __lowercase =1 __lowercase =0 __lowercase =3 __lowercase =self.vocab_size - 1 __lowercase =0.0_1 def snake_case ( self : Optional[int] ): """simple docstring""" __lowercase =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __lowercase =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __lowercase =None if self.use_labels: __lowercase =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __lowercase =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 snake_case ( self : str ): """simple docstring""" random.seed(self.seed ) tf.random.set_seed(self.seed ) def snake_case ( self : List[str] , __lowercase : Any , __lowercase : Tuple , __lowercase : Union[str, Any] , __lowercase : int ): """simple docstring""" __lowercase =TFTransfoXLModel(__lowercase ) __lowercase , __lowercase =model(__lowercase ).to_tuple() __lowercase ={'input_ids': input_ids_a, 'mems': mems_a} __lowercase , __lowercase =model(__lowercase ).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 snake_case ( self : int , __lowercase : Union[str, Any] , __lowercase : Any , __lowercase : List[str] , __lowercase : Tuple ): """simple docstring""" __lowercase =TFTransfoXLLMHeadModel(__lowercase ) __lowercase , __lowercase =model(__lowercase ).to_tuple() __lowercase ={'input_ids': input_ids_a, 'labels': lm_labels} __lowercase , __lowercase =model(__lowercase ).to_tuple() __lowercase , __lowercase =model([input_ids_a, mems_a] ).to_tuple() __lowercase ={'input_ids': input_ids_a, 'mems': mems_a, 'labels': lm_labels} __lowercase , __lowercase =model(__lowercase ).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 snake_case ( self : Tuple , __lowercase : List[str] , __lowercase : List[str] , __lowercase : Optional[Any] , __lowercase : str ): """simple docstring""" __lowercase =TFTransfoXLForSequenceClassification(__lowercase ) __lowercase =model(__lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def snake_case ( self : List[str] ): """simple docstring""" __lowercase =self.prepare_config_and_inputs() ((__lowercase) , (__lowercase) , (__lowercase) , (__lowercase)) =config_and_inputs __lowercase ={'input_ids': input_ids_a} return config, inputs_dict @require_tf class lowerCAmelCase ( A , A , unittest.TestCase ): lowerCAmelCase_ = ( (TFTransfoXLModel, TFTransfoXLLMHeadModel, TFTransfoXLForSequenceClassification) if is_tf_available() else () ) lowerCAmelCase_ = () if is_tf_available() else () lowerCAmelCase_ = ( { "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 lowerCAmelCase_ = False lowerCAmelCase_ = False lowerCAmelCase_ = False lowerCAmelCase_ = False def snake_case ( self : Any , __lowercase : int , __lowercase : Optional[Any] , __lowercase : str , __lowercase : List[Any] , __lowercase : Union[str, Any] ): """simple docstring""" 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 snake_case ( self : int ): """simple docstring""" __lowercase =TFTransfoXLModelTester(self ) __lowercase =ConfigTester(self , config_class=__lowercase , d_embed=37 ) def snake_case ( self : int ): """simple docstring""" self.config_tester.run_common_tests() def snake_case ( self : Any ): """simple docstring""" self.model_tester.set_seed() __lowercase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_model(*__lowercase ) def snake_case ( self : str ): """simple docstring""" self.model_tester.set_seed() __lowercase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_lm_head(*__lowercase ) def snake_case ( self : Union[str, Any] ): """simple docstring""" __lowercase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_for_sequence_classification(*__lowercase ) def snake_case ( self : int ): """simple docstring""" __lowercase , __lowercase =self.model_tester.prepare_config_and_inputs_for_common() __lowercase =[TFTransfoXLForSequenceClassification] for model_class in self.all_model_classes: __lowercase =model_class(__lowercase ) assert isinstance(model.get_input_embeddings() , tf.keras.layers.Layer ) if model_class in list_other_models_with_output_ebd: __lowercase =model.get_output_embeddings() assert isinstance(__lowercase , tf.keras.layers.Layer ) __lowercase =model.get_bias() assert name is None else: __lowercase =model.get_output_embeddings() assert x is None __lowercase =model.get_bias() assert name is None def snake_case ( self : Union[str, Any] ): """simple docstring""" pass @slow def snake_case ( self : Any ): """simple docstring""" for model_name in TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowercase =TFTransfoXLModel.from_pretrained(__lowercase ) self.assertIsNotNone(__lowercase ) @unittest.skip(reason='This model doesn\'t play well with fit() due to not returning a single loss.' ) def snake_case ( self : List[str] ): """simple docstring""" pass @require_tf class lowerCAmelCase ( unittest.TestCase ): @unittest.skip('Skip test until #12651 is resolved.' ) @slow def snake_case ( self : str ): """simple docstring""" __lowercase =TFTransfoXLLMHeadModel.from_pretrained('transfo-xl-wt103' ) # fmt: off __lowercase =tf.convert_to_tensor([[33,1297,2,1,1009,4,1109,11739,4762,358,5,25,245,22,1706,17,20098,5,3215,21,37,1110,3,13,1041,4,24,603,490,2,71477,20098,104447,2,20961,1,2604,4,1,329,3,6224,831,16002,2,8,603,78967,29546,23,803,20,25,416,5,8,232,4,277,6,1855,4601,3,29546,54,8,3609,5,57211,49,4,1,277,18,8,1755,15691,3,341,25,416,693,42573,71,17,401,94,31,17919,2,29546,7873,18,1,435,23,11011,755,5,5167,3,7983,98,84,2,29546,3267,8,3609,4,1,4865,1075,2,6087,71,6,346,8,5854,3,29546,824,1400,1868,2,19,160,2,311,8,5496,2,20920,17,25,15097,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 __lowercase =[33,1297,2,1,1009,4,1109,11739,4762,358,5,25,245,22,1706,17,20098,5,3215,21,37,1110,3,13,1041,4,24,603,490,2,71477,20098,104447,2,20961,1,2604,4,1,329,3,6224,831,16002,2,8,603,78967,29546,23,803,20,25,416,5,8,232,4,277,6,1855,4601,3,29546,54,8,3609,5,57211,49,4,1,277,18,8,1755,15691,3,341,25,416,693,42573,71,17,401,94,31,17919,2,29546,7873,18,1,435,23,11011,755,5,5167,3,7983,98,84,2,29546,3267,8,3609,4,1,4865,1075,2,6087,71,6,346,8,5854,3,29546,824,1400,1868,2,19,160,2,311,8,5496,2,20920,17,25,15097,3,24,24,0,33,1,1857,2,1,1009,4,1109,11739,4762,358,5,25,245,28,1110,3,13,1041,4,24,603,490,2,71477,20098,104447,2,20961,1,2604,4,1,329,3,0] # noqa: E231 # fmt: on # In 1991, the remains of Russian Tsar Nicholas II and his family ( # except for Alexei and Maria ) are discovered. The voice of young son, # Tsarevich Alexei Nikolaevich, narrates the remainder of the story. # 1883 Western Siberia, a young Grigori Rasputin is asked by his father # and a group of men to perform magic. Rasputin has a vision and # denounces one of the men as a horse thief. Although his father initially # slaps him for making such an accusation, Rasputin watches as the man # is chased outside and beaten. Twenty years later, Rasputin sees a vision # of the Virgin Mary, prompting him to become a priest. # Rasputin quickly becomes famous, with people, even a bishop, begging for # his blessing. <unk> <unk> <eos> In the 1990s, the remains of Russian Tsar # Nicholas II and his family were discovered. The voice of <unk> young son, # Tsarevich Alexei Nikolaevich, narrates the remainder of the story.<eos> __lowercase =model.generate(__lowercase , max_length=200 , do_sample=__lowercase ) self.assertListEqual(output_ids[0].numpy().tolist() , __lowercase )
141
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, is_valid_image, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL UpperCAmelCase = logging.get_logger(__name__) def __UpperCamelCase ( lowercase__ : List[Any] ): '''simple docstring''' if isinstance(lowercase__, (list, tuple) ) and isinstance(videos[0], (list, tuple) ) and is_valid_image(videos[0][0] ): return videos elif isinstance(lowercase__, (list, tuple) ) and is_valid_image(videos[0] ): return [videos] elif is_valid_image(lowercase__ ): return [[videos]] raise ValueError(F'''Could not make batched video from {videos}''' ) class lowerCAmelCase ( A ): lowerCAmelCase_ = ["pixel_values"] def __init__( self : Union[str, Any] , __lowercase : bool = True , __lowercase : Dict[str, int] = None , __lowercase : PILImageResampling = PILImageResampling.BILINEAR , __lowercase : bool = True , __lowercase : Dict[str, int] = None , __lowercase : bool = True , __lowercase : Union[int, float] = 1 / 255 , __lowercase : bool = True , __lowercase : Optional[Union[float, List[float]]] = None , __lowercase : Optional[Union[float, List[float]]] = None , **__lowercase : Optional[Any] , ): """simple docstring""" super().__init__(**__lowercase ) __lowercase =size if size is not None else {'shortest_edge': 224} __lowercase =get_size_dict(__lowercase , default_to_square=__lowercase ) __lowercase =crop_size if crop_size is not None else {'height': 224, 'width': 224} __lowercase =get_size_dict(__lowercase , param_name='crop_size' ) __lowercase =do_resize __lowercase =size __lowercase =do_center_crop __lowercase =crop_size __lowercase =resample __lowercase =do_rescale __lowercase =rescale_factor __lowercase =do_normalize __lowercase =image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN __lowercase =image_std if image_std is not None else IMAGENET_STANDARD_STD def snake_case ( self : int , __lowercase : np.ndarray , __lowercase : Dict[str, int] , __lowercase : PILImageResampling = PILImageResampling.BILINEAR , __lowercase : Optional[Union[str, ChannelDimension]] = None , **__lowercase : Optional[Any] , ): """simple docstring""" __lowercase =get_size_dict(__lowercase , default_to_square=__lowercase ) if "shortest_edge" in size: __lowercase =get_resize_output_image_size(__lowercase , size['shortest_edge'] , default_to_square=__lowercase ) elif "height" in size and "width" in size: __lowercase =(size['height'], size['width']) else: raise ValueError(f'''Size must have \'height\' and \'width\' or \'shortest_edge\' as keys. Got {size.keys()}''' ) return resize(__lowercase , size=__lowercase , resample=__lowercase , data_format=__lowercase , **__lowercase ) def snake_case ( self : Dict , __lowercase : np.ndarray , __lowercase : Dict[str, int] , __lowercase : Optional[Union[str, ChannelDimension]] = None , **__lowercase : List[Any] , ): """simple docstring""" __lowercase =get_size_dict(__lowercase ) if "height" not in size or "width" not in size: raise ValueError(f'''Size must have \'height\' and \'width\' as keys. Got {size.keys()}''' ) return center_crop(__lowercase , size=(size['height'], size['width']) , data_format=__lowercase , **__lowercase ) def snake_case ( self : str , __lowercase : np.ndarray , __lowercase : Union[int, float] , __lowercase : Optional[Union[str, ChannelDimension]] = None , **__lowercase : Any , ): """simple docstring""" return rescale(__lowercase , scale=__lowercase , data_format=__lowercase , **__lowercase ) def snake_case ( self : Dict , __lowercase : np.ndarray , __lowercase : Union[float, List[float]] , __lowercase : Union[float, List[float]] , __lowercase : Optional[Union[str, ChannelDimension]] = None , **__lowercase : Optional[Any] , ): """simple docstring""" return normalize(__lowercase , mean=__lowercase , std=__lowercase , data_format=__lowercase , **__lowercase ) def snake_case ( self : Optional[Any] , __lowercase : ImageInput , __lowercase : bool = None , __lowercase : Dict[str, int] = None , __lowercase : PILImageResampling = None , __lowercase : bool = None , __lowercase : Dict[str, int] = None , __lowercase : bool = None , __lowercase : float = None , __lowercase : bool = None , __lowercase : Optional[Union[float, List[float]]] = None , __lowercase : Optional[Union[float, List[float]]] = None , __lowercase : Optional[ChannelDimension] = ChannelDimension.FIRST , ): """simple docstring""" if do_resize and size is None or resample is None: raise ValueError('Size and resample must be specified if do_resize is True.' ) if do_center_crop and crop_size is None: raise ValueError('Crop size must be specified if do_center_crop is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.' ) # All transformations expect numpy arrays. __lowercase =to_numpy_array(__lowercase ) if do_resize: __lowercase =self.resize(image=__lowercase , size=__lowercase , resample=__lowercase ) if do_center_crop: __lowercase =self.center_crop(__lowercase , size=__lowercase ) if do_rescale: __lowercase =self.rescale(image=__lowercase , scale=__lowercase ) if do_normalize: __lowercase =self.normalize(image=__lowercase , mean=__lowercase , std=__lowercase ) __lowercase =to_channel_dimension_format(__lowercase , __lowercase ) return image def snake_case ( self : Union[str, Any] , __lowercase : ImageInput , __lowercase : bool = None , __lowercase : Dict[str, int] = None , __lowercase : PILImageResampling = None , __lowercase : bool = None , __lowercase : Dict[str, int] = None , __lowercase : bool = None , __lowercase : float = None , __lowercase : bool = None , __lowercase : Optional[Union[float, List[float]]] = None , __lowercase : Optional[Union[float, List[float]]] = None , __lowercase : Optional[Union[str, TensorType]] = None , __lowercase : ChannelDimension = ChannelDimension.FIRST , **__lowercase : Tuple , ): """simple docstring""" __lowercase =do_resize if do_resize is not None else self.do_resize __lowercase =resample if resample is not None else self.resample __lowercase =do_center_crop if do_center_crop is not None else self.do_center_crop __lowercase =do_rescale if do_rescale is not None else self.do_rescale __lowercase =rescale_factor if rescale_factor is not None else self.rescale_factor __lowercase =do_normalize if do_normalize is not None else self.do_normalize __lowercase =image_mean if image_mean is not None else self.image_mean __lowercase =image_std if image_std is not None else self.image_std __lowercase =size if size is not None else self.size __lowercase =get_size_dict(__lowercase , default_to_square=__lowercase ) __lowercase =crop_size if crop_size is not None else self.crop_size __lowercase =get_size_dict(__lowercase , param_name='crop_size' ) if not valid_images(__lowercase ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) __lowercase =make_batched(__lowercase ) __lowercase =[ [ self._preprocess_image( image=__lowercase , do_resize=__lowercase , size=__lowercase , resample=__lowercase , do_center_crop=__lowercase , crop_size=__lowercase , do_rescale=__lowercase , rescale_factor=__lowercase , do_normalize=__lowercase , image_mean=__lowercase , image_std=__lowercase , data_format=__lowercase , ) for img in video ] for video in videos ] __lowercase ={'pixel_values': videos} return BatchFeature(data=__lowercase , tensor_type=__lowercase )
141
1
'''simple docstring''' from __future__ import annotations __snake_case ="""#""" class UpperCAmelCase_ : def __init__( self : Any ) -> None: lowerCAmelCase = {} def __UpperCAmelCase ( self : Tuple , UpperCAmelCase__ : str ) -> None: lowerCAmelCase = self._trie for char in text: if char not in trie: lowerCAmelCase = {} lowerCAmelCase = trie[char] lowerCAmelCase = True def __UpperCAmelCase ( self : int , UpperCAmelCase__ : str ) -> tuple | list: lowerCAmelCase = self._trie for char in prefix: if char in trie: lowerCAmelCase = trie[char] else: return [] return self._elements(UpperCAmelCase__ ) def __UpperCAmelCase ( self : Any , UpperCAmelCase__ : dict ) -> tuple: lowerCAmelCase = [] for c, v in d.items(): lowerCAmelCase = [' '] if c == END else [(c + s) for s in self._elements(UpperCAmelCase__ )] result.extend(UpperCAmelCase__ ) return tuple(UpperCAmelCase__ ) __snake_case =Trie() __snake_case =("""depart""", """detergent""", """daring""", """dog""", """deer""", """deal""") for word in words: trie.insert_word(word) def a_ ( lowerCamelCase : str ): lowerCAmelCase = trie.find_word(lowerCamelCase ) return tuple(string + word for word in suffixes ) def a_ ( ): print(autocomplete_using_trie('de' ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
55
'''simple docstring''' import math def a_ ( lowerCamelCase : int ): lowerCAmelCase = math.loga(math.sqrt(4 * positive_integer + 1 ) / 2 + 1 / 2 ) return exponent == int(lowerCamelCase ) def a_ ( lowerCamelCase : float = 1 / 12345 ): lowerCAmelCase = 0 lowerCAmelCase = 0 lowerCAmelCase = 3 while True: lowerCAmelCase = (integer**2 - 1) / 4 # if candidate is an integer, then there is a partition for k if partition_candidate == int(lowerCamelCase ): lowerCAmelCase = int(lowerCamelCase ) total_partitions += 1 if check_partition_perfect(lowerCamelCase ): perfect_partitions += 1 if perfect_partitions > 0: if perfect_partitions / total_partitions < max_proportion: return int(lowerCamelCase ) integer += 1 if __name__ == "__main__": print(F'''{solution() = }''')
55
1
'''simple docstring''' import argparse import collections import json from pathlib import Path import requests import torch import yaml from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( MobileViTImageProcessor, MobileViTVaConfig, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, ) from transformers.utils import logging logging.set_verbosity_info() _UpperCamelCase = logging.get_logger(__name__) def a_ ( _lowerCAmelCase ) -> Union[str, Any]: print('Loading config file...' ) def flatten_yaml_as_dict(_lowerCAmelCase ,_lowerCAmelCase="" ,_lowerCAmelCase="." ): __lowerCamelCase : str = [] for k, v in d.items(): __lowerCamelCase : Optional[Any] = parent_key + sep + k if parent_key else k if isinstance(__UpperCamelCase ,collections.abc.MutableMapping ): items.extend(flatten_yaml_as_dict(__UpperCamelCase ,__UpperCamelCase ,sep=__UpperCamelCase ).items() ) else: items.append((new_key, v) ) return dict(__UpperCamelCase ) __lowerCamelCase : Optional[Any] = argparse.Namespace() with open(__UpperCamelCase ,'r' ) as yaml_file: try: __lowerCamelCase : List[str] = yaml.load(__UpperCamelCase ,Loader=yaml.FullLoader ) __lowerCamelCase : List[str] = flatten_yaml_as_dict(__UpperCamelCase ) for k, v in flat_cfg.items(): setattr(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) except yaml.YAMLError as exc: logger.error('Error while loading config file: {}. Error message: {}'.format(__UpperCamelCase ,str(__UpperCamelCase ) ) ) return config def a_ ( _lowerCAmelCase ,_lowerCAmelCase ) -> str: __lowerCamelCase : str = MobileViTVaConfig() __lowerCamelCase : int = False # dataset if task_name.startswith('imagenet1k_' ): __lowerCamelCase : int = 1000 if int(task_name.strip().split('_' )[-1] ) == 384: __lowerCamelCase : Dict = 384 else: __lowerCamelCase : Any = 256 __lowerCamelCase : List[str] = 'imagenet-1k-id2label.json' elif task_name.startswith('imagenet21k_to_1k_' ): __lowerCamelCase : Any = 21000 if int(task_name.strip().split('_' )[-1] ) == 384: __lowerCamelCase : List[str] = 384 else: __lowerCamelCase : Tuple = 256 __lowerCamelCase : List[Any] = 'imagenet-22k-id2label.json' elif task_name.startswith('ade20k_' ): __lowerCamelCase : Union[str, Any] = 151 __lowerCamelCase : int = 512 __lowerCamelCase : Dict = 'ade20k-id2label.json' __lowerCamelCase : List[str] = True elif task_name.startswith('voc_' ): __lowerCamelCase : Optional[Any] = 21 __lowerCamelCase : Optional[int] = 512 __lowerCamelCase : Union[str, Any] = 'pascal-voc-id2label.json' __lowerCamelCase : Optional[Any] = True # orig_config __lowerCamelCase : int = load_orig_config_file(__UpperCamelCase ) assert getattr(__UpperCamelCase ,'model.classification.name' ,-1 ) == "mobilevit_v2", "Invalid model" __lowerCamelCase : Union[str, Any] = getattr(__UpperCamelCase ,'model.classification.mitv2.width_multiplier' ,1.0 ) assert ( getattr(__UpperCamelCase ,'model.classification.mitv2.attn_norm_layer' ,-1 ) == "layer_norm_2d" ), "Norm layers other than layer_norm_2d is not supported" __lowerCamelCase : Union[str, Any] = getattr(__UpperCamelCase ,'model.classification.activation.name' ,'swish' ) # config.image_size == getattr(orig_config, 'sampler.bs.crop_size_width', 256) if is_segmentation_model: __lowerCamelCase : Any = getattr(__UpperCamelCase ,'model.segmentation.output_stride' ,16 ) if "_deeplabv3" in task_name: __lowerCamelCase : str = getattr(__UpperCamelCase ,'model.segmentation.deeplabv3.aspp_rates' ,[12, 24, 36] ) __lowerCamelCase : List[str] = getattr(__UpperCamelCase ,'model.segmentation.deeplabv3.aspp_out_channels' ,512 ) __lowerCamelCase : Any = getattr(__UpperCamelCase ,'model.segmentation.deeplabv3.aspp_dropout' ,0.1 ) # id2label __lowerCamelCase : Dict = 'huggingface/label-files' __lowerCamelCase : List[str] = json.load(open(hf_hub_download(__UpperCamelCase ,__UpperCamelCase ,repo_type='dataset' ) ,'r' ) ) __lowerCamelCase : int = {int(__UpperCamelCase ): v for k, v in idalabel.items()} __lowerCamelCase : List[Any] = idalabel __lowerCamelCase : str = {v: k for k, v in idalabel.items()} return config def a_ ( _lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ) -> Dict: __lowerCamelCase : Union[str, Any] = dct.pop(__UpperCamelCase ) __lowerCamelCase : str = val def a_ ( _lowerCAmelCase ,_lowerCAmelCase=False ) -> Optional[int]: if base_model: __lowerCamelCase : Optional[int] = '' else: __lowerCamelCase : Dict = 'mobilevitv2.' __lowerCamelCase : Union[str, Any] = [] for k in state_dict.keys(): if k[:8] == "encoder.": __lowerCamelCase : List[str] = k[8:] else: __lowerCamelCase : List[str] = k if ".block." in k: __lowerCamelCase : str = k_new.replace('.block.' ,'.' ) if ".conv." in k: __lowerCamelCase : Union[str, Any] = k_new.replace('.conv.' ,'.convolution.' ) if ".norm." in k: __lowerCamelCase : Any = k_new.replace('.norm.' ,'.normalization.' ) if "conv_1." in k: __lowerCamelCase : Any = k_new.replace('conv_1.' ,F'{model_prefix}conv_stem.' ) for i in [1, 2]: if F'layer_{i}.' in k: __lowerCamelCase : Dict = k_new.replace(F'layer_{i}.' ,F'{model_prefix}encoder.layer.{i-1}.layer.' ) if ".exp_1x1." in k: __lowerCamelCase : List[str] = k_new.replace('.exp_1x1.' ,'.expand_1x1.' ) if ".red_1x1." in k: __lowerCamelCase : Dict = k_new.replace('.red_1x1.' ,'.reduce_1x1.' ) for i in [3, 4, 5]: if F'layer_{i}.0.' in k: __lowerCamelCase : List[str] = k_new.replace(F'layer_{i}.0.' ,F'{model_prefix}encoder.layer.{i-1}.downsampling_layer.' ) if F'layer_{i}.1.local_rep.0.' in k: __lowerCamelCase : Optional[Any] = k_new.replace(F'layer_{i}.1.local_rep.0.' ,F'{model_prefix}encoder.layer.{i-1}.conv_kxk.' ) if F'layer_{i}.1.local_rep.1.' in k: __lowerCamelCase : Union[str, Any] = k_new.replace(F'layer_{i}.1.local_rep.1.' ,F'{model_prefix}encoder.layer.{i-1}.conv_1x1.' ) for i in [3, 4, 5]: if i == 3: __lowerCamelCase : Union[str, Any] = [0, 1] elif i == 4: __lowerCamelCase : Dict = [0, 1, 2, 3] elif i == 5: __lowerCamelCase : List[Any] = [0, 1, 2] for j in j_in: if F'layer_{i}.1.global_rep.{j}.' in k: __lowerCamelCase : Optional[int] = k_new.replace( F'layer_{i}.1.global_rep.{j}.' ,F'{model_prefix}encoder.layer.{i-1}.transformer.layer.{j}.' ) if F'layer_{i}.1.global_rep.{j+1}.' in k: __lowerCamelCase : List[str] = k_new.replace( F'layer_{i}.1.global_rep.{j+1}.' ,F'{model_prefix}encoder.layer.{i-1}.layernorm.' ) if F'layer_{i}.1.conv_proj.' in k: __lowerCamelCase : List[str] = k_new.replace(F'layer_{i}.1.conv_proj.' ,F'{model_prefix}encoder.layer.{i-1}.conv_projection.' ) if "pre_norm_attn.0." in k: __lowerCamelCase : List[str] = k_new.replace('pre_norm_attn.0.' ,'layernorm_before.' ) if "pre_norm_attn.1." in k: __lowerCamelCase : Dict = k_new.replace('pre_norm_attn.1.' ,'attention.' ) if "pre_norm_ffn.0." in k: __lowerCamelCase : List[Any] = k_new.replace('pre_norm_ffn.0.' ,'layernorm_after.' ) if "pre_norm_ffn.1." in k: __lowerCamelCase : Tuple = k_new.replace('pre_norm_ffn.1.' ,'ffn.conv1.' ) if "pre_norm_ffn.3." in k: __lowerCamelCase : Optional[int] = k_new.replace('pre_norm_ffn.3.' ,'ffn.conv2.' ) if "classifier.1." in k: __lowerCamelCase : Optional[int] = k_new.replace('classifier.1.' ,'classifier.' ) if "seg_head." in k: __lowerCamelCase : Optional[Any] = k_new.replace('seg_head.' ,'segmentation_head.' ) if ".aspp_layer." in k: __lowerCamelCase : int = k_new.replace('.aspp_layer.' ,'.' ) if ".aspp_pool." in k: __lowerCamelCase : str = k_new.replace('.aspp_pool.' ,'.' ) rename_keys.append((k, k_new) ) return rename_keys def a_ ( _lowerCAmelCase ) -> Union[str, Any]: __lowerCamelCase : Dict = [] for k in state_dict.keys(): if k.startswith('seg_head.aux_head.' ): keys_to_ignore.append(__UpperCamelCase ) for k in keys_to_ignore: state_dict.pop(__UpperCamelCase ,__UpperCamelCase ) def a_ ( ) -> Tuple: __lowerCamelCase : str = 'http://images.cocodataset.org/val2017/000000039769.jpg' # url = "https://cdn.britannica.com/86/141086-050-9D7C75EE/Gulfstream-G450-business-jet-passengers.jpg" __lowerCamelCase : Optional[int] = Image.open(requests.get(__UpperCamelCase ,stream=__UpperCamelCase ).raw ) return im @torch.no_grad() def a_ ( _lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ) -> List[Any]: __lowerCamelCase : Optional[Any] = get_mobilevitva_config(__UpperCamelCase ,__UpperCamelCase ) # load original state_dict __lowerCamelCase : Union[str, Any] = torch.load(__UpperCamelCase ,map_location='cpu' ) # load huggingface model if task_name.startswith('ade20k_' ) or task_name.startswith('voc_' ): __lowerCamelCase : List[str] = MobileViTVaForSemanticSegmentation(__UpperCamelCase ).eval() __lowerCamelCase : Optional[Any] = False else: __lowerCamelCase : str = MobileViTVaForImageClassification(__UpperCamelCase ).eval() __lowerCamelCase : Any = False # remove and rename some keys of load the original model __lowerCamelCase : int = checkpoint remove_unused_keys(__UpperCamelCase ) __lowerCamelCase : Dict = create_rename_keys(__UpperCamelCase ,base_model=__UpperCamelCase ) for rename_key_src, rename_key_dest in rename_keys: rename_key(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) # load modified state_dict model.load_state_dict(__UpperCamelCase ) # Check outputs on an image, prepared by MobileViTImageProcessor __lowerCamelCase : str = MobileViTImageProcessor(crop_size=config.image_size ,size=config.image_size + 32 ) __lowerCamelCase : Tuple = image_processor(images=prepare_img() ,return_tensors='pt' ) __lowerCamelCase : int = model(**__UpperCamelCase ) # verify classification model if task_name.startswith('imagenet' ): __lowerCamelCase : List[Any] = outputs.logits __lowerCamelCase : Union[str, Any] = logits.argmax(-1 ).item() print('Predicted class:' ,model.config.idalabel[predicted_class_idx] ) if task_name.startswith('imagenet1k_256' ) and config.width_multiplier == 1.0: # expected_logits for base variant __lowerCamelCase : Optional[Any] = torch.tensor([-1.6336E00, -7.3204E-02, -5.1883E-01] ) assert torch.allclose(logits[0, :3] ,__UpperCamelCase ,atol=1E-4 ) Path(__UpperCamelCase ).mkdir(exist_ok=__UpperCamelCase ) print(F'Saving model {task_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(__UpperCamelCase ) print(F'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(__UpperCamelCase ) if __name__ == "__main__": _UpperCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '--task', default='imagenet1k_256', type=str, help=( 'Name of the task for which the MobileViTV2 model you\'d like to convert is trained on . ' '\n Classification (ImageNet-1k)\n - MobileViTV2 (256x256) : imagenet1k_256\n - MobileViTV2 (Trained on 256x256 and Finetuned on 384x384) : imagenet1k_384\n - MobileViTV2 (Trained on ImageNet-21k and Finetuned on ImageNet-1k 256x256) :\n imagenet21k_to_1k_256\n - MobileViTV2 (Trained on ImageNet-21k, Finetuned on ImageNet-1k 256x256, and Finetuned on\n ImageNet-1k 384x384) : imagenet21k_to_1k_384\n Segmentation\n - ADE20K Dataset : ade20k_deeplabv3\n - Pascal VOC 2012 Dataset: voc_deeplabv3\n ' ), choices=[ 'imagenet1k_256', 'imagenet1k_384', 'imagenet21k_to_1k_256', 'imagenet21k_to_1k_384', 'ade20k_deeplabv3', 'voc_deeplabv3', ], ) parser.add_argument( '--orig_checkpoint_path', required=True, type=str, help='Path to the original state dict (.pt file).' ) parser.add_argument('--orig_config_path', required=True, type=str, help='Path to the original config file.') parser.add_argument( '--pytorch_dump_folder_path', required=True, type=str, help='Path to the output PyTorch model directory.' ) _UpperCamelCase = parser.parse_args() convert_mobilevitva_checkpoint( args.task, args.orig_checkpoint_path, args.orig_config_path, args.pytorch_dump_folder_path )
208
'''simple docstring''' import datasets from .evaluate import evaluate SCREAMING_SNAKE_CASE__ = '\\n@article{hendrycks2021cuad,\n title={CUAD: An Expert-Annotated NLP Dataset for Legal Contract Review},\n author={Dan Hendrycks and Collin Burns and Anya Chen and Spencer Ball},\n journal={arXiv preprint arXiv:2103.06268},\n year={2021}\n}\n' SCREAMING_SNAKE_CASE__ = '\nThis metric wrap the official scoring script for version 1 of the Contract\nUnderstanding Atticus Dataset (CUAD).\nContract Understanding Atticus Dataset (CUAD) v1 is a corpus of more than 13,000 labels in 510\ncommercial legal contracts that have been manually labeled to identify 41 categories of important\nclauses that lawyers look for when reviewing contracts in connection with corporate transactions.\n' SCREAMING_SNAKE_CASE__ = '\nComputes CUAD scores (EM, F1, AUPR, Precision@80%Recall, and Precision@90%Recall).\nArgs:\n predictions: List of question-answers dictionaries with the following key-values:\n - \'id\': id of the question-answer pair as given in the references (see below)\n - \'prediction_text\': list of possible texts for the answer, as a list of strings\n depending on a threshold on the confidence probability of each prediction.\n references: List of question-answers dictionaries with the following key-values:\n - \'id\': id of the question-answer pair (see above),\n - \'answers\': a Dict in the CUAD dataset format\n {\n \'text\': list of possible texts for the answer, as a list of strings\n \'answer_start\': list of start positions for the answer, as a list of ints\n }\n Note that answer_start values are not taken into account to compute the metric.\nReturns:\n \'exact_match\': Exact match (the normalized answer exactly match the gold answer)\n \'f1\': The F-score of predicted tokens versus the gold answer\n \'aupr\': Area Under the Precision-Recall curve\n \'prec_at_80_recall\': Precision at 80% recall\n \'prec_at_90_recall\': Precision at 90% recall\nExamples:\n >>> predictions = [{\'prediction_text\': [\'The seller:\', \'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.\'], \'id\': \'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties\'}]\n >>> references = [{\'answers\': {\'answer_start\': [143, 49], \'text\': [\'The seller:\', \'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.\']}, \'id\': \'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties\'}]\n >>> cuad_metric = datasets.load_metric("cuad")\n >>> results = cuad_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'exact_match\': 100.0, \'f1\': 100.0, \'aupr\': 0.0, \'prec_at_80_recall\': 1.0, \'prec_at_90_recall\': 1.0}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a_ ( datasets.Metric ): def A__ ( self ) -> Tuple: """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": { """id""": datasets.Value("""string""" ), """prediction_text""": datasets.features.Sequence(datasets.Value("""string""" ) ), }, """references""": { """id""": datasets.Value("""string""" ), """answers""": datasets.features.Sequence( { """text""": datasets.Value("""string""" ), """answer_start""": datasets.Value("""int32""" ), } ), }, } ) , codebase_urls=["""https://www.atticusprojectai.org/cuad"""] , reference_urls=["""https://www.atticusprojectai.org/cuad"""] , ) def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" UpperCamelCase = {prediction["""id"""]: prediction["""prediction_text"""] for prediction in predictions} UpperCamelCase = [ { """paragraphs""": [ { """qas""": [ { """answers""": [{"""text""": answer_text} for answer_text in ref["""answers"""]["""text"""]], """id""": ref["""id"""], } for ref in references ] } ] } ] UpperCamelCase = evaluate(dataset=_SCREAMING_SNAKE_CASE , predictions=_SCREAMING_SNAKE_CASE ) return score
321
0
from .glue import glue_convert_examples_to_features, glue_output_modes, glue_processors, glue_tasks_num_labels from .squad import SquadExample, SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features from .utils import DataProcessor, InputExample, InputFeatures, SingleSentenceClassificationProcessor from .xnli import xnli_output_modes, xnli_processors, xnli_tasks_num_labels
84
import os from typing import Any, Callable, Dict, List, Optional, Tuple, Union import torch from torch import nn from ...models.controlnet import ControlNetModel, ControlNetOutput from ...models.modeling_utils import ModelMixin from ...utils import logging SCREAMING_SNAKE_CASE : int = logging.get_logger(__name__) class _lowerCamelCase( _a ): def __init__( self, lowerCamelCase) -> List[Any]: """simple docstring""" super().__init__() _lowercase : Union[str, Any] = nn.ModuleList(lowerCamelCase) def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase = None, lowerCamelCase = None, lowerCamelCase = None, lowerCamelCase = None, lowerCamelCase = False, lowerCamelCase = True, ) -> Union[ControlNetOutput, Tuple]: """simple docstring""" for i, (image, scale, controlnet) in enumerate(zip(lowerCamelCase, lowerCamelCase, self.nets)): _lowercase , _lowercase : List[Any] = controlnet( lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, ) # merge samples if i == 0: _lowercase , _lowercase : int = down_samples, mid_sample else: _lowercase : Dict = [ samples_prev + samples_curr for samples_prev, samples_curr in zip(lowerCamelCase, lowerCamelCase) ] mid_block_res_sample += mid_sample return down_block_res_samples, mid_block_res_sample def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase = True, lowerCamelCase = None, lowerCamelCase = False, lowerCamelCase = None, ) -> Tuple: """simple docstring""" _lowercase : Tuple = 0 _lowercase : int = save_directory for controlnet in self.nets: controlnet.save_pretrained( lowerCamelCase, is_main_process=lowerCamelCase, save_function=lowerCamelCase, safe_serialization=lowerCamelCase, variant=lowerCamelCase, ) idx += 1 _lowercase : Any = model_path_to_save + F'''_{idx}''' @classmethod def UpperCamelCase ( cls, lowerCamelCase, **lowerCamelCase) -> List[str]: """simple docstring""" _lowercase : Optional[int] = 0 _lowercase : int = [] # load controlnet and append to list until no controlnet directory exists anymore # first controlnet has to be saved under `./mydirectory/controlnet` to be compliant with `DiffusionPipeline.from_prertained` # second, third, ... controlnets have to be saved under `./mydirectory/controlnet_1`, `./mydirectory/controlnet_2`, ... _lowercase : Union[str, Any] = pretrained_model_path while os.path.isdir(lowerCamelCase): _lowercase : Optional[int] = ControlNetModel.from_pretrained(lowerCamelCase, **lowerCamelCase) controlnets.append(lowerCamelCase) idx += 1 _lowercase : List[Any] = pretrained_model_path + F'''_{idx}''' logger.info(F'''{len(lowerCamelCase)} controlnets loaded from {pretrained_model_path}.''') if len(lowerCamelCase) == 0: raise ValueError( F'''No ControlNets found under {os.path.dirname(lowerCamelCase)}. Expected at least {pretrained_model_path + "_0"}.''') return cls(lowerCamelCase)
84
1
"""simple docstring""" import os import time import pytest from datasets.utils.filelock import FileLock, Timeout def lowercase (SCREAMING_SNAKE_CASE_ : int ) -> Union[str, Any]: SCREAMING_SNAKE_CASE = FileLock(str(tmpdir / 'foo.lock' ) ) SCREAMING_SNAKE_CASE = FileLock(str(tmpdir / 'foo.lock' ) ) SCREAMING_SNAKE_CASE = 0.01 with locka.acquire(): with pytest.raises(A__ ): SCREAMING_SNAKE_CASE = time.time() locka.acquire(A__ ) assert time.time() - _start > timeout def lowercase (SCREAMING_SNAKE_CASE_ : Optional[int] ) -> Dict: SCREAMING_SNAKE_CASE = 'a' * 10_00 + '.lock' SCREAMING_SNAKE_CASE = FileLock(str(tmpdir / filename ) ) assert locka._lock_file.endswith('.lock' ) assert not locka._lock_file.endswith(A__ ) assert len(os.path.basename(locka._lock_file ) ) <= 2_55 SCREAMING_SNAKE_CASE = FileLock(tmpdir / filename ) with locka.acquire(): with pytest.raises(A__ ): locka.acquire(0 )
113
import os from itertools import chain from random import randrange, shuffle import pytest from .sola import PokerHand lowerCAmelCase__ : str = ( '''4S 3H 2C 7S 5H''', '''9D 8H 2C 6S 7H''', '''2D 6D 9D TH 7D''', '''TC 8C 2S JH 6C''', '''JH 8S TH AH QH''', '''TS KS 5S 9S AC''', '''KD 6S 9D TH AD''', '''KS 8D 4D 9S 4S''', # pair '''8C 4S KH JS 4D''', # pair '''QH 8H KD JH 8S''', # pair '''KC 4H KS 2H 8D''', # pair '''KD 4S KC 3H 8S''', # pair '''AH 8S AS KC JH''', # pair '''3H 4C 4H 3S 2H''', # 2 pairs '''5S 5D 2C KH KH''', # 2 pairs '''3C KH 5D 5S KH''', # 2 pairs '''AS 3C KH AD KH''', # 2 pairs '''7C 7S 3S 7H 5S''', # 3 of a kind '''7C 7S KH 2H 7H''', # 3 of a kind '''AC KH QH AH AS''', # 3 of a kind '''2H 4D 3C AS 5S''', # straight (low ace) '''3C 5C 4C 2C 6H''', # straight '''6S 8S 7S 5H 9H''', # straight '''JS QS 9H TS KH''', # straight '''QC KH TS JS AH''', # straight (high ace) '''8C 9C 5C 3C TC''', # flush '''3S 8S 9S 5S KS''', # flush '''4C 5C 9C 8C KC''', # flush '''JH 8H AH KH QH''', # flush '''3D 2H 3H 2C 2D''', # full house '''2H 2C 3S 3H 3D''', # full house '''KH KC 3S 3H 3D''', # full house '''JC 6H JS JD JH''', # 4 of a kind '''JC 7H JS JD JH''', # 4 of a kind '''JC KH JS JD JH''', # 4 of a kind '''2S AS 4S 5S 3S''', # straight flush (low ace) '''2D 6D 3D 4D 5D''', # straight flush '''5C 6C 3C 7C 4C''', # straight flush '''JH 9H TH KH QH''', # straight flush '''JH AH TH KH QH''', # royal flush (high ace straight flush) ) lowerCAmelCase__ : Optional[int] = ( ('''2H 3H 4H 5H 6H''', '''KS AS TS QS JS''', '''Loss'''), ('''2H 3H 4H 5H 6H''', '''AS AD AC AH JD''', '''Win'''), ('''AS AH 2H AD AC''', '''JS JD JC JH 3D''', '''Win'''), ('''2S AH 2H AS AC''', '''JS JD JC JH AD''', '''Loss'''), ('''2S AH 2H AS AC''', '''2H 3H 5H 6H 7H''', '''Win'''), ('''AS 3S 4S 8S 2S''', '''2H 3H 5H 6H 7H''', '''Win'''), ('''2H 3H 5H 6H 7H''', '''2S 3H 4H 5S 6C''', '''Win'''), ('''2S 3H 4H 5S 6C''', '''3D 4C 5H 6H 2S''', '''Tie'''), ('''2S 3H 4H 5S 6C''', '''AH AC 5H 6H AS''', '''Win'''), ('''2S 2H 4H 5S 4C''', '''AH AC 5H 6H AS''', '''Loss'''), ('''2S 2H 4H 5S 4C''', '''AH AC 5H 6H 7S''', '''Win'''), ('''6S AD 7H 4S AS''', '''AH AC 5H 6H 7S''', '''Loss'''), ('''2S AH 4H 5S KC''', '''AH AC 5H 6H 7S''', '''Loss'''), ('''2S 3H 6H 7S 9C''', '''7H 3C TH 6H 9S''', '''Loss'''), ('''4S 5H 6H TS AC''', '''3S 5H 6H TS AC''', '''Win'''), ('''2S AH 4H 5S 6C''', '''AD 4C 5H 6H 2C''', '''Tie'''), ('''AS AH 3H AD AC''', '''AS AH 2H AD AC''', '''Win'''), ('''AH AC 5H 5C QS''', '''AH AC 5H 5C KS''', '''Loss'''), ('''AH AC 5H 5C QS''', '''KH KC 5H 5C QS''', '''Win'''), ('''7C 7S KH 2H 7H''', '''3C 3S AH 2H 3H''', '''Win'''), ('''3C 3S AH 2H 3H''', '''7C 7S KH 2H 7H''', '''Loss'''), ('''6H 5H 4H 3H 2H''', '''5H 4H 3H 2H AH''', '''Win'''), ('''5H 4H 3H 2H AH''', '''5H 4H 3H 2H AH''', '''Tie'''), ('''5H 4H 3H 2H AH''', '''6H 5H 4H 3H 2H''', '''Loss'''), ('''AH AD KS KC AC''', '''AH KD KH AC KC''', '''Win'''), ('''2H 4D 3C AS 5S''', '''2H 4D 3C 6S 5S''', '''Loss'''), ('''2H 3S 3C 3H 2S''', '''3S 3C 2S 2H 2D''', '''Win'''), ('''4D 6D 5D 2D JH''', '''3S 8S 3H TC KH''', '''Loss'''), ('''4S 6C 8S 3S 7S''', '''AD KS 2D 7D 7C''', '''Loss'''), ('''6S 4C 7H 8C 3H''', '''5H JC AH 9D 9C''', '''Loss'''), ('''9D 9H JH TC QH''', '''3C 2S JS 5C 7H''', '''Win'''), ('''2H TC 8S AD 9S''', '''4H TS 7H 2C 5C''', '''Win'''), ('''9D 3S 2C 7S 7C''', '''JC TD 3C TC 9H''', '''Loss'''), ) lowerCAmelCase__ : Optional[Any] = ( ('''2H 3H 4H 5H 6H''', True), ('''AS AH 2H AD AC''', False), ('''2H 3H 5H 6H 7H''', True), ('''KS AS TS QS JS''', True), ('''8H 9H QS JS TH''', False), ('''AS 3S 4S 8S 2S''', True), ) lowerCAmelCase__ : List[Any] = ( ('''2H 3H 4H 5H 6H''', True), ('''AS AH 2H AD AC''', False), ('''2H 3H 5H 6H 7H''', False), ('''KS AS TS QS JS''', True), ('''8H 9H QS JS TH''', True), ) lowerCAmelCase__ : Any = ( ('''2H 4D 3C AS 5S''', True, [5, 4, 3, 2, 14]), ('''2H 5D 3C AS 5S''', False, [14, 5, 5, 3, 2]), ('''JH QD KC AS TS''', False, [14, 13, 12, 11, 10]), ('''9D 3S 2C 7S 7C''', False, [9, 7, 7, 3, 2]), ) lowerCAmelCase__ : Dict = ( ('''JH AH TH KH QH''', 0), ('''JH 9H TH KH QH''', 0), ('''JC KH JS JD JH''', 7), ('''KH KC 3S 3H 3D''', 6), ('''8C 9C 5C 3C TC''', 0), ('''JS QS 9H TS KH''', 0), ('''7C 7S KH 2H 7H''', 3), ('''3C KH 5D 5S KH''', 2), ('''QH 8H KD JH 8S''', 1), ('''2D 6D 9D TH 7D''', 0), ) lowerCAmelCase__ : Optional[int] = ( ('''JH AH TH KH QH''', 23), ('''JH 9H TH KH QH''', 22), ('''JC KH JS JD JH''', 21), ('''KH KC 3S 3H 3D''', 20), ('''8C 9C 5C 3C TC''', 19), ('''JS QS 9H TS KH''', 18), ('''7C 7S KH 2H 7H''', 17), ('''3C KH 5D 5S KH''', 16), ('''QH 8H KD JH 8S''', 15), ('''2D 6D 9D TH 7D''', 14), ) def UpperCamelCase__ ( ) -> Any: snake_case__ , snake_case__ : List[str] = randrange(len(A__ ) ), randrange(len(A__ ) ) snake_case__ : str = ['Loss', 'Tie', 'Win'][(play >= oppo) + (play > oppo)] snake_case__ , snake_case__ : Any = SORTED_HANDS[play], SORTED_HANDS[oppo] return hand, other, expected def UpperCamelCase__ ( A__ = 100 ) -> Optional[int]: return (generate_random_hand() for _ in range(A__ )) @pytest.mark.parametrize('hand, expected' , A__ ) def UpperCamelCase__ ( A__ , A__ ) -> Union[str, Any]: assert PokerHand(A__ )._is_flush() == expected @pytest.mark.parametrize('hand, expected' , A__ ) def UpperCamelCase__ ( A__ , A__ ) -> Any: assert PokerHand(A__ )._is_straight() == expected @pytest.mark.parametrize('hand, expected, card_values' , A__ ) def UpperCamelCase__ ( A__ , A__ , A__ ) -> Dict: snake_case__ : Optional[int] = PokerHand(A__ ) assert player._is_five_high_straight() == expected assert player._card_values == card_values @pytest.mark.parametrize('hand, expected' , A__ ) def UpperCamelCase__ ( A__ , A__ ) -> str: assert PokerHand(A__ )._is_same_kind() == expected @pytest.mark.parametrize('hand, expected' , A__ ) def UpperCamelCase__ ( A__ , A__ ) -> Optional[Any]: assert PokerHand(A__ )._hand_type == expected @pytest.mark.parametrize('hand, other, expected' , A__ ) def UpperCamelCase__ ( A__ , A__ , A__ ) -> int: assert PokerHand(A__ ).compare_with(PokerHand(A__ ) ) == expected @pytest.mark.parametrize('hand, other, expected' , generate_random_hands() ) def UpperCamelCase__ ( A__ , A__ , A__ ) -> Union[str, Any]: assert PokerHand(A__ ).compare_with(PokerHand(A__ ) ) == expected def UpperCamelCase__ ( ) -> Union[str, Any]: snake_case__ : Union[str, Any] = [PokerHand(A__ ) for hand in SORTED_HANDS] snake_case__ : Optional[Any] = poker_hands.copy() shuffle(A__ ) snake_case__ : Tuple = chain(sorted(A__ ) ) for index, hand in enumerate(A__ ): assert hand == poker_hands[index] def UpperCamelCase__ ( ) -> str: # Test that five high straights are compared correctly. snake_case__ : int = [PokerHand('2D AC 3H 4H 5S' ), PokerHand('2S 3H 4H 5S 6C' )] pokerhands.sort(reverse=A__ ) assert pokerhands[0].__str__() == "2S 3H 4H 5S 6C" def UpperCamelCase__ ( ) -> Union[str, Any]: # Multiple calls to five_high_straight function should still return True # and shouldn't mutate the list in every call other than the first. snake_case__ : Optional[int] = PokerHand('2C 4S AS 3D 5C' ) snake_case__ : Optional[int] = True snake_case__ : Tuple = [5, 4, 3, 2, 14] for _ in range(10 ): assert pokerhand._is_five_high_straight() == expected assert pokerhand._card_values == expected_card_values def UpperCamelCase__ ( ) -> List[str]: # Problem number 54 from Project Euler # Testing from poker_hands.txt file snake_case__ : Any = 0 snake_case__ : Optional[Any] = os.path.abspath(os.path.dirname(A__ ) ) snake_case__ : List[str] = os.path.join(A__ , 'poker_hands.txt' ) with open(A__ ) as file_hand: for line in file_hand: snake_case__ : Tuple = line[:14].strip() snake_case__ : List[str] = line[15:].strip() snake_case__ , snake_case__ : Any = PokerHand(A__ ), PokerHand(A__ ) snake_case__ : Tuple = player.compare_with(A__ ) if output == "Win": answer += 1 assert answer == 376
143
0
"""simple docstring""" import argparse import torch from safetensors.torch import load_file from diffusers import StableDiffusionPipeline def A_ ( _lowerCAmelCase : Union[str, Any], _lowerCAmelCase : Tuple, _lowerCAmelCase : Optional[Any], _lowerCAmelCase : Optional[Any], _lowerCAmelCase : Optional[int] ): """simple docstring""" _a = StableDiffusionPipeline.from_pretrained(_lowerCAmelCase, torch_dtype=torch.floataa ) # load LoRA weight from .safetensors _a = load_file(_lowerCAmelCase ) _a = [] # directly update weight in diffusers model for key in state_dict: # it is suggested to print out the key, it usually will be something like below # "lora_te_text_model_encoder_layers_0_self_attn_k_proj.lora_down.weight" # as we have set the alpha beforehand, so just skip if ".alpha" in key or key in visited: continue if "text" in key: _a = key.split('''.''' )[0].split(LORA_PREFIX_TEXT_ENCODER + '''_''' )[-1].split('''_''' ) _a = pipeline.text_encoder else: _a = key.split('''.''' )[0].split(LORA_PREFIX_UNET + '''_''' )[-1].split('''_''' ) _a = pipeline.unet # find the target layer _a = layer_infos.pop(0 ) while len(_lowerCAmelCase ) > -1: try: _a = curr_layer.__getattr__(_lowerCAmelCase ) if len(_lowerCAmelCase ) > 0: _a = layer_infos.pop(0 ) elif len(_lowerCAmelCase ) == 0: break except Exception: if len(_lowerCAmelCase ) > 0: temp_name += "_" + layer_infos.pop(0 ) else: _a = layer_infos.pop(0 ) _a = [] if "lora_down" in key: pair_keys.append(key.replace('''lora_down''', '''lora_up''' ) ) pair_keys.append(_lowerCAmelCase ) else: pair_keys.append(_lowerCAmelCase ) pair_keys.append(key.replace('''lora_up''', '''lora_down''' ) ) # update weight if len(state_dict[pair_keys[0]].shape ) == 4: _a = state_dict[pair_keys[0]].squeeze(3 ).squeeze(2 ).to(torch.floataa ) _a = state_dict[pair_keys[1]].squeeze(3 ).squeeze(2 ).to(torch.floataa ) curr_layer.weight.data += alpha * torch.mm(_lowerCAmelCase, _lowerCAmelCase ).unsqueeze(2 ).unsqueeze(3 ) else: _a = state_dict[pair_keys[0]].to(torch.floataa ) _a = state_dict[pair_keys[1]].to(torch.floataa ) curr_layer.weight.data += alpha * torch.mm(_lowerCAmelCase, _lowerCAmelCase ) # update visited list for item in pair_keys: visited.append(_lowerCAmelCase ) return pipeline if __name__ == "__main__": __snake_case = argparse.ArgumentParser() parser.add_argument( '''--base_model_path''', default=None, type=str, required=True, help='''Path to the base model in diffusers format.''' ) parser.add_argument( '''--checkpoint_path''', default=None, type=str, required=True, help='''Path to the checkpoint to convert.''' ) parser.add_argument('''--dump_path''', default=None, type=str, required=True, help='''Path to the output model.''') parser.add_argument( '''--lora_prefix_unet''', default='''lora_unet''', type=str, help='''The prefix of UNet weight in safetensors''' ) parser.add_argument( '''--lora_prefix_text_encoder''', default='''lora_te''', type=str, help='''The prefix of text encoder weight in safetensors''', ) parser.add_argument('''--alpha''', default=0.75, type=float, help='''The merging ratio in W = W0 + alpha * deltaW''') parser.add_argument( '''--to_safetensors''', action='''store_true''', help='''Whether to store pipeline in safetensors format or not.''' ) parser.add_argument('''--device''', type=str, help='''Device to use (e.g. cpu, cuda:0, cuda:1, etc.)''') __snake_case = parser.parse_args() __snake_case = args.base_model_path __snake_case = args.checkpoint_path __snake_case = args.dump_path __snake_case = args.lora_prefix_unet __snake_case = args.lora_prefix_text_encoder __snake_case = args.alpha __snake_case = convert(base_model_path, checkpoint_path, lora_prefix_unet, lora_prefix_text_encoder, alpha) __snake_case = pipe.to(args.device) pipe.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
368
"""simple docstring""" from collections.abc import Callable import numpy as np def A_ ( _lowerCAmelCase : Callable, _lowerCAmelCase : float, _lowerCAmelCase : float, _lowerCAmelCase : float, _lowerCAmelCase : float ): """simple docstring""" _a = int(np.ceil((x_end - xa) / step_size ) ) _a = np.zeros((n + 1,) ) _a = ya _a = xa for k in range(_lowerCAmelCase ): _a = y[k] + step_size * ode_func(_lowerCAmelCase, y[k] ) _a = y[k] + ( (step_size / 2) * (ode_func(_lowerCAmelCase, y[k] ) + ode_func(x + step_size, _lowerCAmelCase )) ) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
153
0
'''simple docstring''' import numpy as np import qiskit def A_ ( snake_case = 8 , snake_case = None ): SCREAMING_SNAKE_CASE:str = np.random.default_rng(seed=snake_case ) # Roughly 25% of the qubits will contribute to the key. # So we take more than we need. SCREAMING_SNAKE_CASE:Optional[Any] = 6 * key_len # Measurement basis for Alice's qubits. SCREAMING_SNAKE_CASE:List[Any] = rng.integers(2 , size=snake_case ) # The set of states Alice will prepare. SCREAMING_SNAKE_CASE:int = rng.integers(2 , size=snake_case ) # Measurement basis for Bob's qubits. SCREAMING_SNAKE_CASE:int = rng.integers(2 , size=snake_case ) # Quantum Circuit to simulate BB84 SCREAMING_SNAKE_CASE:List[str] = qiskit.QuantumCircuit(snake_case , name="BB84" ) # Alice prepares her qubits according to rules above. for index, _ in enumerate(snake_case ): if alice_state[index] == 1: bbaa_circ.x(snake_case ) if alice_basis[index] == 1: bbaa_circ.h(snake_case ) bbaa_circ.barrier() # Bob measures the received qubits according to rules above. for index, _ in enumerate(snake_case ): if bob_basis[index] == 1: bbaa_circ.h(snake_case ) bbaa_circ.barrier() bbaa_circ.measure_all() # Simulate the quantum circuit. SCREAMING_SNAKE_CASE:Optional[int] = qiskit.Aer.get_backend("aer_simulator" ) # We only need to run one shot because the key is unique. # Multiple shots will produce the same key. SCREAMING_SNAKE_CASE:int = qiskit.execute(snake_case , snake_case , shots=1 , seed_simulator=snake_case ) # Returns the result of measurement. SCREAMING_SNAKE_CASE:int = job.result().get_counts(snake_case ).most_frequent() # Extracting the generated key from the simulation results. # Only keep measurement results where Alice and Bob chose the same basis. SCREAMING_SNAKE_CASE:int = "".join( [ result_bit for alice_basis_bit, bob_basis_bit, result_bit in zip( snake_case , snake_case , snake_case ) if alice_basis_bit == bob_basis_bit ] ) # Get final key. Pad with 0 if too short, otherwise truncate. SCREAMING_SNAKE_CASE:List[Any] = gen_key[:key_len] if len(snake_case ) >= key_len else gen_key.ljust(snake_case , "0" ) return key if __name__ == "__main__": print(f'''The generated key is : {bbaa(8, seed=0)}''') from doctest import testmod testmod()
139
'''simple docstring''' import numpy # List of input, output pairs A_ = ( ((5, 2, 3), 15), ((6, 5, 9), 25), ((11, 12, 13), 41), ((1, 1, 1), 8), ((11, 12, 13), 41), ) A_ = (((5_15, 22, 13), 5_55), ((61, 35, 49), 1_50)) A_ = [2, 4, 1, 5] A_ = len(train_data) A_ = 0.009 def A_ ( snake_case , snake_case="train" ): return calculate_hypothesis_value(snake_case , snake_case ) - output( snake_case , snake_case ) def A_ ( snake_case ): SCREAMING_SNAKE_CASE:Any = 0 for i in range(len(snake_case ) - 1 ): hyp_val += data_input_tuple[i] * parameter_vector[i + 1] hyp_val += parameter_vector[0] return hyp_val def A_ ( snake_case , snake_case ): if data_set == "train": return train_data[example_no][1] elif data_set == "test": return test_data[example_no][1] return None def A_ ( snake_case , snake_case ): if data_set == "train": return _hypothesis_value(train_data[example_no][0] ) elif data_set == "test": return _hypothesis_value(test_data[example_no][0] ) return None def A_ ( snake_case , snake_case=m ): SCREAMING_SNAKE_CASE:Dict = 0 for i in range(snake_case ): if index == -1: summation_value += _error(snake_case ) else: summation_value += _error(snake_case ) * train_data[i][0][index] return summation_value def A_ ( snake_case ): SCREAMING_SNAKE_CASE:int = summation_of_cost_derivative(snake_case , snake_case ) / m return cost_derivative_value def A_ ( ): global parameter_vector # Tune these values to set a tolerance value for predicted output SCREAMING_SNAKE_CASE:List[str] = 0.00_0002 SCREAMING_SNAKE_CASE:Union[str, Any] = 0 SCREAMING_SNAKE_CASE:Union[str, Any] = 0 while True: j += 1 SCREAMING_SNAKE_CASE:List[str] = [0, 0, 0, 0] for i in range(0 , len(snake_case ) ): SCREAMING_SNAKE_CASE:Union[str, Any] = get_cost_derivative(i - 1 ) SCREAMING_SNAKE_CASE:Union[str, Any] = ( parameter_vector[i] - LEARNING_RATE * cost_derivative ) if numpy.allclose( snake_case , snake_case , atol=snake_case , rtol=snake_case , ): break SCREAMING_SNAKE_CASE:List[str] = temp_parameter_vector print(("Number of iterations:", j) ) def A_ ( ): for i in range(len(snake_case ) ): print(("Actual output value:", output(snake_case , "test" )) ) print(("Hypothesis output:", calculate_hypothesis_value(snake_case , "test" )) ) if __name__ == "__main__": run_gradient_descent() print("\nTesting gradient descent for a linear hypothesis function.\n") test_gradient_descent()
139
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 : Tuple ) -> str: """simple docstring""" return EnvironmentCommand() def __UpperCAmelCase ( __a : Union[str, Any] ) -> str: """simple docstring""" return EnvironmentCommand(args.accelerate_config_file ) class UpperCAmelCase_ ( __lowercase ): """simple docstring""" @staticmethod def __lowercase ( _a ) -> int: _a : str = 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 , _a , *_a ) -> None: _a : Union[str, Any] = accelerate_config_file def __lowercase ( self ) -> Optional[int]: _a : Tuple = '''not installed''' if is_safetensors_available(): import safetensors _a : Dict = safetensors.__version__ elif importlib.util.find_spec('''safetensors''' ) is not None: import safetensors _a : str = F"""{safetensors.__version__} but is ignored because of PyTorch version too old.""" _a : Optional[Any] = '''not installed''' _a : List[Any] = '''not found''' if is_accelerate_available(): import accelerate from accelerate.commands.config import default_config_file, load_config_from_file _a : Optional[int] = accelerate.__version__ # Get the default from the config file. if self._accelerate_config_file is not None or os.path.isfile(_a ): _a : Optional[int] = load_config_from_file(self._accelerate_config_file ).to_dict() _a : Optional[int] = ( '''\n'''.join([F"""\t- {prop}: {val}""" for prop, val in accelerate_config.items()] ) if isinstance(_a , _a ) else F"""\t{accelerate_config}""" ) _a : Tuple = '''not installed''' _a : Tuple = '''NA''' if is_torch_available(): import torch _a : str = torch.__version__ _a : int = torch.cuda.is_available() _a : List[Any] = '''not installed''' _a : Optional[Any] = '''NA''' if is_tf_available(): import tensorflow as tf _a : int = tf.__version__ try: # deprecated in v2.1 _a : Dict = tf.test.is_gpu_available() except AttributeError: # returns list of devices, convert to bool _a : List[str] = bool(tf.config.list_physical_devices('''GPU''' ) ) _a : Dict = '''not installed''' _a : Optional[Any] = '''not installed''' _a : Optional[Any] = '''not installed''' _a : List[Any] = '''NA''' if is_flax_available(): import flax import jax import jaxlib _a : Optional[Any] = flax.__version__ _a : Union[str, Any] = jax.__version__ _a : Union[str, Any] = jaxlib.__version__ _a : Tuple = jax.lib.xla_bridge.get_backend().platform _a : Tuple = { '''`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 __lowercase ( _a ) -> Optional[int]: return "\n".join([F"""- {prop}: {val}""" for prop, val in d.items()] ) + "\n"
15
import numpy as np def __UpperCAmelCase ( __a : np.ndarray ,__a : np.ndarray ,__a : float = 1E-12 ,__a : int = 100 ,) -> tuple[float, np.ndarray]: """simple docstring""" assert np.shape(__a )[0] == np.shape(__a )[1] # Ensure proper dimensionality. assert np.shape(__a )[0] == np.shape(__a )[0] # Ensure inputs are either both complex or both real assert np.iscomplexobj(__a ) == np.iscomplexobj(__a ) _a : List[str] = np.iscomplexobj(__a ) if is_complex: # Ensure complex input_matrix is Hermitian assert np.array_equal(__a ,input_matrix.conj().T ) # Set convergence to False. Will define convergence when we exceed max_iterations # or when we have small changes from one iteration to next. _a : List[str] = False _a : List[str] = 0 _a : Tuple = 0 _a : str = 1E12 while not convergence: # Multiple matrix by the vector. _a : str = np.dot(__a ,__a ) # Normalize the resulting output vector. _a : List[Any] = w / np.linalg.norm(__a ) # Find rayleigh quotient # (faster than usual b/c we know vector is normalized already) _a : Dict = vector.conj().T if is_complex else vector.T _a : Tuple = np.dot(__a ,np.dot(__a ,__a ) ) # Check convergence. _a : List[str] = np.abs(lambda_ - lambda_previous ) / lambda_ iterations += 1 if error <= error_tol or iterations >= max_iterations: _a : Dict = True _a : str = lambda_ if is_complex: _a : Tuple = np.real(lambda_ ) return lambda_, vector def __UpperCAmelCase ( ) -> None: """simple docstring""" _a : List[str] = np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]] ) _a : int = np.array([41, 4, 20] ) _a : Optional[Any] = real_input_matrix.astype(np.complexaaa ) _a : int = np.triu(1j * complex_input_matrix ,1 ) complex_input_matrix += imag_matrix complex_input_matrix += -1 * imag_matrix.T _a : Union[str, Any] = np.array([41, 4, 20] ).astype(np.complexaaa ) for problem_type in ["real", "complex"]: if problem_type == "real": _a : Optional[int] = real_input_matrix _a : Union[str, Any] = real_vector elif problem_type == "complex": _a : str = complex_input_matrix _a : str = complex_vector # Our implementation. _a , _a : Optional[Any] = power_iteration(__a ,__a ) # Numpy implementation. # Get eigenvalues and eigenvectors using built-in numpy # eigh (eigh used for symmetric or hermetian matrices). _a , _a : List[str] = np.linalg.eigh(__a ) # Last eigenvalue is the maximum one. _a : Tuple = eigen_values[-1] # Last column in this matrix is eigenvector corresponding to largest eigenvalue. _a : List[Any] = eigen_vectors[:, -1] # Check our implementation and numpy gives close answers. assert np.abs(eigen_value - eigen_value_max ) <= 1E-6 # Take absolute values element wise of each eigenvector. # as they are only unique to a minus sign. assert np.linalg.norm(np.abs(__a ) - np.abs(__a ) ) <= 1E-6 if __name__ == "__main__": import doctest doctest.testmod() test_power_iteration()
15
1
'''simple docstring''' import random import unittest import torch from diffusers import IFInpaintingSuperResolutionPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin from . import IFPipelineTesterMixin @skip_mps class snake_case ( lowercase , lowercase , unittest.TestCase ): """simple docstring""" _lowerCamelCase = IFInpaintingSuperResolutionPipeline _lowerCamelCase = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {"width", "height"} _lowerCamelCase = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS.union({"original_image"} ) _lowerCamelCase = PipelineTesterMixin.required_optional_params - {"latents"} def snake_case ( self ): """simple docstring""" return self._get_superresolution_dummy_components() def snake_case ( self , UpperCamelCase , UpperCamelCase=0 ): """simple docstring""" if str(UpperCamelCase ).startswith("mps" ): lowerCamelCase_ = torch.manual_seed(UpperCamelCase ) else: lowerCamelCase_ = torch.Generator(device=UpperCamelCase ).manual_seed(UpperCamelCase ) lowerCamelCase_ = floats_tensor((1, 3, 16, 16) , rng=random.Random(UpperCamelCase ) ).to(UpperCamelCase ) lowerCamelCase_ = floats_tensor((1, 3, 32, 32) , rng=random.Random(UpperCamelCase ) ).to(UpperCamelCase ) lowerCamelCase_ = floats_tensor((1, 3, 32, 32) , rng=random.Random(UpperCamelCase ) ).to(UpperCamelCase ) lowerCamelCase_ = { "prompt": "A painting of a squirrel eating a burger", "image": image, "original_image": original_image, "mask_image": mask_image, "generator": generator, "num_inference_steps": 2, "output_type": "numpy", } return inputs @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def snake_case ( self ): """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 ) def snake_case ( self ): """simple docstring""" self._test_save_load_optional_components() @unittest.skipIf(torch_device != "cuda" , reason="float16 requires CUDA" ) def snake_case ( self ): """simple docstring""" # Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder super().test_save_load_floataa(expected_max_diff=1e-1 ) def snake_case ( self ): """simple docstring""" self._test_attention_slicing_forward_pass(expected_max_diff=1e-2 ) def snake_case ( self ): """simple docstring""" self._test_save_load_local() def snake_case ( self ): """simple docstring""" self._test_inference_batch_single_identical( expected_max_diff=1e-2 , )
55
'''simple docstring''' import math def __snake_case ( UpperCAmelCase_ : int ): lowerCamelCase_ = math.loga(math.sqrt(4 * positive_integer + 1 ) / 2 + 1 / 2 ) return exponent == int(UpperCAmelCase_ ) def __snake_case ( UpperCAmelCase_ : float = 1 / 12345 ): lowerCamelCase_ = 0 lowerCamelCase_ = 0 lowerCamelCase_ = 3 while True: lowerCamelCase_ = (integer**2 - 1) / 4 # if candidate is an integer, then there is a partition for k if partition_candidate == int(UpperCAmelCase_ ): lowerCamelCase_ = int(UpperCAmelCase_ ) total_partitions += 1 if check_partition_perfect(UpperCAmelCase_ ): perfect_partitions += 1 if perfect_partitions > 0: if perfect_partitions / total_partitions < max_proportion: return int(UpperCAmelCase_ ) integer += 1 if __name__ == "__main__": print(f'''{solution() = }''')
55
1
import os import pytest from attr import dataclass _A : Optional[Any] = 'us-east-1' # defaults region @dataclass class __SCREAMING_SNAKE_CASE : _UpperCAmelCase : str _UpperCAmelCase : List[str] = "arn:aws:iam::558105141721:role/sagemaker_execution_role" _UpperCAmelCase : Tuple = { "task_name": "mnli", "per_device_train_batch_size": 1_6, "per_device_eval_batch_size": 1_6, "do_train": True, "do_eval": True, "do_predict": True, "output_dir": "/opt/ml/model", "overwrite_output_dir": True, "max_steps": 5_0_0, "save_steps": 5_5_0_0, } _UpperCAmelCase : Dict = {**hyperparameters, "max_steps": 1_0_0_0} @property def __lowerCamelCase ( self : Optional[int] ) ->str: if self.framework == "pytorch": return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"eval_accuracy.*=\D*(.*?)$"}, {"Name": "eval_loss", "Regex": r"eval_loss.*=\D*(.*?)$"}, ] else: return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"loss.*=\D*(.*?)]?$"}, {"Name": "eval_loss", "Regex": r"sparse_categorical_accuracy.*=\D*(.*?)]?$"}, ] @property def __lowerCamelCase ( self : List[Any] ) ->str: return F"{self.framework}-transfromers-test" @property def __lowerCamelCase ( self : int ) ->str: return F"./tests/sagemaker/scripts/{self.framework}" @property def __lowerCamelCase ( self : Tuple ) ->str: if self.framework == "pytorch": return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-pytorch-training:1.7.1-transformers4.6.1-gpu-py36-cu110-ubuntu18.04" else: return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-tensorflow-training:2.4.1-transformers4.6.1-gpu-py37-cu110-ubuntu18.04" @pytest.fixture(scope='''class''' ) def _a ( UpperCAmelCase ) -> Tuple: """simple docstring""" lowerCamelCase__ : int = SageMakerTestEnvironment(framework=request.cls.framework )
265
from math import ceil, sqrt def _a ( UpperCAmelCase = 1000000 ) -> int: """simple docstring""" lowerCamelCase__ : Any = 0 for outer_width in range(3 , (limit // 4) + 2 ): if outer_width**2 > limit: lowerCamelCase__ : List[Any] = max(ceil(sqrt(outer_width**2 - limit ) ) , 1 ) else: lowerCamelCase__ : Union[str, Any] = 1 if (outer_width - hole_width_lower_bound) % 2: hole_width_lower_bound += 1 answer += (outer_width - hole_width_lower_bound - 2) // 2 + 1 return answer if __name__ == "__main__": print(F'''{solution() = }''')
265
1
"""simple docstring""" import copy import os from collections import OrderedDict from typing import TYPE_CHECKING, Any, Dict, Mapping, Optional, Union if TYPE_CHECKING: from ...processing_utils import ProcessorMixin from ...utils import TensorType from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { 'google/owlvit-base-patch32': 'https://huggingface.co/google/owlvit-base-patch32/resolve/main/config.json', 'google/owlvit-base-patch16': 'https://huggingface.co/google/owlvit-base-patch16/resolve/main/config.json', 'google/owlvit-large-patch14': 'https://huggingface.co/google/owlvit-large-patch14/resolve/main/config.json', } class _SCREAMING_SNAKE_CASE ( A__ ): UpperCAmelCase_ :Dict = "owlvit_text_model" def __init__( self , __A=4_9408 , __A=512 , __A=2048 , __A=12 , __A=8 , __A=16 , __A="quick_gelu" , __A=1E-5 , __A=0.0 , __A=0.0_2 , __A=1.0 , __A=0 , __A=4_9406 , __A=4_9407 , **__A , ) -> Union[str, Any]: super().__init__(pad_token_id=__A , bos_token_id=__A , eos_token_id=__A , **__A ) lowerCAmelCase_ :List[str] = vocab_size lowerCAmelCase_ :Dict = hidden_size lowerCAmelCase_ :str = intermediate_size lowerCAmelCase_ :str = num_hidden_layers lowerCAmelCase_ :int = num_attention_heads lowerCAmelCase_ :Any = max_position_embeddings lowerCAmelCase_ :List[str] = hidden_act lowerCAmelCase_ :str = layer_norm_eps lowerCAmelCase_ :Any = attention_dropout lowerCAmelCase_ :str = initializer_range lowerCAmelCase_ :str = initializer_factor @classmethod def __lowerCAmelCase ( cls , __A , **__A ) -> "PretrainedConfig": cls._set_token_in_kwargs(__A ) lowerCAmelCase_ , lowerCAmelCase_ :Optional[Any] = cls.get_config_dict(__A , **__A ) # get the text config dict if we are loading from OwlViTConfig if config_dict.get("""model_type""" ) == "owlvit": lowerCAmelCase_ :Optional[int] = config_dict["""text_config"""] if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( f"""You are using a model of type {config_dict["model_type"]} to instantiate a model of type """ f"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" ) return cls.from_dict(__A , **__A ) class _SCREAMING_SNAKE_CASE ( A__ ): UpperCAmelCase_ :str = "owlvit_vision_model" def __init__( self , __A=768 , __A=3072 , __A=12 , __A=12 , __A=3 , __A=768 , __A=32 , __A="quick_gelu" , __A=1E-5 , __A=0.0 , __A=0.0_2 , __A=1.0 , **__A , ) -> Any: super().__init__(**__A ) lowerCAmelCase_ :int = hidden_size lowerCAmelCase_ :Optional[int] = intermediate_size lowerCAmelCase_ :Dict = num_hidden_layers lowerCAmelCase_ :int = num_attention_heads lowerCAmelCase_ :Optional[int] = num_channels lowerCAmelCase_ :Any = image_size lowerCAmelCase_ :Union[str, Any] = patch_size lowerCAmelCase_ :Optional[int] = hidden_act lowerCAmelCase_ :int = layer_norm_eps lowerCAmelCase_ :Tuple = attention_dropout lowerCAmelCase_ :Tuple = initializer_range lowerCAmelCase_ :Dict = initializer_factor @classmethod def __lowerCAmelCase ( cls , __A , **__A ) -> "PretrainedConfig": cls._set_token_in_kwargs(__A ) lowerCAmelCase_ , lowerCAmelCase_ :Optional[Any] = cls.get_config_dict(__A , **__A ) # get the vision config dict if we are loading from OwlViTConfig if config_dict.get("""model_type""" ) == "owlvit": lowerCAmelCase_ :List[Any] = config_dict["""vision_config"""] if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( f"""You are using a model of type {config_dict["model_type"]} to instantiate a model of type """ f"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" ) return cls.from_dict(__A , **__A ) class _SCREAMING_SNAKE_CASE ( A__ ): UpperCAmelCase_ :str = "owlvit" UpperCAmelCase_ :int = True def __init__( self , __A=None , __A=None , __A=512 , __A=2.6_5_9_2 , __A=True , **__A , ) -> Tuple: super().__init__(**__A ) if text_config is None: lowerCAmelCase_ :Optional[Any] = {} logger.info("""text_config is None. Initializing the OwlViTTextConfig with default values.""" ) if vision_config is None: lowerCAmelCase_ :List[Any] = {} logger.info("""vision_config is None. initializing the OwlViTVisionConfig with default values.""" ) lowerCAmelCase_ :Tuple = OwlViTTextConfig(**__A ) lowerCAmelCase_ :Dict = OwlViTVisionConfig(**__A ) lowerCAmelCase_ :Any = projection_dim lowerCAmelCase_ :int = logit_scale_init_value lowerCAmelCase_ :List[str] = return_dict lowerCAmelCase_ :Optional[int] = 1.0 @classmethod def __lowerCAmelCase ( cls , __A , **__A ) -> "PretrainedConfig": cls._set_token_in_kwargs(__A ) lowerCAmelCase_ , lowerCAmelCase_ :Optional[int] = cls.get_config_dict(__A , **__A ) if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( f"""You are using a model of type {config_dict["model_type"]} to instantiate a model of type """ f"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" ) return cls.from_dict(__A , **__A ) @classmethod def __lowerCAmelCase ( cls , __A , __A , **__A ) -> Optional[int]: lowerCAmelCase_ :Optional[int] = {} lowerCAmelCase_ :int = text_config lowerCAmelCase_ :Dict = vision_config return cls.from_dict(__A , **__A ) def __lowerCAmelCase ( self ) -> Any: lowerCAmelCase_ :List[Any] = copy.deepcopy(self.__dict__ ) lowerCAmelCase_ :str = self.text_config.to_dict() lowerCAmelCase_ :Tuple = self.vision_config.to_dict() lowerCAmelCase_ :Optional[int] = self.__class__.model_type return output class _SCREAMING_SNAKE_CASE ( A__ ): @property def __lowerCAmelCase ( self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ("""input_ids""", {0: """batch""", 1: """sequence"""}), ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ("""attention_mask""", {0: """batch""", 1: """sequence"""}), ] ) @property def __lowerCAmelCase ( self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ("""logits_per_image""", {0: """batch"""}), ("""logits_per_text""", {0: """batch"""}), ("""text_embeds""", {0: """batch"""}), ("""image_embeds""", {0: """batch"""}), ] ) @property def __lowerCAmelCase ( self ) -> float: return 1E-4 def __lowerCAmelCase ( self , __A , __A = -1 , __A = -1 , __A = None , ) -> Mapping[str, Any]: lowerCAmelCase_ :Tuple = super().generate_dummy_inputs( processor.tokenizer , batch_size=__A , seq_length=__A , framework=__A ) lowerCAmelCase_ :Tuple = super().generate_dummy_inputs( processor.image_processor , batch_size=__A , framework=__A ) return {**text_input_dict, **image_input_dict} @property def __lowerCAmelCase ( self ) -> int: return 14
84
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { 'facebook/levit-128S': 'https://huggingface.co/facebook/levit-128S/resolve/main/config.json', # See all LeViT models at https://huggingface.co/models?filter=levit } class _SCREAMING_SNAKE_CASE ( A__ ): UpperCAmelCase_ :str = "levit" def __init__( self , __A=224 , __A=3 , __A=3 , __A=2 , __A=1 , __A=16 , __A=[128, 256, 384] , __A=[4, 8, 12] , __A=[4, 4, 4] , __A=[16, 16, 16] , __A=0 , __A=[2, 2, 2] , __A=[2, 2, 2] , __A=0.0_2 , **__A , ) -> Any: super().__init__(**__A ) lowerCAmelCase_ :Tuple = image_size lowerCAmelCase_ :Optional[int] = num_channels lowerCAmelCase_ :Union[str, Any] = kernel_size lowerCAmelCase_ :Optional[Any] = stride lowerCAmelCase_ :Optional[int] = padding lowerCAmelCase_ :Optional[Any] = hidden_sizes lowerCAmelCase_ :Optional[int] = num_attention_heads lowerCAmelCase_ :int = depths lowerCAmelCase_ :List[str] = key_dim lowerCAmelCase_ :str = drop_path_rate lowerCAmelCase_ :Optional[int] = patch_size lowerCAmelCase_ :Union[str, Any] = attention_ratio lowerCAmelCase_ :Dict = mlp_ratio lowerCAmelCase_ :Any = initializer_range lowerCAmelCase_ :Optional[int] = [ ["""Subsample""", key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2], ["""Subsample""", key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2], ] class _SCREAMING_SNAKE_CASE ( A__ ): UpperCAmelCase_ :Tuple = version.parse("1.11" ) @property def __lowerCAmelCase ( self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def __lowerCAmelCase ( self ) -> float: return 1E-4
84
1
'''simple docstring''' from collections import OrderedDict from typing import TYPE_CHECKING, Any, List, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import TensorType, logging if TYPE_CHECKING: from ...onnx.config import PatchingSpec from ...tokenization_utils_base import PreTrainedTokenizerBase __A : Optional[int] = logging.get_logger(__name__) __A : Any = { 'allenai/longformer-base-4096': 'https://huggingface.co/allenai/longformer-base-4096/resolve/main/config.json', 'allenai/longformer-large-4096': 'https://huggingface.co/allenai/longformer-large-4096/resolve/main/config.json', 'allenai/longformer-large-4096-finetuned-triviaqa': ( 'https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/config.json' ), 'allenai/longformer-base-4096-extra.pos.embd.only': ( 'https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/config.json' ), 'allenai/longformer-large-4096-extra.pos.embd.only': ( 'https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/config.json' ), } class __UpperCamelCase ( __snake_case ): lowercase : List[Any] = "longformer" def __init__( self :Optional[int] ,_UpperCamelCase :Union[List[int], int] = 5_1_2 ,_UpperCamelCase :int = 2 ,_UpperCamelCase :int = 1 ,_UpperCamelCase :int = 0 ,_UpperCamelCase :int = 2 ,_UpperCamelCase :int = 3_0_5_2_2 ,_UpperCamelCase :int = 7_6_8 ,_UpperCamelCase :int = 1_2 ,_UpperCamelCase :int = 1_2 ,_UpperCamelCase :int = 3_0_7_2 ,_UpperCamelCase :str = "gelu" ,_UpperCamelCase :float = 0.1 ,_UpperCamelCase :float = 0.1 ,_UpperCamelCase :int = 5_1_2 ,_UpperCamelCase :int = 2 ,_UpperCamelCase :float = 0.02 ,_UpperCamelCase :float = 1E-1_2 ,_UpperCamelCase :bool = False ,**_UpperCamelCase :int ,): super().__init__(pad_token_id=lowerCamelCase_ ,**lowerCamelCase_ ) snake_case_ : Optional[Any] = attention_window snake_case_ : Optional[Any] = sep_token_id snake_case_ : int = bos_token_id snake_case_ : int = eos_token_id snake_case_ : Union[str, Any] = vocab_size snake_case_ : str = hidden_size snake_case_ : Optional[int] = num_hidden_layers snake_case_ : List[str] = num_attention_heads snake_case_ : List[str] = hidden_act snake_case_ : Tuple = intermediate_size snake_case_ : Union[str, Any] = hidden_dropout_prob snake_case_ : Optional[Any] = attention_probs_dropout_prob snake_case_ : int = max_position_embeddings snake_case_ : Union[str, Any] = type_vocab_size snake_case_ : str = initializer_range snake_case_ : Union[str, Any] = layer_norm_eps snake_case_ : List[str] = onnx_export class __UpperCamelCase ( __snake_case ): def __init__( self :Dict ,_UpperCamelCase :"PretrainedConfig" ,_UpperCamelCase :str = "default" ,_UpperCamelCase :"List[PatchingSpec]" = None ): super().__init__(lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ) snake_case_ : Any = True @property def a__ ( self :Optional[Any] ): if self.task == "multiple-choice": snake_case_ : List[str] = {0: """batch""", 1: """choice""", 2: """sequence"""} else: snake_case_ : str = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""global_attention_mask""", dynamic_axis), ] ) @property def a__ ( self :Any ): snake_case_ : Tuple = super().outputs if self.task == "default": snake_case_ : int = {0: """batch"""} return outputs @property def a__ ( self :List[str] ): return 1E-4 @property def a__ ( self :Any ): # needs to be >= 14 to support tril operator return max(super().default_onnx_opset ,1_4 ) def a__ ( self :List[str] ,_UpperCamelCase :"PreTrainedTokenizerBase" ,_UpperCamelCase :int = -1 ,_UpperCamelCase :int = -1 ,_UpperCamelCase :bool = False ,_UpperCamelCase :Optional[TensorType] = None ,): snake_case_ : List[Any] = super().generate_dummy_inputs( preprocessor=lowerCamelCase_ ,batch_size=lowerCamelCase_ ,seq_length=lowerCamelCase_ ,is_pair=lowerCamelCase_ ,framework=lowerCamelCase_ ) import torch # for some reason, replacing this code by inputs["global_attention_mask"] = torch.randint(2, inputs["input_ids"].shape, dtype=torch.int64) # makes the export fail randomly snake_case_ : str = torch.zeros_like(inputs["""input_ids"""] ) # make every second token global snake_case_ : Dict = 1 return inputs
364
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __A : int = { 'configuration_whisper': ['WHISPER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'WhisperConfig', 'WhisperOnnxConfig'], 'feature_extraction_whisper': ['WhisperFeatureExtractor'], 'processing_whisper': ['WhisperProcessor'], 'tokenization_whisper': ['WhisperTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Union[str, Any] = ['WhisperTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Any = [ 'WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST', 'WhisperForConditionalGeneration', 'WhisperModel', 'WhisperPreTrainedModel', 'WhisperForAudioClassification', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : List[Any] = [ 'TF_WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFWhisperForConditionalGeneration', 'TFWhisperModel', 'TFWhisperPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Union[str, Any] = [ 'FlaxWhisperForConditionalGeneration', 'FlaxWhisperModel', 'FlaxWhisperPreTrainedModel', 'FlaxWhisperForAudioClassification', ] if TYPE_CHECKING: from .configuration_whisper import WHISPER_PRETRAINED_CONFIG_ARCHIVE_MAP, WhisperConfig, WhisperOnnxConfig from .feature_extraction_whisper import WhisperFeatureExtractor from .processing_whisper import WhisperProcessor from .tokenization_whisper import WhisperTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_whisper_fast import WhisperTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_whisper import ( WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST, WhisperForAudioClassification, WhisperForConditionalGeneration, WhisperModel, WhisperPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_whisper import ( TF_WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST, TFWhisperForConditionalGeneration, TFWhisperModel, TFWhisperPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_whisper import ( FlaxWhisperForAudioClassification, FlaxWhisperForConditionalGeneration, FlaxWhisperModel, FlaxWhisperPreTrainedModel, ) else: import sys __A : str = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
8
0
import argparse import torch from transformers import ( SpeechTaConfig, SpeechTaFeatureExtractor, SpeechTaForSpeechToSpeech, SpeechTaForSpeechToText, SpeechTaForTextToSpeech, SpeechTaProcessor, SpeechTaTokenizer, logging, ) from transformers.tokenization_utils import AddedToken logging.set_verbosity_info() _a = logging.get_logger('''transformers.models.speecht5''') _a = { '''speech_encoder_prenet.layer_norm''': '''speecht5.encoder.prenet.feature_projection.layer_norm''', '''speech_encoder_prenet.post_extract_proj''': '''speecht5.encoder.prenet.feature_projection.projection''', '''speech_encoder_prenet.pos_conv.0''': '''speecht5.encoder.prenet.pos_conv_embed.conv''', '''speech_encoder_prenet.mask_emb''': '''speecht5.encoder.prenet.masked_spec_embed''', } _a = { '''text_encoder_prenet.encoder_prenet.0''': '''speecht5.encoder.prenet.embed_tokens''', '''text_encoder_prenet.encoder_prenet.1.alpha''': '''speecht5.encoder.prenet.encode_positions.alpha''', } _a = { '''speech_decoder_prenet.decoder_prenet.0.0.prenet.0.0''': '''speecht5.decoder.prenet.layers.0''', '''speech_decoder_prenet.decoder_prenet.0.0.prenet.1.0''': '''speecht5.decoder.prenet.layers.1''', '''speech_decoder_prenet.decoder_prenet.0.1''': '''speecht5.decoder.prenet.final_layer''', '''speech_decoder_prenet.decoder_prenet.1.alpha''': '''speecht5.decoder.prenet.encode_positions.alpha''', '''speech_decoder_prenet.spkembs_layer.0''': '''speecht5.decoder.prenet.speaker_embeds_layer''', } _a = { '''speech_decoder_postnet.feat_out''': '''speech_decoder_postnet.feat_out''', '''speech_decoder_postnet.prob_out''': '''speech_decoder_postnet.prob_out''', '''speech_decoder_postnet.postnet.postnet.0.0''': '''speech_decoder_postnet.layers.0.conv''', '''speech_decoder_postnet.postnet.postnet.0.1''': '''speech_decoder_postnet.layers.0.batch_norm''', '''speech_decoder_postnet.postnet.postnet.1.0''': '''speech_decoder_postnet.layers.1.conv''', '''speech_decoder_postnet.postnet.postnet.1.1''': '''speech_decoder_postnet.layers.1.batch_norm''', '''speech_decoder_postnet.postnet.postnet.2.0''': '''speech_decoder_postnet.layers.2.conv''', '''speech_decoder_postnet.postnet.postnet.2.1''': '''speech_decoder_postnet.layers.2.batch_norm''', '''speech_decoder_postnet.postnet.postnet.3.0''': '''speech_decoder_postnet.layers.3.conv''', '''speech_decoder_postnet.postnet.postnet.3.1''': '''speech_decoder_postnet.layers.3.batch_norm''', '''speech_decoder_postnet.postnet.postnet.4.0''': '''speech_decoder_postnet.layers.4.conv''', '''speech_decoder_postnet.postnet.postnet.4.1''': '''speech_decoder_postnet.layers.4.batch_norm''', } _a = { '''text_decoder_prenet.embed_tokens''': '''speecht5.decoder.prenet.embed_tokens''', } _a = { '''text_decoder_postnet.output_projection''': '''text_decoder_postnet.lm_head''', } _a = { '''encoder.layers.*.self_attn.k_proj''': '''speecht5.encoder.wrapped_encoder.layers.*.attention.k_proj''', '''encoder.layers.*.self_attn.v_proj''': '''speecht5.encoder.wrapped_encoder.layers.*.attention.v_proj''', '''encoder.layers.*.self_attn.q_proj''': '''speecht5.encoder.wrapped_encoder.layers.*.attention.q_proj''', '''encoder.layers.*.self_attn.out_proj''': '''speecht5.encoder.wrapped_encoder.layers.*.attention.out_proj''', '''encoder.layers.*.self_attn_layer_norm''': '''speecht5.encoder.wrapped_encoder.layers.*.layer_norm''', '''encoder.layers.*.fc1''': '''speecht5.encoder.wrapped_encoder.layers.*.feed_forward.intermediate_dense''', '''encoder.layers.*.fc2''': '''speecht5.encoder.wrapped_encoder.layers.*.feed_forward.output_dense''', '''encoder.layers.*.final_layer_norm''': '''speecht5.encoder.wrapped_encoder.layers.*.final_layer_norm''', '''encoder.layer_norm''': '''speecht5.encoder.wrapped_encoder.layer_norm''', '''encoder.pos_emb.pe_k''': '''speecht5.encoder.wrapped_encoder.embed_positions.pe_k''', } _a = { '''decoder.layers.*.self_attn.k_proj''': '''speecht5.decoder.wrapped_decoder.layers.*.self_attn.k_proj''', '''decoder.layers.*.self_attn.v_proj''': '''speecht5.decoder.wrapped_decoder.layers.*.self_attn.v_proj''', '''decoder.layers.*.self_attn.q_proj''': '''speecht5.decoder.wrapped_decoder.layers.*.self_attn.q_proj''', '''decoder.layers.*.self_attn.out_proj''': '''speecht5.decoder.wrapped_decoder.layers.*.self_attn.out_proj''', '''decoder.layers.*.self_attn_layer_norm''': '''speecht5.decoder.wrapped_decoder.layers.*.self_attn_layer_norm''', '''decoder.layers.*.encoder_attn.k_proj''': '''speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.k_proj''', '''decoder.layers.*.encoder_attn.v_proj''': '''speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.v_proj''', '''decoder.layers.*.encoder_attn.q_proj''': '''speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.q_proj''', '''decoder.layers.*.encoder_attn.out_proj''': '''speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.out_proj''', '''decoder.layers.*.encoder_attn_layer_norm''': '''speecht5.decoder.wrapped_decoder.layers.*.encoder_attn_layer_norm''', '''decoder.layers.*.fc1''': '''speecht5.decoder.wrapped_decoder.layers.*.feed_forward.intermediate_dense''', '''decoder.layers.*.fc2''': '''speecht5.decoder.wrapped_decoder.layers.*.feed_forward.output_dense''', '''decoder.layers.*.final_layer_norm''': '''speecht5.decoder.wrapped_decoder.layers.*.final_layer_norm''', } _a = { **MAPPING_SPEECH_ENCODER_PRENET, **MAPPING_ENCODER, **MAPPING_DECODER, **MAPPING_TEXT_DECODER_PRENET, **MAPPING_TEXT_DECODER_POSTNET, } _a = { **MAPPING_TEXT_ENCODER_PRENET, **MAPPING_ENCODER, **MAPPING_DECODER, **MAPPING_SPEECH_DECODER_PRENET, **MAPPING_SPEECH_DECODER_POSTNET, } _a = { **MAPPING_SPEECH_ENCODER_PRENET, **MAPPING_ENCODER, **MAPPING_DECODER, **MAPPING_SPEECH_DECODER_PRENET, **MAPPING_SPEECH_DECODER_POSTNET, } _a = [] _a = [ '''encoder.version''', '''encoder.layers.*.norm_k.weight''', '''encoder.layers.*.norm_k.bias''', '''decoder.version''', '''decoder.layers.*.norm_k.weight''', '''decoder.layers.*.norm_k.bias''', '''decoder.pos_emb.pe_k''', '''speech_encoder_prenet.embed_positions._float_tensor''', '''text_decoder_prenet.embed_positions._float_tensor''', ] _a = IGNORE_KEYS + [ '''encoder.proj''', '''text_encoder_prenet.*''', '''speech_decoder_prenet.*''', '''speech_decoder_postnet.*''', ] _a = IGNORE_KEYS + [ '''encoder.proj''', '''speech_encoder_prenet.*''', '''text_decoder_prenet.*''', '''text_decoder_postnet.*''', ] _a = IGNORE_KEYS + [ '''encoder.proj''', '''text_encoder_prenet.*''', '''text_decoder_prenet.*''', '''text_decoder_postnet.*''', ] def __A ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase )-> Any: """simple docstring""" for attribute in key.split('.' ): _UpperCAmelCase = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if weight_type is not None: _UpperCAmelCase = getattr(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).shape else: _UpperCAmelCase = hf_pointer.shape if hf_shape != value.shape: raise ValueError( F"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be""" F""" {value.shape} for {full_name}""" ) if weight_type == "weight": _UpperCAmelCase = value elif weight_type == "weight_g": _UpperCAmelCase = value elif weight_type == "weight_v": _UpperCAmelCase = value elif weight_type == "bias": _UpperCAmelCase = value elif weight_type == "running_mean": _UpperCAmelCase = value elif weight_type == "running_var": _UpperCAmelCase = value elif weight_type == "num_batches_tracked": _UpperCAmelCase = value else: _UpperCAmelCase = value logger.info(F"""{key + ("." + weight_type if weight_type is not None else "")} was initialized from {full_name}.""" ) def __A ( __lowerCAmelCase , __lowerCAmelCase )-> int: """simple docstring""" for key in ignore_keys: if key.endswith('.*' ): if name.startswith(key[:-1] ): return True elif ".*." in key: _UpperCAmelCase , _UpperCAmelCase = key.split('.*.' ) if prefix in name and suffix in name: return True elif key in name: return True return False def __A ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase )-> List[Any]: """simple docstring""" _UpperCAmelCase = [] if task == "s2t": _UpperCAmelCase = hf_model.speechta.encoder.prenet.feature_encoder _UpperCAmelCase = MAPPING_S2T _UpperCAmelCase = IGNORE_KEYS_S2T elif task == "t2s": _UpperCAmelCase = None _UpperCAmelCase = MAPPING_T2S _UpperCAmelCase = IGNORE_KEYS_T2S elif task == "s2s": _UpperCAmelCase = hf_model.speechta.encoder.prenet.feature_encoder _UpperCAmelCase = MAPPING_S2S _UpperCAmelCase = IGNORE_KEYS_S2S else: raise ValueError(F"""Unsupported task: {task}""" ) for name, value in fairseq_dict.items(): if should_ignore(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): logger.info(F"""{name} was ignored""" ) continue _UpperCAmelCase = False if "conv_layers" in name: load_conv_layer( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , hf_model.config.feat_extract_norm == 'group' , ) _UpperCAmelCase = True else: for key, mapped_key in MAPPING.items(): # mapped_key = "speecht5." + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if "*" in key: _UpperCAmelCase , _UpperCAmelCase = key.split('.*.' ) if prefix in name and suffix in name: _UpperCAmelCase = suffix # if key in name or key.split("w2v_model.")[-1] == name.split(".")[0]: if key in name: _UpperCAmelCase = True if "*" in mapped_key: _UpperCAmelCase = name.split(_SCREAMING_SNAKE_CASE )[0].split('.' )[-2] _UpperCAmelCase = mapped_key.replace('*' , _SCREAMING_SNAKE_CASE ) if "weight_g" in name: _UpperCAmelCase = 'weight_g' elif "weight_v" in name: _UpperCAmelCase = 'weight_v' elif "bias" in name: _UpperCAmelCase = 'bias' elif "weight" in name: _UpperCAmelCase = 'weight' elif "running_mean" in name: _UpperCAmelCase = 'running_mean' elif "running_var" in name: _UpperCAmelCase = 'running_var' elif "num_batches_tracked" in name: _UpperCAmelCase = 'num_batches_tracked' else: _UpperCAmelCase = None set_recursively(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) continue if not is_used: unused_weights.append(_SCREAMING_SNAKE_CASE ) logger.warning(F"""Unused weights: {unused_weights}""" ) def __A ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase )-> Any: """simple docstring""" _UpperCAmelCase = full_name.split('conv_layers.' )[-1] _UpperCAmelCase = name.split('.' ) _UpperCAmelCase = int(items[0] ) _UpperCAmelCase = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) _UpperCAmelCase = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) _UpperCAmelCase = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.""" ) _UpperCAmelCase = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.""" ) _UpperCAmelCase = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(_SCREAMING_SNAKE_CASE ) @torch.no_grad() def __A ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase=None , __lowerCAmelCase=None , __lowerCAmelCase=None , )-> Any: """simple docstring""" if config_path is not None: _UpperCAmelCase = SpeechTaConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) else: _UpperCAmelCase = SpeechTaConfig() if task == "s2t": _UpperCAmelCase = config.max_text_positions _UpperCAmelCase = SpeechTaForSpeechToText(_SCREAMING_SNAKE_CASE ) elif task == "t2s": _UpperCAmelCase = 1_876 _UpperCAmelCase = 600 _UpperCAmelCase = config.max_speech_positions _UpperCAmelCase = SpeechTaForTextToSpeech(_SCREAMING_SNAKE_CASE ) elif task == "s2s": _UpperCAmelCase = 1_876 _UpperCAmelCase = config.max_speech_positions _UpperCAmelCase = SpeechTaForSpeechToSpeech(_SCREAMING_SNAKE_CASE ) else: raise ValueError(F"""Unknown task name: {task}""" ) if vocab_path: _UpperCAmelCase = SpeechTaTokenizer(_SCREAMING_SNAKE_CASE , model_max_length=config.max_text_positions ) # Mask token behaves like a normal word, i.e. include the space before it _UpperCAmelCase = AddedToken('<mask>' , lstrip=_SCREAMING_SNAKE_CASE , rstrip=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = mask_token tokenizer.add_special_tokens({'mask_token': mask_token} ) tokenizer.add_tokens(['<ctc_blank>'] ) _UpperCAmelCase = SpeechTaFeatureExtractor() _UpperCAmelCase = SpeechTaProcessor(tokenizer=_SCREAMING_SNAKE_CASE , feature_extractor=_SCREAMING_SNAKE_CASE ) processor.save_pretrained(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = torch.load(_SCREAMING_SNAKE_CASE ) recursively_load_weights(fairseq_checkpoint['model'] , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) if repo_id: print('Pushing to the hub...' ) processor.push_to_hub(_SCREAMING_SNAKE_CASE ) model.push_to_hub(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": _a = argparse.ArgumentParser() parser.add_argument( '''--task''', default='''s2t''', type=str, help='''Type of the SpeechT5 model you\'d like to convert. Should be one of \'s2t\', \'t2s\', \'s2s\'.''', ) parser.add_argument('''--checkpoint_path''', required=True, default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--vocab_path''', default=None, type=str, help='''Path to SentencePiece model''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument( '''--pytorch_dump_folder_path''', required=True, default=None, type=str, help='''Path to the output PyTorch model.''' ) parser.add_argument( '''--push_to_hub''', default=None, type=str, help='''Where to upload the converted model on the 🤗 hub.''' ) _a = parser.parse_args() convert_speechta_checkpoint( args.task, args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.vocab_path, args.push_to_hub, )
39
"""simple docstring""" from sklearn.metrics import recall_score import datasets lowerCAmelCase__ = ''' Recall is the fraction of the positive examples that were correctly labeled by the model as positive. It can be computed with the equation: Recall = TP / (TP + FN) Where TP is the true positives and FN is the false negatives. ''' lowerCAmelCase__ = ''' Args: - **predictions** (`list` of `int`): The predicted labels. - **references** (`list` of `int`): The ground truth labels. - **labels** (`list` of `int`): The set of labels to include when `average` is not set to `binary`, and their order when average is `None`. Labels present in the data can be excluded in this input, for example to calculate a multiclass average ignoring a majority negative class, while labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in y_true and y_pred are used in sorted order. Defaults to None. - **pos_label** (`int`): The class label to use as the \'positive class\' when calculating the recall. Defaults to `1`. - **average** (`string`): This parameter is required for multiclass/multilabel targets. If None, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `\'binary\'`. - `\'binary\'`: Only report results for the class specified by `pos_label`. This is applicable only if the target labels and predictions are binary. - `\'micro\'`: Calculate metrics globally by counting the total true positives, false negatives, and false positives. - `\'macro\'`: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. - `\'weighted\'`: Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `\'macro\'` to account for label imbalance. Note that it can result in an F-score that is not between precision and recall. - `\'samples\'`: Calculate metrics for each instance, and find their average (only meaningful for multilabel classification). - **sample_weight** (`list` of `float`): Sample weights Defaults to `None`. - **zero_division** (): Sets the value to return when there is a zero division. Defaults to . - `\'warn\'`: If there is a zero division, the return value is `0`, but warnings are also raised. - `0`: If there is a zero division, the return value is `0`. - `1`: If there is a zero division, the return value is `1`. Returns: - **recall** (`float`, or `array` of `float`): Either the general recall score, or the recall scores for individual classes, depending on the values input to `labels` and `average`. Minimum possible value is 0. Maximum possible value is 1. A higher recall means that more of the positive examples have been labeled correctly. Therefore, a higher recall is generally considered better. Examples: Example 1-A simple example with some errors >>> recall_metric = datasets.load_metric(\'recall\') >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1]) >>> print(results) {\'recall\': 0.6666666666666666} Example 2-The same example as Example 1, but with `pos_label=0` instead of the default `pos_label=1`. >>> recall_metric = datasets.load_metric(\'recall\') >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], pos_label=0) >>> print(results) {\'recall\': 0.5} Example 3-The same example as Example 1, but with `sample_weight` included. >>> recall_metric = datasets.load_metric(\'recall\') >>> sample_weight = [0.9, 0.2, 0.9, 0.3, 0.8] >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], sample_weight=sample_weight) >>> print(results) {\'recall\': 0.55} Example 4-A multiclass example, using different averages. >>> recall_metric = datasets.load_metric(\'recall\') >>> predictions = [0, 2, 1, 0, 0, 1] >>> references = [0, 1, 2, 0, 1, 2] >>> results = recall_metric.compute(predictions=predictions, references=references, average=\'macro\') >>> print(results) {\'recall\': 0.3333333333333333} >>> results = recall_metric.compute(predictions=predictions, references=references, average=\'micro\') >>> print(results) {\'recall\': 0.3333333333333333} >>> results = recall_metric.compute(predictions=predictions, references=references, average=\'weighted\') >>> print(results) {\'recall\': 0.3333333333333333} >>> results = recall_metric.compute(predictions=predictions, references=references, average=None) >>> print(results) {\'recall\': array([1., 0., 0.])} ''' lowerCAmelCase__ = ''' @article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011} ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _lowerCamelCase ( datasets.Metric ): def snake_case_ (self ) -> str: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Sequence(datasets.Value("int32" ) ), "references": datasets.Sequence(datasets.Value("int32" ) ), } if self.config_name == "multilabel" else { "predictions": datasets.Value("int32" ), "references": datasets.Value("int32" ), } ) , reference_urls=["https://scikit-learn.org/stable/modules/generated/sklearn.metrics.recall_score.html"] , ) def snake_case_ (self , __a , __a , __a=None , __a=1 , __a="binary" , __a=None , __a="warn" , ) -> str: UpperCamelCase = recall_score( __a , __a , labels=__a , pos_label=__a , average=__a , sample_weight=__a , zero_division=__a , ) return {"recall": float(__a ) if score.size == 1 else score}
153
0
def _lowerCamelCase ( lowerCamelCase_ : int , lowerCamelCase_ : int ): """simple docstring""" return base * power(lowerCamelCase_ , (exponent - 1) ) if exponent else 1 if __name__ == "__main__": print('''Raise base to the power of exponent using recursion...''') snake_case__ : Any = int(input('''Enter the base: ''').strip()) snake_case__ : Dict = int(input('''Enter the exponent: ''').strip()) snake_case__ : Optional[int] = power(base, abs(exponent)) if exponent < 0: # power() does not properly deal w/ negative exponents snake_case__ : Union[str, Any] = 1 / result print(f'''{base} to the power of {exponent} is {result}''')
358
'''simple docstring''' import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class __SCREAMING_SNAKE_CASE ( lowerCamelCase_ ): '''simple docstring''' lowerCamelCase_ :Tuple = ['''image_processor''', '''tokenizer'''] lowerCamelCase_ :Optional[Any] = '''ViTImageProcessor''' lowerCamelCase_ :int = ('''CLIPTokenizer''', '''CLIPTokenizerFast''') def __init__( self , snake_case_=None , snake_case_=None , **snake_case_ ): '''simple docstring''' UpperCAmelCase_ : Dict = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , snake_case_ , ) UpperCAmelCase_ : int = kwargs.pop('feature_extractor' ) UpperCAmelCase_ : str = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.' ) if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.' ) super().__init__(snake_case_ , snake_case_ ) def __call__( self , snake_case_=None , snake_case_=None , snake_case_=None , snake_case_=None , **snake_case_ ): '''simple docstring''' if text is None and visual_prompt is None and images is None: raise ValueError('You have to specify either text, visual prompt or images.' ) if text is not None and visual_prompt is not None: raise ValueError('You have to specify exactly one type of prompt. Either text or visual prompt.' ) if text is not None: UpperCAmelCase_ : Optional[int] = self.tokenizer(snake_case_ , return_tensors=snake_case_ , **snake_case_ ) if visual_prompt is not None: UpperCAmelCase_ : Optional[Any] = self.image_processor(snake_case_ , return_tensors=snake_case_ , **snake_case_ ) if images is not None: UpperCAmelCase_ : int = self.image_processor(snake_case_ , return_tensors=snake_case_ , **snake_case_ ) if visual_prompt is not None and images is not None: UpperCAmelCase_ : Tuple = { 'pixel_values': image_features.pixel_values, 'conditional_pixel_values': prompt_features.pixel_values, } return encoding elif text is not None and images is not None: UpperCAmelCase_ : Optional[int] = image_features.pixel_values return encoding elif text is not None: return encoding elif visual_prompt is not None: UpperCAmelCase_ : Dict = { 'conditional_pixel_values': prompt_features.pixel_values, } return encoding else: return BatchEncoding(data=dict(**snake_case_ ) , tensor_type=snake_case_ ) def _UpperCamelCase ( self , *snake_case_ , **snake_case_ ): '''simple docstring''' return self.tokenizer.batch_decode(*snake_case_ , **snake_case_ ) def _UpperCamelCase ( self , *snake_case_ , **snake_case_ ): '''simple docstring''' return self.tokenizer.decode(*snake_case_ , **snake_case_ ) @property def _UpperCamelCase ( self ): '''simple docstring''' warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , snake_case_ , ) return self.image_processor_class @property def _UpperCamelCase ( self ): '''simple docstring''' warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , snake_case_ , ) return self.image_processor
274
0
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_ ) -> List[str]: """simple docstring""" return EnvironmentCommand() def UpperCAmelCase ( a_ ) -> Union[str, 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 : str ,A : str ,*A : List[Any] ): __A = accelerate_config_file def UpperCamelCase_ ( self : Optional[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 : Any ): return "\n".join([f'''- {prop}: {val}''' for prop, val in d.items()] ) + "\n"
15
from typing import Dict, Optional import numpy as np import datasets SCREAMING_SNAKE_CASE :List[Any] = '\nIoU is the area of overlap between the predicted segmentation and the ground truth divided by the area of union\nbetween the predicted segmentation and the ground truth. For binary (two classes) or multi-class segmentation,\nthe mean IoU of the image is calculated by taking the IoU of each class and averaging them.\n' SCREAMING_SNAKE_CASE :List[str] = '\nArgs:\n predictions (`List[ndarray]`):\n List of predicted segmentation maps, each of shape (height, width). Each segmentation map can be of a different size.\n references (`List[ndarray]`):\n List of ground truth segmentation maps, each of shape (height, width). Each segmentation map can be of a different size.\n num_labels (`int`):\n Number of classes (categories).\n ignore_index (`int`):\n Index that will be ignored during evaluation.\n nan_to_num (`int`, *optional*):\n If specified, NaN values will be replaced by the number defined by the user.\n label_map (`dict`, *optional*):\n If specified, dictionary mapping old label indices to new label indices.\n reduce_labels (`bool`, *optional*, defaults to `False`):\n Whether or not to reduce all label values of segmentation maps by 1. Usually used for datasets where 0 is used for background,\n and background itself is not included in all classes of a dataset (e.g. ADE20k). The background label will be replaced by 255.\n\nReturns:\n `Dict[str, float | ndarray]` comprising various elements:\n - *mean_iou* (`float`):\n Mean Intersection-over-Union (IoU averaged over all categories).\n - *mean_accuracy* (`float`):\n Mean accuracy (averaged over all categories).\n - *overall_accuracy* (`float`):\n Overall accuracy on all images.\n - *per_category_accuracy* (`ndarray` of shape `(num_labels,)`):\n Per category accuracy.\n - *per_category_iou* (`ndarray` of shape `(num_labels,)`):\n Per category IoU.\n\nExamples:\n\n >>> import numpy as np\n\n >>> mean_iou = datasets.load_metric("mean_iou")\n\n >>> # suppose one has 3 different segmentation maps predicted\n >>> predicted_1 = np.array([[1, 2], [3, 4], [5, 255]])\n >>> actual_1 = np.array([[0, 3], [5, 4], [6, 255]])\n\n >>> predicted_2 = np.array([[2, 7], [9, 2], [3, 6]])\n >>> actual_2 = np.array([[1, 7], [9, 2], [3, 6]])\n\n >>> predicted_3 = np.array([[2, 2, 3], [8, 2, 4], [3, 255, 2]])\n >>> actual_3 = np.array([[1, 2, 2], [8, 2, 1], [3, 255, 1]])\n\n >>> predicted = [predicted_1, predicted_2, predicted_3]\n >>> ground_truth = [actual_1, actual_2, actual_3]\n\n >>> results = mean_iou.compute(predictions=predicted, references=ground_truth, num_labels=10, ignore_index=255, reduce_labels=False)\n >>> print(results) # doctest: +NORMALIZE_WHITESPACE\n {\'mean_iou\': 0.47750000000000004, \'mean_accuracy\': 0.5916666666666666, \'overall_accuracy\': 0.5263157894736842, \'per_category_iou\': array([0. , 0. , 0.375, 0.4 , 0.5 , 0. , 0.5 , 1. , 1. , 1. ]), \'per_category_accuracy\': array([0. , 0. , 0.75 , 0.66666667, 1. , 0. , 0.5 , 1. , 1. , 1. ])}\n' SCREAMING_SNAKE_CASE :str = '\\n@software{MMSegmentation_Contributors_OpenMMLab_Semantic_Segmentation_2020,\nauthor = {{MMSegmentation Contributors}},\nlicense = {Apache-2.0},\nmonth = {7},\ntitle = {{OpenMMLab Semantic Segmentation Toolbox and Benchmark}},\nurl = {https://github.com/open-mmlab/mmsegmentation},\nyear = {2020}\n}' def UpperCAmelCase ( a_ , a_ , a_ , a_ , a_ = None , a_ = False , ) -> Tuple: """simple docstring""" if label_map is not None: for old_id, new_id in label_map.items(): __A = new_id # turn into Numpy arrays __A = np.array(a_ ) __A = np.array(a_ ) if reduce_labels: __A = 2_5_5 __A = label - 1 __A = 2_5_5 __A = label != ignore_index __A = np.not_equal(a_ , a_ ) __A = pred_label[mask] __A = np.array(a_ )[mask] __A = pred_label[pred_label == label] __A = np.histogram(a_ , bins=a_ , range=(0, num_labels - 1) )[0] __A = np.histogram(a_ , bins=a_ , range=(0, num_labels - 1) )[0] __A = np.histogram(a_ , bins=a_ , range=(0, num_labels - 1) )[0] __A = area_pred_label + area_label - area_intersect return area_intersect, area_union, area_pred_label, area_label def UpperCAmelCase ( a_ , a_ , a_ , a_ , a_ = None , a_ = False , ) -> Union[str, Any]: """simple docstring""" __A = np.zeros((num_labels,) , dtype=np.floataa ) __A = np.zeros((num_labels,) , dtype=np.floataa ) __A = np.zeros((num_labels,) , dtype=np.floataa ) __A = np.zeros((num_labels,) , dtype=np.floataa ) for result, gt_seg_map in zip(a_ , a_ ): __A , __A , __A , __A = intersect_and_union( a_ , a_ , a_ , a_ , a_ , a_ ) total_area_intersect += area_intersect total_area_union += area_union total_area_pred_label += area_pred_label total_area_label += area_label return total_area_intersect, total_area_union, total_area_pred_label, total_area_label def UpperCAmelCase ( a_ , a_ , a_ , a_ , a_ = None , a_ = None , a_ = False , ) -> str: """simple docstring""" __A , __A , __A , __A = total_intersect_and_union( a_ , a_ , a_ , a_ , a_ , a_ ) # compute metrics __A = {} __A = total_area_intersect.sum() / total_area_label.sum() __A = total_area_intersect / total_area_union __A = total_area_intersect / total_area_label __A = np.nanmean(a_ ) __A = np.nanmean(a_ ) __A = all_acc __A = iou __A = acc if nan_to_num is not None: __A = {metric: np.nan_to_num(a_ , nan=a_ ) for metric, metric_value in metrics.items()} return metrics @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCAmelCase ( datasets.Metric ): '''simple docstring''' def UpperCamelCase_ ( self : List[Any] ): return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( # 1st Seq - height dim, 2nd - width dim { "predictions": datasets.Sequence(datasets.Sequence(datasets.Value("uint16" ) ) ), "references": datasets.Sequence(datasets.Sequence(datasets.Value("uint16" ) ) ), } ) ,reference_urls=[ "https://github.com/open-mmlab/mmsegmentation/blob/71c201b1813267d78764f306a297ca717827c4bf/mmseg/core/evaluation/metrics.py" ] ,) def UpperCamelCase_ ( self : int ,A : Optional[Any] ,A : Optional[Any] ,A : int ,A : bool ,A : Optional[int] = None ,A : Optional[Dict[int, int]] = None ,A : bool = False ,): __A = mean_iou( results=A ,gt_seg_maps=A ,num_labels=A ,ignore_index=A ,nan_to_num=A ,label_map=A ,reduce_labels=A ,) return iou_result
15
1
import torch import torch.nn as nn from transformers import CLIPConfig, CLIPVisionModel, PreTrainedModel from ...utils import logging SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE = nn.functional.normalize(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = nn.functional.normalize(_SCREAMING_SNAKE_CASE ) return torch.mm(_SCREAMING_SNAKE_CASE , normalized_text_embeds.t() ) class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' __snake_case : int = CLIPConfig __snake_case : Any = ["CLIPEncoderLayer"] def __init__( self : Union[str, Any] ,lowerCamelCase__ : CLIPConfig ) -> Dict: '''simple docstring''' super().__init__(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = CLIPVisionModel(config.vision_config ) SCREAMING_SNAKE_CASE = nn.Linear(config.vision_config.hidden_size ,config.projection_dim ,bias=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = nn.Parameter(torch.ones(17 ,config.projection_dim ) ,requires_grad=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = nn.Parameter(torch.ones(3 ,config.projection_dim ) ,requires_grad=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = nn.Parameter(torch.ones(17 ) ,requires_grad=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = nn.Parameter(torch.ones(3 ) ,requires_grad=lowerCamelCase__ ) @torch.no_grad() def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ,lowerCamelCase__ : Optional[Any] ,lowerCamelCase__ : List[str] ) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE = self.vision_model(lowerCamelCase__ )[1] # pooled_output SCREAMING_SNAKE_CASE = self.visual_projection(lowerCamelCase__ ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 SCREAMING_SNAKE_CASE = cosine_distance(lowerCamelCase__ ,self.special_care_embeds ).cpu().float().numpy() SCREAMING_SNAKE_CASE = cosine_distance(lowerCamelCase__ ,self.concept_embeds ).cpu().float().numpy() SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = image_embeds.shape[0] for i in range(lowerCamelCase__ ): SCREAMING_SNAKE_CASE = {"""special_scores""": {}, """special_care""": [], """concept_scores""": {}, """bad_concepts""": []} # increase this value to create a stronger `nfsw` filter # at the cost of increasing the possibility of filtering benign images SCREAMING_SNAKE_CASE = 0.0 for concept_idx in range(len(special_cos_dist[0] ) ): SCREAMING_SNAKE_CASE = special_cos_dist[i][concept_idx] SCREAMING_SNAKE_CASE = self.special_care_embeds_weights[concept_idx].item() SCREAMING_SNAKE_CASE = round(concept_cos - concept_threshold + adjustment ,3 ) if result_img["special_scores"][concept_idx] > 0: result_img["special_care"].append({concept_idx, result_img["""special_scores"""][concept_idx]} ) SCREAMING_SNAKE_CASE = 0.01 for concept_idx in range(len(cos_dist[0] ) ): SCREAMING_SNAKE_CASE = cos_dist[i][concept_idx] SCREAMING_SNAKE_CASE = self.concept_embeds_weights[concept_idx].item() SCREAMING_SNAKE_CASE = round(concept_cos - concept_threshold + adjustment ,3 ) if result_img["concept_scores"][concept_idx] > 0: result_img["bad_concepts"].append(lowerCamelCase__ ) result.append(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = [len(res["""bad_concepts"""] ) > 0 for res in result] return images, has_nsfw_concepts @torch.no_grad() def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ,lowerCamelCase__ : torch.FloatTensor ,lowerCamelCase__ : torch.FloatTensor ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE = self.vision_model(lowerCamelCase__ )[1] # pooled_output SCREAMING_SNAKE_CASE = self.visual_projection(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = cosine_distance(lowerCamelCase__ ,self.special_care_embeds ) SCREAMING_SNAKE_CASE = cosine_distance(lowerCamelCase__ ,self.concept_embeds ) # increase this value to create a stronger `nsfw` filter # at the cost of increasing the possibility of filtering benign images SCREAMING_SNAKE_CASE = 0.0 SCREAMING_SNAKE_CASE = special_cos_dist - self.special_care_embeds_weights + adjustment # special_scores = special_scores.round(decimals=3) SCREAMING_SNAKE_CASE = torch.any(special_scores > 0 ,dim=1 ) SCREAMING_SNAKE_CASE = special_care * 0.01 SCREAMING_SNAKE_CASE = special_adjustment.unsqueeze(1 ).expand(-1 ,cos_dist.shape[1] ) SCREAMING_SNAKE_CASE = (cos_dist - self.concept_embeds_weights) + special_adjustment # concept_scores = concept_scores.round(decimals=3) SCREAMING_SNAKE_CASE = torch.any(concept_scores > 0 ,dim=1 ) return images, has_nsfw_concepts
193
from PIL import Image def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Image: '''simple docstring''' def brightness(_SCREAMING_SNAKE_CASE ) -> float: return 1_28 + level + (c - 1_28) if not -255.0 <= level <= 255.0: raise ValueError("""level must be between -255.0 (black) and 255.0 (white)""" ) return img.point(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": # Load image with Image.open("""image_data/lena.jpg""") as img: # Change brightness to 100 SCREAMING_SNAKE_CASE_ = change_brightness(img, 1_0_0) brigt_img.save("""image_data/lena_brightness.png""", format="""png""")
193
1
import argparse import torch from safetensors.torch import load_file from diffusers import StableDiffusionPipeline def lowerCAmelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ )-> Tuple: # load base model lowerCAmelCase_ : Dict = StableDiffusionPipeline.from_pretrained(_a , torch_dtype=torch.floataa ) # load LoRA weight from .safetensors lowerCAmelCase_ : List[Any] = load_file(_a ) lowerCAmelCase_ : Optional[int] = [] # directly update weight in diffusers model for key in state_dict: # it is suggested to print out the key, it usually will be something like below # "lora_te_text_model_encoder_layers_0_self_attn_k_proj.lora_down.weight" # as we have set the alpha beforehand, so just skip if ".alpha" in key or key in visited: continue if "text" in key: lowerCAmelCase_ : int = key.split('''.''' )[0].split(LORA_PREFIX_TEXT_ENCODER + '''_''' )[-1].split('''_''' ) lowerCAmelCase_ : Optional[int] = pipeline.text_encoder else: lowerCAmelCase_ : Tuple = key.split('''.''' )[0].split(LORA_PREFIX_UNET + '''_''' )[-1].split('''_''' ) lowerCAmelCase_ : Optional[Any] = pipeline.unet # find the target layer lowerCAmelCase_ : Dict = layer_infos.pop(0 ) while len(_a ) > -1: try: lowerCAmelCase_ : Optional[int] = curr_layer.__getattr__(_a ) if len(_a ) > 0: lowerCAmelCase_ : str = layer_infos.pop(0 ) elif len(_a ) == 0: break except Exception: if len(_a ) > 0: temp_name += "_" + layer_infos.pop(0 ) else: lowerCAmelCase_ : str = layer_infos.pop(0 ) lowerCAmelCase_ : Optional[int] = [] if "lora_down" in key: pair_keys.append(key.replace('''lora_down''' , '''lora_up''' ) ) pair_keys.append(_a ) else: pair_keys.append(_a ) pair_keys.append(key.replace('''lora_up''' , '''lora_down''' ) ) # update weight if len(state_dict[pair_keys[0]].shape ) == 4: lowerCAmelCase_ : Dict = state_dict[pair_keys[0]].squeeze(3 ).squeeze(2 ).to(torch.floataa ) lowerCAmelCase_ : List[Any] = state_dict[pair_keys[1]].squeeze(3 ).squeeze(2 ).to(torch.floataa ) curr_layer.weight.data += alpha * torch.mm(_a , _a ).unsqueeze(2 ).unsqueeze(3 ) else: lowerCAmelCase_ : Optional[int] = state_dict[pair_keys[0]].to(torch.floataa ) lowerCAmelCase_ : Tuple = state_dict[pair_keys[1]].to(torch.floataa ) curr_layer.weight.data += alpha * torch.mm(_a , _a ) # update visited list for item in pair_keys: visited.append(_a ) return pipeline if __name__ == "__main__": _UpperCAmelCase : Optional[int] =argparse.ArgumentParser() parser.add_argument( """--base_model_path""", default=None, type=str, required=True, help="""Path to the base model in diffusers format.""" ) parser.add_argument( """--checkpoint_path""", default=None, type=str, required=True, help="""Path to the checkpoint to convert.""" ) parser.add_argument("""--dump_path""", default=None, type=str, required=True, help="""Path to the output model.""") parser.add_argument( """--lora_prefix_unet""", default="""lora_unet""", type=str, help="""The prefix of UNet weight in safetensors""" ) parser.add_argument( """--lora_prefix_text_encoder""", default="""lora_te""", type=str, help="""The prefix of text encoder weight in safetensors""", ) parser.add_argument("""--alpha""", default=0.75, type=float, help="""The merging ratio in W = W0 + alpha * deltaW""") parser.add_argument( """--to_safetensors""", action="""store_true""", help="""Whether to store pipeline in safetensors format or not.""" ) parser.add_argument("""--device""", type=str, help="""Device to use (e.g. cpu, cuda:0, cuda:1, etc.)""") _UpperCAmelCase : str =parser.parse_args() _UpperCAmelCase : int =args.base_model_path _UpperCAmelCase : Union[str, Any] =args.checkpoint_path _UpperCAmelCase : List[Any] =args.dump_path _UpperCAmelCase : Optional[int] =args.lora_prefix_unet _UpperCAmelCase : Dict =args.lora_prefix_text_encoder _UpperCAmelCase : List[str] =args.alpha _UpperCAmelCase : Dict =convert(base_model_path, checkpoint_path, lora_prefix_unet, lora_prefix_text_encoder, alpha) _UpperCAmelCase : Optional[int] =pipe.to(args.device) pipe.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
262
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase__ : int = logging.get_logger(__name__) lowercase__ : List[Any] = { '''EleutherAI/gpt-neox-20b''': '''https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/config.json''', # See all GPTNeoX models at https://huggingface.co/models?filter=gpt_neox } class _UpperCAmelCase ( lowerCAmelCase__): _lowerCAmelCase : List[Any] = """gpt_neox""" def __init__( self : List[str] , lowercase_ : str=50432 , lowercase_ : List[Any]=6144 , lowercase_ : List[Any]=44 , lowercase_ : Union[str, Any]=64 , lowercase_ : List[str]=24576 , lowercase_ : List[Any]="gelu" , lowercase_ : str=0.25 , lowercase_ : Optional[int]=10000 , lowercase_ : Optional[int]=0.0 , lowercase_ : Optional[int]=0.0 , lowercase_ : int=0.1 , lowercase_ : Tuple=2048 , lowercase_ : Union[str, Any]=0.02 , lowercase_ : List[str]=1E-5 , lowercase_ : str=True , lowercase_ : str=0 , lowercase_ : Union[str, Any]=2 , lowercase_ : List[str]=False , lowercase_ : Optional[int]=True , lowercase_ : List[Any]=None , **lowercase_ : Optional[int] , ): super().__init__(bos_token_id=lowercase_ , eos_token_id=lowercase_ , **lowercase_ ) snake_case_ : List[str] = vocab_size snake_case_ : Optional[Any] = max_position_embeddings snake_case_ : str = hidden_size snake_case_ : Dict = num_hidden_layers snake_case_ : Dict = num_attention_heads snake_case_ : List[Any] = intermediate_size snake_case_ : List[Any] = hidden_act snake_case_ : str = rotary_pct snake_case_ : Dict = rotary_emb_base snake_case_ : Optional[int] = attention_dropout snake_case_ : Tuple = hidden_dropout snake_case_ : Tuple = classifier_dropout snake_case_ : List[str] = initializer_range snake_case_ : Union[str, Any] = layer_norm_eps snake_case_ : Any = use_cache snake_case_ : Optional[int] = tie_word_embeddings snake_case_ : Any = use_parallel_residual snake_case_ : Union[str, Any] = rope_scaling self._rope_scaling_validation() if self.hidden_size % self.num_attention_heads != 0: raise ValueError( '''The hidden size is not divisble by the number of attention heads! Make sure to update them!''' ) def _snake_case ( self : Optional[int] ): if self.rope_scaling is None: return if not isinstance(self.rope_scaling , lowercase_ ) or len(self.rope_scaling ) != 2: raise ValueError( '''`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, ''' f"got {self.rope_scaling}" ) snake_case_ : Any = self.rope_scaling.get('''type''' , lowercase_ ) snake_case_ : Union[str, Any] = self.rope_scaling.get('''factor''' , lowercase_ ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( f"`rope_scaling`'s name field must be one of ['linear', 'dynamic'], got {rope_scaling_type}" ) if rope_scaling_factor is None or not isinstance(lowercase_ , lowercase_ ) or rope_scaling_factor <= 1.0: raise ValueError(f"`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}" )
264
0
"""simple docstring""" import jax.numpy as jnp from ...utils import logging from ..ta.modeling_flax_ta import FlaxTaEncoderModel, FlaxTaForConditionalGeneration, FlaxTaModel from .configuration_mta import MTaConfig __lowerCAmelCase : int =logging.get_logger(__name__) __lowerCAmelCase : List[Any] ="""T5Config""" def UpperCAmelCase__ ( lowerCAmelCase__ :jnp.array , lowerCAmelCase__ :int , lowerCAmelCase__ :int ) -> jnp.ndarray: '''simple docstring''' lowercase = jnp.zeros_like(lowerCAmelCase__ ) lowercase = shifted_input_ids.at[:, 1:].set(input_ids[:, :-1] ) lowercase = shifted_input_ids.at[:, 0].set(lowerCAmelCase__ ) lowercase = jnp.where(shifted_input_ids == -1_0_0 , lowerCAmelCase__ , lowerCAmelCase__ ) return shifted_input_ids class _A ( lowerCAmelCase ): snake_case__ : List[str] = 'mt5' snake_case__ : List[str] = MTaConfig class _A ( lowerCAmelCase ): snake_case__ : Tuple = 'mt5' snake_case__ : Optional[int] = MTaConfig class _A ( lowerCAmelCase ): snake_case__ : Tuple = 'mt5' snake_case__ : Optional[int] = MTaConfig
32
"""simple docstring""" import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING __lowerCAmelCase : Tuple ={ """facebook/mask2former-swin-small-coco-instance""": ( """https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json""" ) # See all Mask2Former models at https://huggingface.co/models?filter=mask2former } __lowerCAmelCase : Optional[Any] =logging.get_logger(__name__) class _A ( lowerCAmelCase ): snake_case__ : Dict = 'mask2former' snake_case__ : Union[str, Any] = ['swin'] snake_case__ : Any = {'hidden_size': 'hidden_dim'} def __init__( self , __lowerCAmelCase = None , __lowerCAmelCase = 256 , __lowerCAmelCase = 256 , __lowerCAmelCase = 256 , __lowerCAmelCase = 1024 , __lowerCAmelCase = "relu" , __lowerCAmelCase = 6 , __lowerCAmelCase = 10 , __lowerCAmelCase = 8 , __lowerCAmelCase = 0.0 , __lowerCAmelCase = 2048 , __lowerCAmelCase = False , __lowerCAmelCase = False , __lowerCAmelCase = 4 , __lowerCAmelCase = 255 , __lowerCAmelCase = 100 , __lowerCAmelCase = 0.1 , __lowerCAmelCase = 2.0 , __lowerCAmelCase = 5.0 , __lowerCAmelCase = 5.0 , __lowerCAmelCase = 1_2544 , __lowerCAmelCase = 3.0 , __lowerCAmelCase = 0.7_5 , __lowerCAmelCase = 0.0_2 , __lowerCAmelCase = 1.0 , __lowerCAmelCase = True , __lowerCAmelCase = [4, 8, 16, 32] , __lowerCAmelCase = None , **__lowerCAmelCase , ): """simple docstring""" if backbone_config is None: logger.info("""`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.""" ) lowercase = CONFIG_MAPPING["""swin"""]( image_size=224 , in_channels=3 , patch_size=4 , embed_dim=96 , depths=[2, 2, 18, 2] , num_heads=[3, 6, 12, 24] , window_size=7 , drop_path_rate=0.3 , use_absolute_embeddings=__lowerCAmelCase , out_features=["""stage1""", """stage2""", """stage3""", """stage4"""] , ) if isinstance(__lowerCAmelCase , __lowerCAmelCase ): lowercase = backbone_config.pop("""model_type""" ) lowercase = CONFIG_MAPPING[backbone_model_type] lowercase = config_class.from_dict(__lowerCAmelCase ) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( f'Backbone {backbone_config.model_type} is not a supported model and may not be compatible with Mask2Former. ' f'Supported model types: {",".join(self.backbones_supported )}' ) lowercase = backbone_config lowercase = feature_size lowercase = mask_feature_size lowercase = hidden_dim lowercase = encoder_feedforward_dim lowercase = activation_function lowercase = encoder_layers lowercase = decoder_layers lowercase = num_attention_heads lowercase = dropout lowercase = dim_feedforward lowercase = pre_norm lowercase = enforce_input_projection lowercase = common_stride lowercase = ignore_value lowercase = num_queries lowercase = no_object_weight lowercase = class_weight lowercase = mask_weight lowercase = dice_weight lowercase = train_num_points lowercase = oversample_ratio lowercase = importance_sample_ratio lowercase = init_std lowercase = init_xavier_std lowercase = use_auxiliary_loss lowercase = feature_strides lowercase = output_auxiliary_logits lowercase = decoder_layers super().__init__(**__lowerCAmelCase ) @classmethod def A__ ( cls , __lowerCAmelCase , **__lowerCAmelCase ): """simple docstring""" return cls( backbone_config=__lowerCAmelCase , **__lowerCAmelCase , ) def A__ ( self ): """simple docstring""" lowercase = copy.deepcopy(self.__dict__ ) lowercase = self.backbone_config.to_dict() lowercase = self.__class__.model_type return output
32
1
from __future__ import annotations def UpperCamelCase ( __lowerCamelCase : list[int] ): return len(set(__lowerCamelCase ) ) == len(__lowerCamelCase ) if __name__ == "__main__": import doctest doctest.testmod()
59
from __future__ import annotations def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ ): return [ord(SCREAMING_SNAKE_CASE__ ) - 96 for elem in plain] def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ ): return "".join(chr(elem + 96 ) for elem in encoded ) def __SCREAMING_SNAKE_CASE (): snake_case_ = encode(input('''-> ''' ).strip().lower() ) print('''Encoded: ''' , SCREAMING_SNAKE_CASE__ ) print('''Decoded:''' , decode(SCREAMING_SNAKE_CASE__ ) ) if __name__ == "__main__": main()
8
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) a_ : Dict = { "configuration_albert": ["ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "AlbertConfig", "AlbertOnnxConfig"], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[Any] = ["AlbertTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Union[str, Any] = ["AlbertTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : int = [ "ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "AlbertForMaskedLM", "AlbertForMultipleChoice", "AlbertForPreTraining", "AlbertForQuestionAnswering", "AlbertForSequenceClassification", "AlbertForTokenClassification", "AlbertModel", "AlbertPreTrainedModel", "load_tf_weights_in_albert", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Optional[int] = [ "TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFAlbertForMaskedLM", "TFAlbertForMultipleChoice", "TFAlbertForPreTraining", "TFAlbertForQuestionAnswering", "TFAlbertForSequenceClassification", "TFAlbertForTokenClassification", "TFAlbertMainLayer", "TFAlbertModel", "TFAlbertPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Optional[Any] = [ "FlaxAlbertForMaskedLM", "FlaxAlbertForMultipleChoice", "FlaxAlbertForPreTraining", "FlaxAlbertForQuestionAnswering", "FlaxAlbertForSequenceClassification", "FlaxAlbertForTokenClassification", "FlaxAlbertModel", "FlaxAlbertPreTrainedModel", ] if TYPE_CHECKING: from .configuration_albert import ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, AlbertConfig, AlbertOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_albert import AlbertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_albert_fast import AlbertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_albert import ( ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST, AlbertForMaskedLM, AlbertForMultipleChoice, AlbertForPreTraining, AlbertForQuestionAnswering, AlbertForSequenceClassification, AlbertForTokenClassification, AlbertModel, AlbertPreTrainedModel, load_tf_weights_in_albert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_albert import ( TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFAlbertForMaskedLM, TFAlbertForMultipleChoice, TFAlbertForPreTraining, TFAlbertForQuestionAnswering, TFAlbertForSequenceClassification, TFAlbertForTokenClassification, TFAlbertMainLayer, TFAlbertModel, TFAlbertPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_albert import ( FlaxAlbertForMaskedLM, FlaxAlbertForMultipleChoice, FlaxAlbertForPreTraining, FlaxAlbertForQuestionAnswering, FlaxAlbertForSequenceClassification, FlaxAlbertForTokenClassification, FlaxAlbertModel, FlaxAlbertPreTrainedModel, ) else: import sys a_ : Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
104
'''simple docstring''' import unicodedata from dataclasses import dataclass from typing import Optional, Union import numpy as np from transformers.data.data_collator import DataCollatorMixin from transformers.file_utils import PaddingStrategy from transformers.tokenization_utils_base import PreTrainedTokenizerBase def _A (lowerCAmelCase__ :int , lowerCAmelCase__ :Any , lowerCAmelCase__ :Optional[Any] , lowerCAmelCase__ :Dict ) -> Optional[int]: '''simple docstring''' if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): _a = np.full((len(lowerCAmelCase__ ), sequence_length, 2) , lowerCAmelCase__ ) else: _a = np.full((len(lowerCAmelCase__ ), sequence_length) , lowerCAmelCase__ ) for i, tensor in enumerate(lowerCAmelCase__ ): if padding_side == "right": if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): _a = tensor[:sequence_length] else: _a = tensor[:sequence_length] else: if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): _a = tensor[:sequence_length] else: _a = tensor[:sequence_length] return out_tensor.tolist() def _A (lowerCAmelCase__ :Any ) -> Union[str, Any]: '''simple docstring''' _a = ord(lowerCAmelCase__ ) if (cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or (cp >= 91 and cp <= 96) or (cp >= 1_23 and cp <= 1_26): return True _a = unicodedata.category(lowerCAmelCase__ ) if cat.startswith('P' ): return True return False @dataclass class a ( _SCREAMING_SNAKE_CASE ): _lowerCAmelCase = 42 _lowerCAmelCase = True _lowerCAmelCase = None _lowerCAmelCase = None _lowerCAmelCase = -1_0_0 _lowerCAmelCase = "pt" def __UpperCAmelCase ( self , __magic_name__ ) -> Any: import torch _a = 'label' if 'label' in features[0].keys() else 'labels' _a = [feature[label_name] for feature in features] if label_name in features[0].keys() else None _a = self.tokenizer.pad( __magic_name__ , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors='pt' if labels is None else None , ) if labels is None: return batch _a = torch.tensor(batch['entity_ids'] ).shape[1] _a = self.tokenizer.padding_side if padding_side == "right": _a = [ list(__magic_name__ ) + [self.label_pad_token_id] * (sequence_length - len(__magic_name__ )) for label in labels ] else: _a = [ [self.label_pad_token_id] * (sequence_length - len(__magic_name__ )) + list(__magic_name__ ) for label in labels ] _a = [feature['ner_tags'] for feature in features] _a = padding_tensor(__magic_name__ , -1 , __magic_name__ , __magic_name__ ) _a = [feature['original_entity_spans'] for feature in features] _a = padding_tensor(__magic_name__ , (-1, -1) , __magic_name__ , __magic_name__ ) _a = {k: torch.tensor(__magic_name__ , dtype=torch.intaa ) for k, v in batch.items()} return batch
104
1
from __future__ import annotations from collections.abc import Iterable, Iterator from dataclasses import dataclass _A = (3, 9, -11, 0, 7, 5, 1, -1) _A = (4, 6, 2, 0, 8, 10, 3, -2) @dataclass class UpperCAmelCase__ : """simple docstring""" UpperCAmelCase__ : int UpperCAmelCase__ : Node | None class UpperCAmelCase__ : """simple docstring""" def __init__( self , A_ ) -> None: __UpperCamelCase =None for i in sorted(__lowerCAmelCase , reverse=__lowerCAmelCase ): __UpperCamelCase =Node(__lowerCAmelCase , self.head ) def __iter__( self ) -> Iterator[int]: __UpperCamelCase =self.head while node: yield node.data __UpperCamelCase =node.next_node def __len__( self ) -> int: return sum(1 for _ in self ) def __str__( self ) -> str: return " -> ".join([str(__lowerCAmelCase ) for node in self] ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : SortedLinkedList , SCREAMING_SNAKE_CASE__ : SortedLinkedList ): return SortedLinkedList(list(__a ) + list(__a ) ) if __name__ == "__main__": import doctest doctest.testmod() _A = SortedLinkedList print(merge_lists(SSL(test_data_odd), SSL(test_data_even)))
62
class A (SCREAMING_SNAKE_CASE ): '''simple docstring''' pass class A (SCREAMING_SNAKE_CASE ): '''simple docstring''' pass class A : '''simple docstring''' def __init__( self : List[Any] ) -> str: """simple docstring""" A__ = [ [], [], [], ] def a_ ( self : Dict , __lowerCAmelCase : int , __lowerCAmelCase : int ) -> None: """simple docstring""" try: if len(self.queues[priority] ) >= 1_00: raise OverflowError("""Maximum queue size is 100""" ) self.queues[priority].append(__lowerCAmelCase ) except IndexError: raise ValueError("""Valid priorities are 0, 1, and 2""" ) def a_ ( self : Optional[Any] ) -> int: """simple docstring""" for queue in self.queues: if queue: return queue.pop(0 ) raise UnderFlowError("""All queues are empty""" ) def __str__( self : Tuple ) -> str: """simple docstring""" return "\n".join(f'Priority {i}: {q}' for i, q in enumerate(self.queues ) ) class A : '''simple docstring''' def __init__( self : int ) -> str: """simple docstring""" A__ = [] def a_ ( self : int , __lowerCAmelCase : int ) -> None: """simple docstring""" if len(self.queue ) == 1_00: raise OverFlowError("""Maximum queue size is 100""" ) self.queue.append(__lowerCAmelCase ) def a_ ( self : List[str] ) -> int: """simple docstring""" if not self.queue: raise UnderFlowError("""The queue is empty""" ) else: A__ = min(self.queue ) self.queue.remove(__lowerCAmelCase ) return data def __str__( self : List[Any] ) -> str: """simple docstring""" return str(self.queue ) def __lowerCamelCase ( ) -> Optional[Any]: """simple docstring""" A__ = FixedPriorityQueue() fpq.enqueue(0 , 1_0 ) fpq.enqueue(1 , 7_0 ) fpq.enqueue(0 , 1_0_0 ) fpq.enqueue(2 , 1 ) fpq.enqueue(2 , 5 ) fpq.enqueue(1 , 7 ) fpq.enqueue(2 , 4 ) fpq.enqueue(1 , 6_4 ) fpq.enqueue(0 , 1_2_8 ) print(__a ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(__a ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) def __lowerCamelCase ( ) -> int: """simple docstring""" A__ = ElementPriorityQueue() epq.enqueue(1_0 ) epq.enqueue(7_0 ) epq.enqueue(1_0_0 ) epq.enqueue(1 ) epq.enqueue(5 ) epq.enqueue(7 ) epq.enqueue(4 ) epq.enqueue(6_4 ) epq.enqueue(1_2_8 ) print(__a ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(__a ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) if __name__ == "__main__": fixed_priority_queue() element_priority_queue()
274
0
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_convbert import ConvBertTokenizer a__ : List[Any] = logging.get_logger(__name__) a__ : str = {'vocab_file': 'vocab.txt'} a__ : Any = { 'vocab_file': { 'YituTech/conv-bert-base': 'https://huggingface.co/YituTech/conv-bert-base/resolve/main/vocab.txt', 'YituTech/conv-bert-medium-small': ( 'https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/vocab.txt' ), 'YituTech/conv-bert-small': 'https://huggingface.co/YituTech/conv-bert-small/resolve/main/vocab.txt', } } a__ : Tuple = { 'YituTech/conv-bert-base': 5_1_2, 'YituTech/conv-bert-medium-small': 5_1_2, 'YituTech/conv-bert-small': 5_1_2, } a__ : str = { 'YituTech/conv-bert-base': {'do_lower_case': True}, 'YituTech/conv-bert-medium-small': {'do_lower_case': True}, 'YituTech/conv-bert-small': {'do_lower_case': True}, } class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE = PRETRAINED_VOCAB_FILES_MAP __SCREAMING_SNAKE_CASE = PRETRAINED_INIT_CONFIGURATION __SCREAMING_SNAKE_CASE = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __SCREAMING_SNAKE_CASE = ConvBertTokenizer def __init__( self , lowercase=None , lowercase=None , lowercase=True , lowercase="[UNK]" , lowercase="[SEP]" , lowercase="[PAD]" , lowercase="[CLS]" , lowercase="[MASK]" , lowercase=True , lowercase=None , **lowercase , ) -> int: super().__init__( lowercase , tokenizer_file=lowercase , do_lower_case=lowercase , unk_token=lowercase , sep_token=lowercase , pad_token=lowercase , cls_token=lowercase , mask_token=lowercase , tokenize_chinese_chars=lowercase , strip_accents=lowercase , **lowercase , ) __UpperCamelCase = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""" , lowercase ) != do_lower_case or normalizer_state.get("""strip_accents""" , lowercase ) != strip_accents or normalizer_state.get("""handle_chinese_chars""" , lowercase ) != tokenize_chinese_chars ): __UpperCamelCase = getattr(lowercase , normalizer_state.pop("""type""" ) ) __UpperCamelCase = do_lower_case __UpperCamelCase = strip_accents __UpperCamelCase = tokenize_chinese_chars __UpperCamelCase = normalizer_class(**lowercase ) __UpperCamelCase = do_lower_case def __lowerCamelCase ( self , lowercase , lowercase=None ) -> Tuple: __UpperCamelCase = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __lowerCamelCase ( self , lowercase , lowercase = None ) -> List[int]: __UpperCamelCase = [self.sep_token_id] __UpperCamelCase = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __lowerCamelCase ( self , lowercase , lowercase = None ) -> Tuple[str]: __UpperCamelCase = self._tokenizer.model.save(lowercase , name=lowercase ) return tuple(lowercase )
243
'''simple docstring''' import functools import gc import inspect import torch from .imports import is_npu_available, is_xpu_available def _lowercase ( *__A ): '''simple docstring''' if not isinstance(__A ,__A ): __UpperCamelCase = list(__A ) for i in range(len(__A ) ): __UpperCamelCase = None gc.collect() if is_xpu_available(): torch.xpu.empty_cache() elif is_npu_available(): torch.npu.empty_cache() else: torch.cuda.empty_cache() return objects def _lowercase ( __A ): '''simple docstring''' __UpperCamelCase = [ """CUDA out of memory.""", # CUDA OOM """cuDNN error: CUDNN_STATUS_NOT_SUPPORTED.""", # CUDNN SNAFU """DefaultCPUAllocator: can't allocate memory""", # CPU OOM ] if isinstance(__A ,__A ) and len(exception.args ) == 1: return any(err in exception.args[0] for err in _statements ) return False def _lowercase ( __A = None ,__A = 128 ): '''simple docstring''' if function is None: return functools.partial(__A ,starting_batch_size=__A ) __UpperCamelCase = starting_batch_size def decorator(*__A ,**__A ): nonlocal batch_size gc.collect() if is_xpu_available(): torch.xpu.empty_cache() elif is_npu_available(): torch.npu.empty_cache() else: torch.cuda.empty_cache() __UpperCamelCase = list(inspect.signature(__A ).parameters.keys() ) # Guard against user error if len(__A ) < (len(__A ) + 1): __UpperCamelCase = """, """.join([f"{arg}={value}" for arg, value in zip(params[1:] ,args[1:] )] ) raise TypeError( f"Batch size was passed into `{function.__name__}` as the first argument when called." f"Remove this as the decorator already does so: `{function.__name__}({arg_str})`" ) while True: if batch_size == 0: raise RuntimeError("""No executable batch size found, reached zero.""" ) try: return function(__A ,*__A ,**__A ) except Exception as e: if should_reduce_batch_size(__A ): gc.collect() if is_xpu_available(): torch.xpu.empty_cache() elif is_npu_available(): torch.npu.empty_cache() else: torch.cuda.empty_cache() batch_size //= 2 else: raise return decorator
243
1
import inspect import unittest import warnings from transformers import DeiTConfig from transformers.models.auto import get_values from transformers.testing_utils import ( require_accelerate, require_torch, require_torch_gpu, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_MAPPING, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, DeiTModel, ) from transformers.models.deit.modeling_deit import DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class SCREAMING_SNAKE_CASE__ : def __init__( self,__lowerCamelCase,__lowerCamelCase=13,__lowerCamelCase=30,__lowerCamelCase=2,__lowerCamelCase=3,__lowerCamelCase=True,__lowerCamelCase=True,__lowerCamelCase=32,__lowerCamelCase=5,__lowerCamelCase=4,__lowerCamelCase=37,__lowerCamelCase="gelu",__lowerCamelCase=0.1,__lowerCamelCase=0.1,__lowerCamelCase=10,__lowerCamelCase=0.02,__lowerCamelCase=3,__lowerCamelCase=None,__lowerCamelCase=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 ): 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 ): 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=__lowerCamelCase,initializer_range=self.initializer_range,encoder_stride=self.encoder_stride,) def UpperCamelCase ( self,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase ): A__ = DeiTModel(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() A__ = model(__lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape,(self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase ( self,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase ): A__ = DeiTForMaskedImageModeling(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() A__ = model(__lowerCamelCase ) self.parent.assertEqual( result.reconstruction.shape,(self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images A__ = 1 A__ = DeiTForMaskedImageModeling(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() A__ = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) A__ = model(__lowerCamelCase ) self.parent.assertEqual(result.reconstruction.shape,(self.batch_size, 1, self.image_size, self.image_size) ) def UpperCamelCase ( self,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase ): A__ = self.type_sequence_label_size A__ = DeiTForImageClassification(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() A__ = model(__lowerCamelCase,labels=__lowerCamelCase ) self.parent.assertEqual(result.logits.shape,(self.batch_size, self.type_sequence_label_size) ) # test greyscale images A__ = 1 A__ = DeiTForImageClassification(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() A__ = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) A__ = model(__lowerCamelCase,labels=__lowerCamelCase ) self.parent.assertEqual(result.logits.shape,(self.batch_size, self.type_sequence_label_size) ) def UpperCamelCase ( self ): A__ = self.prepare_config_and_inputs() ( ( A__ ) , ( A__ ) , ( A__ ) , ) = config_and_inputs A__ = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE__ ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): __SCREAMING_SNAKE_CASE = ( ( DeiTModel, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, ) if is_torch_available() else () ) __SCREAMING_SNAKE_CASE = ( { '''feature-extraction''': DeiTModel, '''image-classification''': (DeiTForImageClassification, DeiTForImageClassificationWithTeacher), } if is_torch_available() else {} ) __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False def UpperCamelCase ( self ): A__ = DeiTModelTester(self ) A__ = ConfigTester(self,config_class=__lowerCamelCase,has_text_modality=__lowerCamelCase,hidden_size=37 ) def UpperCamelCase ( self ): self.config_tester.run_common_tests() @unittest.skip(reason='''DeiT does not use inputs_embeds''' ) def UpperCamelCase ( self ): pass def UpperCamelCase ( self ): A__ , A__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A__ = model_class(__lowerCamelCase ) self.assertIsInstance(model.get_input_embeddings(),(nn.Module) ) A__ = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__lowerCamelCase,nn.Linear ) ) def UpperCamelCase ( self ): A__ , A__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A__ = model_class(__lowerCamelCase ) 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],__lowerCamelCase ) def UpperCamelCase ( self ): A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCamelCase ) def UpperCamelCase ( self ): A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*__lowerCamelCase ) def UpperCamelCase ( self ): A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase ) def UpperCamelCase ( self,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase=False ): A__ = super()._prepare_for_class(__lowerCamelCase,__lowerCamelCase,return_labels=__lowerCamelCase ) if return_labels: if model_class.__name__ == "DeiTForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def UpperCamelCase ( self ): if not self.model_tester.is_training: return A__ , A__ = self.model_tester.prepare_config_and_inputs_for_common() A__ = True for model_class in self.all_model_classes: # DeiTForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(__lowerCamelCase ) or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue A__ = model_class(__lowerCamelCase ) model.to(__lowerCamelCase ) model.train() A__ = self._prepare_for_class(__lowerCamelCase,__lowerCamelCase,return_labels=__lowerCamelCase ) A__ = model(**__lowerCamelCase ).loss loss.backward() def UpperCamelCase ( self ): A__ , A__ = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return A__ = False A__ = True for model_class in self.all_model_classes: if model_class in get_values(__lowerCamelCase ) or not model_class.supports_gradient_checkpointing: continue # DeiTForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "DeiTForImageClassificationWithTeacher": continue A__ = model_class(__lowerCamelCase ) model.gradient_checkpointing_enable() model.to(__lowerCamelCase ) model.train() A__ = self._prepare_for_class(__lowerCamelCase,__lowerCamelCase,return_labels=__lowerCamelCase ) A__ = model(**__lowerCamelCase ).loss loss.backward() def UpperCamelCase ( self ): A__ , A__ = self.model_tester.prepare_config_and_inputs_for_common() A__ = [ {'''title''': '''multi_label_classification''', '''num_labels''': 2, '''dtype''': torch.float}, {'''title''': '''single_label_classification''', '''num_labels''': 1, '''dtype''': torch.long}, {'''title''': '''regression''', '''num_labels''': 1, '''dtype''': torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(__lowerCamelCase ), *get_values(__lowerCamelCase ), ] or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=f"Testing {model_class} with {problem_type['title']}" ): A__ = problem_type['''title'''] A__ = problem_type['''num_labels'''] A__ = model_class(__lowerCamelCase ) model.to(__lowerCamelCase ) model.train() A__ = self._prepare_for_class(__lowerCamelCase,__lowerCamelCase,return_labels=__lowerCamelCase ) if problem_type["num_labels"] > 1: A__ = inputs['''labels'''].unsqueeze(1 ).repeat(1,problem_type['''num_labels'''] ) A__ = inputs['''labels'''].to(problem_type['''dtype'''] ) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=__lowerCamelCase ) as warning_list: A__ = model(**__lowerCamelCase ).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message ): raise ValueError( f"Something is going wrong in the regression problem: intercepted {w.message}" ) loss.backward() @slow def UpperCamelCase ( self ): for model_name in DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A__ = DeiTModel.from_pretrained(__lowerCamelCase ) self.assertIsNotNone(__lowerCamelCase ) def UpperCamelCase__( )->Tuple: A__ = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): @cached_property def UpperCamelCase ( self ): return ( DeiTImageProcessor.from_pretrained('''facebook/deit-base-distilled-patch16-224''' ) if is_vision_available() else None ) @slow def UpperCamelCase ( self ): A__ = DeiTForImageClassificationWithTeacher.from_pretrained('''facebook/deit-base-distilled-patch16-224''' ).to( __lowerCamelCase ) A__ = self.default_image_processor A__ = prepare_img() A__ = image_processor(images=__lowerCamelCase,return_tensors='''pt''' ).to(__lowerCamelCase ) # forward pass with torch.no_grad(): A__ = model(**__lowerCamelCase ) # verify the logits A__ = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape,__lowerCamelCase ) A__ = torch.tensor([-1.0266, 0.1912, -1.2861] ).to(__lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3],__lowerCamelCase,atol=1E-4 ) ) @slow @require_accelerate @require_torch_gpu def UpperCamelCase ( self ): A__ = DeiTModel.from_pretrained( '''facebook/deit-base-distilled-patch16-224''',torch_dtype=torch.floataa,device_map='''auto''' ) A__ = self.default_image_processor A__ = prepare_img() A__ = image_processor(images=__lowerCamelCase,return_tensors='''pt''' ) A__ = inputs.pixel_values.to(__lowerCamelCase ) # forward pass to make sure inference works in fp16 with torch.no_grad(): A__ = model(__lowerCamelCase )
193
import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def UpperCamelCase__( UpperCamelCase__ : List[Any] , UpperCamelCase__ : Tuple=0.999 , UpperCamelCase__ : Any="cosine" , )->List[str]: if alpha_transform_type == "cosine": def alpha_bar_fn(UpperCamelCase__ : Optional[int] ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(UpperCamelCase__ : str ): return math.exp(t * -12.0 ) else: raise ValueError(f"Unsupported alpha_tranform_type: {alpha_transform_type}" ) A__ = [] for i in range(UpperCamelCase__ ): A__ = i / num_diffusion_timesteps A__ = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(UpperCamelCase__ ) / alpha_bar_fn(UpperCamelCase__ ) , UpperCamelCase__ ) ) return torch.tensor(UpperCamelCase__ , dtype=torch.floataa ) class SCREAMING_SNAKE_CASE__ ( UpperCamelCase__ , UpperCamelCase__ ): __SCREAMING_SNAKE_CASE = [e.name for e in KarrasDiffusionSchedulers] __SCREAMING_SNAKE_CASE = 2 @register_to_config def __init__( self,__lowerCamelCase = 1000,__lowerCamelCase = 0.00085,__lowerCamelCase = 0.012,__lowerCamelCase = "linear",__lowerCamelCase = None,__lowerCamelCase = "epsilon",__lowerCamelCase = False,__lowerCamelCase = False,__lowerCamelCase = 1.0,__lowerCamelCase = "linspace",__lowerCamelCase = 0,): if trained_betas is not None: A__ = torch.tensor(__lowerCamelCase,dtype=torch.floataa ) elif beta_schedule == "linear": A__ = torch.linspace(__lowerCamelCase,__lowerCamelCase,__lowerCamelCase,dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. A__ = ( torch.linspace(beta_start**0.5,beta_end**0.5,__lowerCamelCase,dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule A__ = betas_for_alpha_bar(__lowerCamelCase,alpha_transform_type='''cosine''' ) elif beta_schedule == "exp": A__ = betas_for_alpha_bar(__lowerCamelCase,alpha_transform_type='''exp''' ) else: raise NotImplementedError(f"{beta_schedule} does is not implemented for {self.__class__}" ) A__ = 1.0 - self.betas A__ = torch.cumprod(self.alphas,dim=0 ) # set all values self.set_timesteps(__lowerCamelCase,__lowerCamelCase,__lowerCamelCase ) A__ = use_karras_sigmas def UpperCamelCase ( self,__lowerCamelCase,__lowerCamelCase=None ): if schedule_timesteps is None: A__ = self.timesteps A__ = (schedule_timesteps == timestep).nonzero() # The sigma index that is taken for the **very** first `step` # is always the second index (or the last index if there is only 1) # This way we can ensure we don't accidentally skip a sigma in # case we start in the middle of the denoising schedule (e.g. for image-to-image) if len(self._index_counter ) == 0: A__ = 1 if len(__lowerCamelCase ) > 1 else 0 else: A__ = timestep.cpu().item() if torch.is_tensor(__lowerCamelCase ) else timestep A__ = self._index_counter[timestep_int] return indices[pos].item() @property def UpperCamelCase ( self ): # standard deviation of the initial noise distribution if self.config.timestep_spacing in ["linspace", "trailing"]: return self.sigmas.max() return (self.sigmas.max() ** 2 + 1) ** 0.5 def UpperCamelCase ( self,__lowerCamelCase,__lowerCamelCase,): A__ = self.index_for_timestep(__lowerCamelCase ) A__ = self.sigmas[step_index] A__ = sample / ((sigma**2 + 1) ** 0.5) return sample def UpperCamelCase ( self,__lowerCamelCase,__lowerCamelCase = None,__lowerCamelCase = None,): A__ = num_inference_steps A__ = num_train_timesteps or self.config.num_train_timesteps # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891 if self.config.timestep_spacing == "linspace": A__ = np.linspace(0,num_train_timesteps - 1,__lowerCamelCase,dtype=__lowerCamelCase )[::-1].copy() elif self.config.timestep_spacing == "leading": A__ = num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 A__ = (np.arange(0,__lowerCamelCase ) * step_ratio).round()[::-1].copy().astype(__lowerCamelCase ) timesteps += self.config.steps_offset elif self.config.timestep_spacing == "trailing": A__ = num_train_timesteps / self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 A__ = (np.arange(__lowerCamelCase,0,-step_ratio )).round().copy().astype(__lowerCamelCase ) timesteps -= 1 else: raise ValueError( f"{self.config.timestep_spacing} is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'." ) A__ = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 ) A__ = np.log(__lowerCamelCase ) A__ = np.interp(__lowerCamelCase,np.arange(0,len(__lowerCamelCase ) ),__lowerCamelCase ) if self.config.use_karras_sigmas: A__ = self._convert_to_karras(in_sigmas=__lowerCamelCase,num_inference_steps=self.num_inference_steps ) A__ = np.array([self._sigma_to_t(__lowerCamelCase,__lowerCamelCase ) for sigma in sigmas] ) A__ = np.concatenate([sigmas, [0.0]] ).astype(np.floataa ) A__ = torch.from_numpy(__lowerCamelCase ).to(device=__lowerCamelCase ) A__ = torch.cat([sigmas[:1], sigmas[1:-1].repeat_interleave(2 ), sigmas[-1:]] ) A__ = torch.from_numpy(__lowerCamelCase ) A__ = torch.cat([timesteps[:1], timesteps[1:].repeat_interleave(2 )] ) if str(__lowerCamelCase ).startswith('''mps''' ): # mps does not support float64 A__ = timesteps.to(__lowerCamelCase,dtype=torch.floataa ) else: A__ = timesteps.to(device=__lowerCamelCase ) # empty dt and derivative A__ = None A__ = None # for exp beta schedules, such as the one for `pipeline_shap_e.py` # we need an index counter A__ = defaultdict(__lowerCamelCase ) def UpperCamelCase ( self,__lowerCamelCase,__lowerCamelCase ): # get log sigma A__ = np.log(__lowerCamelCase ) # get distribution A__ = log_sigma - log_sigmas[:, np.newaxis] # get sigmas range A__ = np.cumsum((dists >= 0),axis=0 ).argmax(axis=0 ).clip(max=log_sigmas.shape[0] - 2 ) A__ = low_idx + 1 A__ = log_sigmas[low_idx] A__ = log_sigmas[high_idx] # interpolate sigmas A__ = (low - log_sigma) / (low - high) A__ = np.clip(__lowerCamelCase,0,1 ) # transform interpolation to time range A__ = (1 - w) * low_idx + w * high_idx A__ = t.reshape(sigma.shape ) return t def UpperCamelCase ( self,__lowerCamelCase,__lowerCamelCase ): A__ = in_sigmas[-1].item() A__ = in_sigmas[0].item() A__ = 7.0 # 7.0 is the value used in the paper A__ = np.linspace(0,1,__lowerCamelCase ) A__ = sigma_min ** (1 / rho) A__ = sigma_max ** (1 / rho) A__ = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho return sigmas @property def UpperCamelCase ( self ): return self.dt is None def UpperCamelCase ( self,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase = True,): A__ = self.index_for_timestep(__lowerCamelCase ) # advance index counter by 1 A__ = timestep.cpu().item() if torch.is_tensor(__lowerCamelCase ) else timestep self._index_counter[timestep_int] += 1 if self.state_in_first_order: A__ = self.sigmas[step_index] A__ = self.sigmas[step_index + 1] else: # 2nd order / Heun's method A__ = self.sigmas[step_index - 1] A__ = self.sigmas[step_index] # currently only gamma=0 is supported. This usually works best anyways. # We can support gamma in the future but then need to scale the timestep before # passing it to the model which requires a change in API A__ = 0 A__ = sigma * (gamma + 1) # Note: sigma_hat == sigma for now # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise if self.config.prediction_type == "epsilon": A__ = sigma_hat if self.state_in_first_order else sigma_next A__ = sample - sigma_input * model_output elif self.config.prediction_type == "v_prediction": A__ = sigma_hat if self.state_in_first_order else sigma_next A__ = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + ( sample / (sigma_input**2 + 1) ) elif self.config.prediction_type == "sample": A__ = model_output else: raise ValueError( f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`" ) if self.config.clip_sample: A__ = pred_original_sample.clamp( -self.config.clip_sample_range,self.config.clip_sample_range ) if self.state_in_first_order: # 2. Convert to an ODE derivative for 1st order A__ = (sample - pred_original_sample) / sigma_hat # 3. delta timestep A__ = sigma_next - sigma_hat # store for 2nd order step A__ = derivative A__ = dt A__ = sample else: # 2. 2nd order / Heun's method A__ = (sample - pred_original_sample) / sigma_next A__ = (self.prev_derivative + derivative) / 2 # 3. take prev timestep & sample A__ = self.dt A__ = self.sample # free dt and derivative # Note, this puts the scheduler in "first order mode" A__ = None A__ = None A__ = None A__ = sample + derivative * dt if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=__lowerCamelCase ) def UpperCamelCase ( self,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase,): # Make sure sigmas and timesteps have the same device and dtype as original_samples A__ = self.sigmas.to(device=original_samples.device,dtype=original_samples.dtype ) if original_samples.device.type == "mps" and torch.is_floating_point(__lowerCamelCase ): # mps does not support float64 A__ = self.timesteps.to(original_samples.device,dtype=torch.floataa ) A__ = timesteps.to(original_samples.device,dtype=torch.floataa ) else: A__ = self.timesteps.to(original_samples.device ) A__ = timesteps.to(original_samples.device ) A__ = [self.index_for_timestep(__lowerCamelCase,__lowerCamelCase ) for t in timesteps] A__ = sigmas[step_indices].flatten() while len(sigma.shape ) < len(original_samples.shape ): A__ = sigma.unsqueeze(-1 ) A__ = original_samples + noise * sigma return noisy_samples def __len__( self ): return self.config.num_train_timesteps
193
1
from __future__ import annotations def lowerCAmelCase__ ( a__ , a__ ) ->list[list[int]]: '''simple docstring''' _UpperCamelCase = [] create_all_state(1 , __UpperCAmelCase , __UpperCAmelCase , [] , __UpperCAmelCase ) return result def lowerCAmelCase__ ( a__ , a__ , a__ , a__ , a__ , ) ->None: '''simple docstring''' if level == 0: total_list.append(current_list[:] ) return for i in range(__UpperCAmelCase , total_number - level + 2 ): current_list.append(__UpperCAmelCase ) create_all_state(i + 1 , __UpperCAmelCase , level - 1 , __UpperCAmelCase , __UpperCAmelCase ) current_list.pop() def lowerCAmelCase__ ( a__ ) ->None: '''simple docstring''' for i in total_list: print(*__UpperCAmelCase ) if __name__ == "__main__": lowerCamelCase__ = 4 lowerCamelCase__ = 2 lowerCamelCase__ = generate_all_combinations(n, k) print_all_state(total_list)
352
from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable lowerCamelCase__ = {'''configuration_gpt_neox''': ['''GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTNeoXConfig''']} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = ['''GPTNeoXTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ = [ '''GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GPTNeoXForCausalLM''', '''GPTNeoXForQuestionAnswering''', '''GPTNeoXForSequenceClassification''', '''GPTNeoXForTokenClassification''', '''GPTNeoXLayer''', '''GPTNeoXModel''', '''GPTNeoXPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_gpt_neox import GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXConfig try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_neox_fast import GPTNeoXTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox import ( GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXLayer, GPTNeoXModel, GPTNeoXPreTrainedModel, ) else: import sys lowerCamelCase__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
63
0
import os import time import pytest from datasets.utils.filelock import FileLock, Timeout def SCREAMING_SNAKE_CASE_ ( __A : Optional[Any] ) -> Optional[Any]: """simple docstring""" a_ : Optional[int] = FileLock(str(tmpdir / 'foo.lock' ) ) a_ : str = FileLock(str(tmpdir / 'foo.lock' ) ) a_ : Optional[Any] = 0.01 with locka.acquire(): with pytest.raises(__A ): a_ : Tuple = time.time() locka.acquire(__A ) assert time.time() - _start > timeout def SCREAMING_SNAKE_CASE_ ( __A : str ) -> List[Any]: """simple docstring""" a_ : List[Any] = 'a' * 10_00 + '.lock' a_ : List[Any] = FileLock(str(tmpdir / filename ) ) assert locka._lock_file.endswith('.lock' ) assert not locka._lock_file.endswith(__A ) assert len(os.path.basename(locka._lock_file ) ) <= 2_55 a_ : Tuple = FileLock(tmpdir / filename ) with locka.acquire(): with pytest.raises(__A ): locka.acquire(0 )
32
def SCREAMING_SNAKE_CASE_ ( __A : list[int] , __A : str ) -> list[int]: """simple docstring""" a_ : Any = int(__A ) # Initialize Result a_ : Tuple = [] # Traverse through all denomination for denomination in reversed(__A ): # Find denominations while int(__A ) >= int(__A ): total_value -= int(__A ) answer.append(__A ) # Append the "answers" array return answer # Driver Code if __name__ == "__main__": UpperCAmelCase_ : Union[str, Any] = [] UpperCAmelCase_ : Union[str, Any] = '0' if ( input('Do you want to enter your denominations ? (yY/n): ').strip().lower() == "y" ): UpperCAmelCase_ : List[Any] = int(input('Enter the number of denominations you want to add: ').strip()) for i in range(0, n): denominations.append(int(input(F'Denomination {i}: ').strip())) UpperCAmelCase_ : str = input('Enter the change you want to make in Indian Currency: ').strip() else: # All denominations of Indian Currency if user does not enter UpperCAmelCase_ : List[Any] = [1, 2, 5, 10, 20, 50, 100, 500, 2000] UpperCAmelCase_ : str = input('Enter the change you want to make: ').strip() if int(value) == 0 or int(value) < 0: print('The total value cannot be zero or negative.') else: print(F'Following is minimal change for {value}: ') UpperCAmelCase_ : Optional[Any] = find_minimum_change(denominations, value) # Print result for i in range(len(answer)): print(answer[i], end=' ')
32
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _UpperCAmelCase = { 'configuration_lilt': ['LILT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LiltConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase = [ 'LILT_PRETRAINED_MODEL_ARCHIVE_LIST', 'LiltForQuestionAnswering', 'LiltForSequenceClassification', 'LiltForTokenClassification', 'LiltModel', 'LiltPreTrainedModel', ] if TYPE_CHECKING: from .configuration_lilt import LILT_PRETRAINED_CONFIG_ARCHIVE_MAP, LiltConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_lilt import ( LILT_PRETRAINED_MODEL_ARCHIVE_LIST, LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, LiltPreTrainedModel, ) else: import sys _UpperCAmelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
328
from typing import List, Optional, Tuple, Union import PIL import torch from torchvision import transforms from diffusers.pipeline_utils import DiffusionPipeline, ImagePipelineOutput from diffusers.schedulers import DDIMScheduler from diffusers.utils import randn_tensor _UpperCAmelCase = transforms.Compose( [ transforms.Resize((2_5_6, 2_5_6)), transforms.ToTensor(), transforms.Normalize([0.5], [0.5]), ] ) def lowerCAmelCase_ ( UpperCamelCase_ ) -> List[Any]: if isinstance(UpperCamelCase_ , torch.Tensor ): return image elif isinstance(UpperCamelCase_ , PIL.Image.Image ): UpperCamelCase_ = [image] UpperCamelCase_ = [trans(img.convert("RGB" ) ) for img in image] UpperCamelCase_ = torch.stack(UpperCamelCase_ ) return image class _UpperCamelCase ( lowerCAmelCase_ ): def __init__( self: List[Any] , _SCREAMING_SNAKE_CASE: str , _SCREAMING_SNAKE_CASE: Dict ) -> str: """simple docstring""" super().__init__() # make sure scheduler can always be converted to DDIM UpperCamelCase_ = DDIMScheduler.from_config(scheduler.config ) self.register_modules(unet=_SCREAMING_SNAKE_CASE , scheduler=_SCREAMING_SNAKE_CASE ) def lowercase ( self: List[str] , _SCREAMING_SNAKE_CASE: Dict ) -> Optional[Any]: """simple docstring""" if strength < 0 or strength > 1: raise ValueError(f'''The value of strength should in [0.0, 1.0] but is {strength}''' ) def lowercase ( self: str , _SCREAMING_SNAKE_CASE: Any , _SCREAMING_SNAKE_CASE: Optional[Any] , _SCREAMING_SNAKE_CASE: List[str] ) -> int: """simple docstring""" UpperCamelCase_ = min(int(num_inference_steps * strength ) , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = max(num_inference_steps - init_timestep , 0 ) UpperCamelCase_ = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def lowercase ( self: Tuple , _SCREAMING_SNAKE_CASE: Optional[Any] , _SCREAMING_SNAKE_CASE: Optional[Any] , _SCREAMING_SNAKE_CASE: Tuple , _SCREAMING_SNAKE_CASE: Optional[int] , _SCREAMING_SNAKE_CASE: int , _SCREAMING_SNAKE_CASE: Optional[int]=None ) -> List[Any]: """simple docstring""" if not isinstance(_SCREAMING_SNAKE_CASE , (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(_SCREAMING_SNAKE_CASE )}''' ) UpperCamelCase_ = image.to(device=_SCREAMING_SNAKE_CASE , dtype=_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) and len(_SCREAMING_SNAKE_CASE ) != batch_size: raise ValueError( f'''You have passed a list of generators of length {len(_SCREAMING_SNAKE_CASE )}, but requested an effective batch''' f''' size of {batch_size}. Make sure the batch size matches the length of the generators.''' ) UpperCamelCase_ = init_latents.shape UpperCamelCase_ = randn_tensor(_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , device=_SCREAMING_SNAKE_CASE , dtype=_SCREAMING_SNAKE_CASE ) # get latents print("add noise to latents at timestep" , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = self.scheduler.add_noise(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = init_latents return latents @torch.no_grad() def __call__( self: Dict , _SCREAMING_SNAKE_CASE: Union[torch.FloatTensor, PIL.Image.Image] = None , _SCREAMING_SNAKE_CASE: float = 0.8 , _SCREAMING_SNAKE_CASE: int = 1 , _SCREAMING_SNAKE_CASE: Optional[Union[torch.Generator, List[torch.Generator]]] = None , _SCREAMING_SNAKE_CASE: float = 0.0 , _SCREAMING_SNAKE_CASE: int = 50 , _SCREAMING_SNAKE_CASE: Optional[bool] = None , _SCREAMING_SNAKE_CASE: Optional[str] = "pil" , _SCREAMING_SNAKE_CASE: bool = True , ) -> Union[ImagePipelineOutput, Tuple]: """simple docstring""" self.check_inputs(_SCREAMING_SNAKE_CASE ) # 2. Preprocess image UpperCamelCase_ = preprocess(_SCREAMING_SNAKE_CASE ) # 3. set timesteps self.scheduler.set_timesteps(_SCREAMING_SNAKE_CASE , device=self.device ) UpperCamelCase_ , UpperCamelCase_ = self.get_timesteps(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , self.device ) UpperCamelCase_ = timesteps[:1].repeat(_SCREAMING_SNAKE_CASE ) # 4. Prepare latent variables UpperCamelCase_ = self.prepare_latents(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , self.unet.dtype , self.device , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = latents # 5. Denoising loop for t in self.progress_bar(_SCREAMING_SNAKE_CASE ): # 1. predict noise model_output UpperCamelCase_ = self.unet(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 UpperCamelCase_ = self.scheduler.step( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , eta=_SCREAMING_SNAKE_CASE , use_clipped_model_output=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , ).prev_sample UpperCamelCase_ = (image / 2 + 0.5).clamp(0 , 1 ) UpperCamelCase_ = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": UpperCamelCase_ = self.numpy_to_pil(_SCREAMING_SNAKE_CASE ) if not return_dict: return (image, latent_timestep.item()) return ImagePipelineOutput(images=_SCREAMING_SNAKE_CASE )
328
1
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy lowerCAmelCase__ = logging.get_logger(__name__) class lowercase_ (lowerCamelCase__ ): """simple docstring""" def __init__( self : Tuple ,lowercase__ : int ,lowercase__ : int ,lowercase__ : float ,**lowercase__ : str ): __lowercase = feature_size __lowercase = sampling_rate __lowercase = padding_value __lowercase = kwargs.pop('''padding_side''' ,'''right''' ) __lowercase = kwargs.pop('''return_attention_mask''' ,lowercase__ ) super().__init__(**lowercase__ ) def SCREAMING_SNAKE_CASE ( self : Dict ,lowercase__ : Union[ BatchFeature, List[BatchFeature], Dict[str, BatchFeature], Dict[str, List[BatchFeature]], List[Dict[str, BatchFeature]], ] ,lowercase__ : Union[bool, str, PaddingStrategy] = True ,lowercase__ : Optional[int] = None ,lowercase__ : bool = False ,lowercase__ : Optional[int] = None ,lowercase__ : Optional[bool] = None ,lowercase__ : Optional[Union[str, TensorType]] = None ,): # If we have a list of dicts, let's convert it in a dict of lists # We do this to allow using this method as a collate_fn function in PyTorch Dataloader if isinstance(lowercase__ ,(list, tuple) ) and isinstance(processed_features[0] ,(dict, BatchFeature) ): __lowercase = { key: [example[key] for example in processed_features] for key in processed_features[0].keys() } # The model's main input name, usually `input_values`, has be passed for padding if self.model_input_names[0] not in processed_features: raise ValueError( '''You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`''' F" to this method that includes {self.model_input_names[0]}, but you provided" F" {list(processed_features.keys() )}" ) __lowercase = processed_features[self.model_input_names[0]] __lowercase = ( return_attention_mask if return_attention_mask is not None else self.return_attention_mask ) if len(lowercase__ ) == 0: if return_attention_mask: __lowercase = [] return processed_features # If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays # and rebuild them afterwards if no return_tensors is specified # Note that we lose the specific device the tensor may be on for PyTorch __lowercase = required_input[0] if isinstance(lowercase__ ,(list, tuple) ): # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element. __lowercase = 0 while len(required_input[index] ) == 0: index += 1 if index < len(lowercase__ ): __lowercase = required_input[index][0] if return_tensors is None: if is_tf_tensor(lowercase__ ): __lowercase = '''tf''' elif is_torch_tensor(lowercase__ ): __lowercase = '''pt''' elif isinstance(lowercase__ ,(int, float, list, tuple, np.ndarray) ): __lowercase = '''np''' else: raise ValueError( F"type of {first_element} unknown: {type(lowercase__ )}. " '''Should be one of a python, numpy, pytorch or tensorflow object.''' ) for key, value in processed_features.items(): if isinstance(value[0] ,(int, float) ): __lowercase = to_numpy(lowercase__ ) else: __lowercase = [to_numpy(lowercase__ ) for v in value] # Convert padding_strategy in PaddingStrategy __lowercase = self._get_padding_strategies(padding=lowercase__ ,max_length=lowercase__ ) __lowercase = processed_features[self.model_input_names[0]] __lowercase = len(lowercase__ ) if not all(len(lowercase__ ) == batch_size for v in processed_features.values() ): raise ValueError('''Some items in the output dictionary have a different batch size than others.''' ) __lowercase = [] for i in range(lowercase__ ): __lowercase = {k: v[i] for k, v in processed_features.items()} # truncation __lowercase = self._truncate( lowercase__ ,max_length=lowercase__ ,pad_to_multiple_of=lowercase__ ,truncation=lowercase__ ,) truncated_inputs.append(lowercase__ ) if padding_strategy == PaddingStrategy.LONGEST: # make sure that `max_length` cannot be longer than the longest truncated length __lowercase = max(len(input_slice[self.model_input_names[0]] ) for input_slice in truncated_inputs ) __lowercase = PaddingStrategy.MAX_LENGTH __lowercase = {} for i in range(lowercase__ ): # padding __lowercase = self._pad( truncated_inputs[i] ,max_length=lowercase__ ,padding_strategy=lowercase__ ,pad_to_multiple_of=lowercase__ ,return_attention_mask=lowercase__ ,) for key, value in outputs.items(): if key not in batch_outputs: __lowercase = [] if value.dtype is np.dtype(np.floataa ): __lowercase = value.astype(np.floataa ) batch_outputs[key].append(lowercase__ ) return BatchFeature(lowercase__ ,tensor_type=lowercase__ ) def SCREAMING_SNAKE_CASE ( self : str ,lowercase__ : Union[Dict[str, np.ndarray], BatchFeature] ,lowercase__ : Optional[int] = None ,lowercase__ : PaddingStrategy = PaddingStrategy.DO_NOT_PAD ,lowercase__ : Optional[int] = None ,lowercase__ : Optional[bool] = None ,): __lowercase = processed_features[self.model_input_names[0]] if padding_strategy == PaddingStrategy.LONGEST: __lowercase = len(lowercase__ ) if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): __lowercase = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of __lowercase = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(lowercase__ ) < max_length if return_attention_mask and "attention_mask" not in processed_features: __lowercase = np.ones(len(lowercase__ ) ,dtype=np.intaa ) if needs_to_be_padded: __lowercase = max_length - len(lowercase__ ) if self.padding_side == "right": if return_attention_mask: __lowercase = np.pad( processed_features['''attention_mask'''] ,(0, difference) ) __lowercase = ((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference) __lowercase = np.pad( lowercase__ ,lowercase__ ,'''constant''' ,constant_values=self.padding_value ) elif self.padding_side == "left": if return_attention_mask: __lowercase = np.pad( processed_features['''attention_mask'''] ,(difference, 0) ) __lowercase = ((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0) __lowercase = np.pad( lowercase__ ,lowercase__ ,'''constant''' ,constant_values=self.padding_value ) else: raise ValueError('''Invalid padding strategy:''' + str(self.padding_side ) ) return processed_features def SCREAMING_SNAKE_CASE ( self : Tuple ,lowercase__ : Union[Dict[str, np.ndarray], BatchFeature] ,lowercase__ : Optional[int] = None ,lowercase__ : Optional[int] = None ,lowercase__ : Optional[bool] = None ,): if not truncation: return processed_features elif truncation and max_length is None: raise ValueError('''When setting ``truncation=True``, make sure that ``max_length`` is defined.''' ) __lowercase = processed_features[self.model_input_names[0]] # find `max_length` that fits `pad_to_multiple_of` if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): __lowercase = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of __lowercase = len(lowercase__ ) > max_length if needs_to_be_truncated: __lowercase = processed_features[self.model_input_names[0]][:max_length] if "attention_mask" in processed_features: __lowercase = processed_features['''attention_mask'''][:max_length] return processed_features def SCREAMING_SNAKE_CASE ( self : List[str] ,lowercase__ : Dict=False ,lowercase__ : Dict=None ): # Get padding strategy if padding is not False: if padding is True: __lowercase = PaddingStrategy.LONGEST # Default to pad to the longest sequence in the batch elif not isinstance(lowercase__ ,lowercase__ ): __lowercase = PaddingStrategy(lowercase__ ) elif isinstance(lowercase__ ,lowercase__ ): __lowercase = padding else: __lowercase = PaddingStrategy.DO_NOT_PAD # Set max length if needed if max_length is None: if padding_strategy == PaddingStrategy.MAX_LENGTH: raise ValueError( F"When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined" ) # Test if we have a padding value if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None): raise ValueError( '''Asking to pad but the feature_extractor does not have a padding value. Please select a value to use''' ''' as `padding_value`. For example: `feature_extractor.padding_value = 0.0`.''' ) return padding_strategy
104
'''simple docstring''' from __future__ import annotations from random import random from typing import Generic, TypeVar lowerCAmelCase__ = TypeVar('''KT''') lowerCAmelCase__ = TypeVar('''VT''') class lowercase_ (Generic[KT, VT] ): """simple docstring""" def __init__( self : Optional[Any] ,lowercase__ : KT | str = "root" ,lowercase__ : VT | None = None ): __lowercase = key __lowercase = value __lowercase = [] def __repr__( self : Tuple ): return F"Node({self.key}: {self.value})" @property def SCREAMING_SNAKE_CASE ( self : int ): return len(self.forward ) class lowercase_ (Generic[KT, VT] ): """simple docstring""" def __init__( self : int ,lowercase__ : float = 0.5 ,lowercase__ : int = 1_6 ): __lowercase = Node[KT, VT]() __lowercase = 0 __lowercase = p __lowercase = max_level def __str__( self : List[str] ): __lowercase = list(self ) if len(lowercase__ ) == 0: return F"SkipList(level={self.level})" __lowercase = max((len(str(lowercase__ ) ) for item in items) ,default=4 ) __lowercase = max(lowercase__ ,4 ) + 4 __lowercase = self.head __lowercase = [] __lowercase = node.forward.copy() lines.append(F"[{node.key}]".ljust(lowercase__ ,'''-''' ) + '''* ''' * len(lowercase__ ) ) lines.append(''' ''' * label_size + '''| ''' * len(lowercase__ ) ) while len(node.forward ) != 0: __lowercase = node.forward[0] lines.append( F"[{node.key}]".ljust(lowercase__ ,'''-''' ) + ''' '''.join(str(n.key ) if n.key == node.key else '''|''' for n in forwards ) ) lines.append(''' ''' * label_size + '''| ''' * len(lowercase__ ) ) __lowercase = node.forward lines.append('''None'''.ljust(lowercase__ ) + '''* ''' * len(lowercase__ ) ) return F"SkipList(level={self.level})\n" + "\n".join(lowercase__ ) def __iter__( self : List[str] ): __lowercase = self.head while len(node.forward ) != 0: yield node.forward[0].key __lowercase = node.forward[0] def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): __lowercase = 1 while random() < self.p and level < self.max_level: level += 1 return level def SCREAMING_SNAKE_CASE ( self : List[str] ,lowercase__ : str ): __lowercase = [] __lowercase = self.head for i in reversed(range(self.level ) ): # i < node.level - When node level is lesser than `i` decrement `i`. # node.forward[i].key < key - Jumping to node with key value higher # or equal to searched key would result # in skipping searched key. while i < node.level and node.forward[i].key < key: __lowercase = node.forward[i] # Each leftmost node (relative to searched node) will potentially have to # be updated. update_vector.append(lowercase__ ) update_vector.reverse() # Note that we were inserting values in reverse order. # len(node.forward) != 0 - If current node doesn't contain any further # references then searched key is not present. # node.forward[0].key == key - Next node key should be equal to search key # if key is present. if len(node.forward ) != 0 and node.forward[0].key == key: return node.forward[0], update_vector else: return None, update_vector def SCREAMING_SNAKE_CASE ( self : List[str] ,lowercase__ : KT ): __lowercase , __lowercase = self._locate_node(lowercase__ ) if node is not None: for i, update_node in enumerate(lowercase__ ): # Remove or replace all references to removed node. if update_node.level > i and update_node.forward[i].key == key: if node.level > i: __lowercase = node.forward[i] else: __lowercase = update_node.forward[:i] def SCREAMING_SNAKE_CASE ( self : List[str] ,lowercase__ : KT ,lowercase__ : VT ): __lowercase , __lowercase = self._locate_node(lowercase__ ) if node is not None: __lowercase = value else: __lowercase = self.random_level() if level > self.level: # After level increase we have to add additional nodes to head. for _ in range(self.level - 1 ,lowercase__ ): update_vector.append(self.head ) __lowercase = level __lowercase = Node(lowercase__ ,lowercase__ ) for i, update_node in enumerate(update_vector[:level] ): # Change references to pass through new node. if update_node.level > i: new_node.forward.append(update_node.forward[i] ) if update_node.level < i + 1: update_node.forward.append(lowercase__ ) else: __lowercase = new_node def SCREAMING_SNAKE_CASE ( self : List[Any] ,lowercase__ : VT ): __lowercase , __lowercase = self._locate_node(lowercase__ ) if node is not None: return node.value return None def _A ( ): """simple docstring""" __lowercase = SkipList() skip_list.insert('''Key1''' , 3 ) skip_list.insert('''Key2''' , 12 ) skip_list.insert('''Key3''' , 41 ) skip_list.insert('''Key4''' , -19 ) __lowercase = skip_list.head __lowercase = {} while node.level != 0: __lowercase = node.forward[0] __lowercase = node.value assert len(A__ ) == 4 assert all_values["Key1"] == 3 assert all_values["Key2"] == 12 assert all_values["Key3"] == 41 assert all_values["Key4"] == -19 def _A ( ): """simple docstring""" __lowercase = SkipList() skip_list.insert('''Key1''' , 10 ) skip_list.insert('''Key1''' , 12 ) skip_list.insert('''Key5''' , 7 ) skip_list.insert('''Key7''' , 10 ) skip_list.insert('''Key10''' , 5 ) skip_list.insert('''Key7''' , 7 ) skip_list.insert('''Key5''' , 5 ) skip_list.insert('''Key10''' , 10 ) __lowercase = skip_list.head __lowercase = {} while node.level != 0: __lowercase = node.forward[0] __lowercase = node.value if len(A__ ) != 4: print() assert len(A__ ) == 4 assert all_values["Key1"] == 12 assert all_values["Key7"] == 7 assert all_values["Key5"] == 5 assert all_values["Key10"] == 10 def _A ( ): """simple docstring""" __lowercase = SkipList() assert skip_list.find('''Some key''' ) is None def _A ( ): """simple docstring""" __lowercase = SkipList() skip_list.insert('''Key2''' , 20 ) assert skip_list.find('''Key2''' ) == 20 skip_list.insert('''Some Key''' , 10 ) skip_list.insert('''Key2''' , 8 ) skip_list.insert('''V''' , 13 ) assert skip_list.find('''Y''' ) is None assert skip_list.find('''Key2''' ) == 8 assert skip_list.find('''Some Key''' ) == 10 assert skip_list.find('''V''' ) == 13 def _A ( ): """simple docstring""" __lowercase = SkipList() skip_list.delete('''Some key''' ) assert len(skip_list.head.forward ) == 0 def _A ( ): """simple docstring""" __lowercase = SkipList() skip_list.insert('''Key1''' , 12 ) skip_list.insert('''V''' , 13 ) skip_list.insert('''X''' , 14 ) skip_list.insert('''Key2''' , 15 ) skip_list.delete('''V''' ) skip_list.delete('''Key2''' ) assert skip_list.find('''V''' ) is None assert skip_list.find('''Key2''' ) is None def _A ( ): """simple docstring""" __lowercase = SkipList() skip_list.insert('''Key1''' , 12 ) skip_list.insert('''V''' , 13 ) skip_list.insert('''X''' , 14 ) skip_list.insert('''Key2''' , 15 ) skip_list.delete('''V''' ) assert skip_list.find('''V''' ) is None assert skip_list.find('''X''' ) == 14 assert skip_list.find('''Key1''' ) == 12 assert skip_list.find('''Key2''' ) == 15 skip_list.delete('''X''' ) assert skip_list.find('''V''' ) is None assert skip_list.find('''X''' ) is None assert skip_list.find('''Key1''' ) == 12 assert skip_list.find('''Key2''' ) == 15 skip_list.delete('''Key1''' ) assert skip_list.find('''V''' ) is None assert skip_list.find('''X''' ) is None assert skip_list.find('''Key1''' ) is None assert skip_list.find('''Key2''' ) == 15 skip_list.delete('''Key2''' ) assert skip_list.find('''V''' ) is None assert skip_list.find('''X''' ) is None assert skip_list.find('''Key1''' ) is None assert skip_list.find('''Key2''' ) is None def _A ( ): """simple docstring""" __lowercase = SkipList() skip_list.insert('''Key1''' , 12 ) skip_list.insert('''V''' , 13 ) skip_list.insert('''X''' , 142 ) skip_list.insert('''Key2''' , 15 ) skip_list.delete('''X''' ) def traverse_keys(A__ ): yield node.key for forward_node in node.forward: yield from traverse_keys(A__ ) assert len(set(traverse_keys(skip_list.head ) ) ) == 4 def _A ( ): """simple docstring""" def is_sorted(A__ ): return all(next_item >= item for item, next_item in zip(A__ , lst[1:] ) ) __lowercase = SkipList() for i in range(10 ): skip_list.insert(A__ , A__ ) assert is_sorted(list(A__ ) ) skip_list.delete(5 ) skip_list.delete(8 ) skip_list.delete(2 ) assert is_sorted(list(A__ ) ) skip_list.insert(-12 , -12 ) skip_list.insert(77 , 77 ) assert is_sorted(list(A__ ) ) def _A ( ): """simple docstring""" for _ in range(100 ): # Repeat test 100 times due to the probabilistic nature of skip list # random values == random bugs test_insert() test_insert_overrides_existing_value() test_searching_empty_list_returns_none() test_search() test_deleting_item_from_empty_list_do_nothing() test_deleted_items_are_not_founded_by_find_method() test_delete_removes_only_given_key() test_delete_doesnt_leave_dead_nodes() test_iter_always_yields_sorted_values() def _A ( ): """simple docstring""" __lowercase = SkipList() skip_list.insert(2 , '''2''' ) skip_list.insert(4 , '''4''' ) skip_list.insert(6 , '''4''' ) skip_list.insert(4 , '''5''' ) skip_list.insert(8 , '''4''' ) skip_list.insert(9 , '''4''' ) skip_list.delete(4 ) print(A__ ) if __name__ == "__main__": import doctest doctest.testmod() main()
104
1
from __future__ import annotations import copy import inspect import unittest import numpy as np from transformers import is_tf_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, ) if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class __A: def __init__( self , _snake_case , _snake_case=2 , _snake_case=3 , _snake_case=4 , _snake_case=2 , _snake_case=7 , _snake_case=True , _snake_case=True , _snake_case=True , _snake_case=True , _snake_case=99 , _snake_case=36 , _snake_case=2 , _snake_case=4 , _snake_case=37 , _snake_case="gelu" , _snake_case=0.1 , _snake_case=0.1 , _snake_case=512 , _snake_case=16 , _snake_case=2 , _snake_case=0.02 , _snake_case=6 , _snake_case=6 , _snake_case=3 , _snake_case=4 , _snake_case=None , _snake_case=1_000 , ) -> int: '''simple docstring''' __a = parent __a = batch_size __a = num_channels __a = image_size __a = patch_size __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 SCREAMING_SNAKE_CASE_ ( self ) -> Tuple: '''simple docstring''' __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 ) __a = bbox.numpy() # 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 = tmp_coordinate if bbox[i, j, 2] < bbox[i, j, 0]: __a = bbox[i, j, 2] __a = bbox[i, j, 0] __a = tmp_coordinate __a = tf.constant(_snake_case ) __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 SCREAMING_SNAKE_CASE_ ( self , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case ) -> List[Any]: '''simple docstring''' __a = TFLayoutLMvaModel(config=_snake_case ) # text + image __a = model(_snake_case , pixel_values=_snake_case , training=_snake_case ) __a = model( _snake_case , bbox=_snake_case , pixel_values=_snake_case , attention_mask=_snake_case , token_type_ids=_snake_case , training=_snake_case , ) __a = model(_snake_case , bbox=_snake_case , pixel_values=_snake_case , training=_snake_case ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only __a = model(_snake_case , training=_snake_case ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only __a = model({'''pixel_values''': pixel_values} , training=_snake_case ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE_ ( self , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case ) -> Optional[Any]: '''simple docstring''' __a = self.num_labels __a = TFLayoutLMvaForSequenceClassification(config=_snake_case ) __a = model( _snake_case , bbox=_snake_case , pixel_values=_snake_case , attention_mask=_snake_case , token_type_ids=_snake_case , labels=_snake_case , training=_snake_case , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE_ ( self , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case ) -> Tuple: '''simple docstring''' __a = self.num_labels __a = TFLayoutLMvaForTokenClassification(config=_snake_case ) __a = model( _snake_case , bbox=_snake_case , pixel_values=_snake_case , attention_mask=_snake_case , token_type_ids=_snake_case , labels=_snake_case , training=_snake_case , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def SCREAMING_SNAKE_CASE_ ( self , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case ) -> Any: '''simple docstring''' __a = 2 __a = TFLayoutLMvaForQuestionAnswering(config=_snake_case ) __a = model( _snake_case , bbox=_snake_case , pixel_values=_snake_case , attention_mask=_snake_case , token_type_ids=_snake_case , start_positions=_snake_case , end_positions=_snake_case , training=_snake_case , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def SCREAMING_SNAKE_CASE_ ( self ) -> Optional[int]: '''simple docstring''' __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_tf class __A( a , a , unittest.TestCase ): snake_case_ = ( ( TFLayoutLMvaModel, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, ) if is_tf_available() else () ) snake_case_ = ( {'''document-question-answering''': TFLayoutLMvaForQuestionAnswering, '''feature-extraction''': TFLayoutLMvaModel} if is_tf_available() else {} ) snake_case_ = False snake_case_ = False snake_case_ = False def SCREAMING_SNAKE_CASE_ ( self , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case ) -> int: '''simple docstring''' return True def SCREAMING_SNAKE_CASE_ ( self , _snake_case , _snake_case , _snake_case=False ) -> dict: '''simple docstring''' __a = copy.deepcopy(_snake_case ) if model_class in get_values(_snake_case ): __a = { k: tf.tile(tf.expand_dims(_snake_case , 1 ) , (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1) ) if isinstance(_snake_case , tf.Tensor ) and v.ndim > 0 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(_snake_case ): __a = tf.ones(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(_snake_case ): __a = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) __a = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(_snake_case ): __a = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(_snake_case ): __a = tf.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=tf.intaa ) return inputs_dict def SCREAMING_SNAKE_CASE_ ( self ) -> Dict: '''simple docstring''' __a = TFLayoutLMvaModelTester(self ) __a = ConfigTester(self , config_class=_snake_case , hidden_size=37 ) def SCREAMING_SNAKE_CASE_ ( self ) -> int: '''simple docstring''' self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE_ ( self ) -> Any: '''simple docstring''' __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(_snake_case ) if getattr(_snake_case , '''hf_compute_loss''' , _snake_case ): # The number of elements in the loss should be the same as the number of elements in the label __a = self._prepare_for_class(inputs_dict.copy() , _snake_case , return_labels=_snake_case ) __a = prepared_for_class[ sorted(prepared_for_class.keys() - inputs_dict.keys() , reverse=_snake_case )[0] ] __a = added_label.shape.as_list()[:1] # Test that model correctly compute the loss with kwargs __a = self._prepare_for_class(inputs_dict.copy() , _snake_case , return_labels=_snake_case ) __a = prepared_for_class.pop('''input_ids''' ) __a = model(_snake_case , **_snake_case )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss when we mask some positions __a = self._prepare_for_class(inputs_dict.copy() , _snake_case , return_labels=_snake_case ) __a = prepared_for_class.pop('''input_ids''' ) if "labels" in prepared_for_class: __a = prepared_for_class['''labels'''].numpy() if len(labels.shape ) > 1 and labels.shape[1] != 1: __a = -100 __a = tf.convert_to_tensor(_snake_case ) __a = model(_snake_case , **_snake_case )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) self.assertTrue(not np.any(np.isnan(loss.numpy() ) ) ) # Test that model correctly compute the loss with a dict __a = self._prepare_for_class(inputs_dict.copy() , _snake_case , return_labels=_snake_case ) __a = model(_snake_case )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss with a tuple __a = self._prepare_for_class(inputs_dict.copy() , _snake_case , return_labels=_snake_case ) # Get keys that were added with the _prepare_for_class function __a = prepared_for_class.keys() - inputs_dict.keys() __a = inspect.signature(model.call ).parameters __a = list(signature.keys() ) # Create a dictionary holding the location of the tensors in the tuple __a = {0: '''input_ids'''} for label_key in label_keys: __a = signature_names.index(_snake_case ) __a = label_key __a = sorted(tuple_index_mapping.items() ) # Initialize a list with their default values, update the values and convert to a tuple __a = [] for name in signature_names: if name != "kwargs": list_input.append(signature[name].default ) for index, value in sorted_tuple_index_mapping: __a = prepared_for_class[value] __a = tuple(_snake_case ) # Send to model __a = model(tuple_input[:-1] )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) def SCREAMING_SNAKE_CASE_ ( self ) -> Tuple: '''simple docstring''' ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(_snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case ) def SCREAMING_SNAKE_CASE_ ( self ) -> int: '''simple docstring''' ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __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(_snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case ) def SCREAMING_SNAKE_CASE_ ( self ) -> str: '''simple docstring''' ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification( _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case ) def SCREAMING_SNAKE_CASE_ ( self ) -> Union[str, Any]: '''simple docstring''' ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification( _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case ) def SCREAMING_SNAKE_CASE_ ( self ) -> Any: '''simple docstring''' ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering( _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case ) @slow def SCREAMING_SNAKE_CASE_ ( self ) -> Optional[int]: '''simple docstring''' for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = TFLayoutLMvaModel.from_pretrained(_snake_case ) self.assertIsNotNone(_snake_case ) def __lowerCAmelCase ( ) -> int: __a = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_tf class __A( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE_ ( self ) -> List[Any]: '''simple docstring''' return LayoutLMvaImageProcessor(apply_ocr=_snake_case ) if is_vision_available() else None @slow def SCREAMING_SNAKE_CASE_ ( self ) -> Union[str, Any]: '''simple docstring''' __a = TFLayoutLMvaModel.from_pretrained('''microsoft/layoutlmv3-base''' ) __a = self.default_image_processor __a = prepare_img() __a = image_processor(images=_snake_case , return_tensors='''tf''' ).pixel_values __a = tf.constant([[1, 2]] ) __a = tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]] ) , axis=0 ) # forward pass __a = model(input_ids=_snake_case , bbox=_snake_case , pixel_values=_snake_case , training=_snake_case ) # verify the logits __a = (1, 199, 768) self.assertEqual(outputs.last_hidden_state.shape , _snake_case ) __a = tf.constant( [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]] ) self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3] , _snake_case , atol=1E-4 ) )
352
import argparse import fairseq import torch from transformers import UniSpeechSatConfig, UniSpeechSatForCTC, UniSpeechSatForPreTraining, logging logging.set_verbosity_info() A : str = logging.get_logger(__name__) A : Any = { 'post_extract_proj': 'feature_projection.projection', 'encoder.pos_conv.0': 'encoder.pos_conv_embed.conv', 'self_attn.k_proj': 'encoder.layers.*.attention.k_proj', 'self_attn.v_proj': 'encoder.layers.*.attention.v_proj', 'self_attn.q_proj': 'encoder.layers.*.attention.q_proj', 'self_attn.out_proj': 'encoder.layers.*.attention.out_proj', 'self_attn_layer_norm': 'encoder.layers.*.layer_norm', 'fc1': 'encoder.layers.*.feed_forward.intermediate_dense', 'fc2': 'encoder.layers.*.feed_forward.output_dense', 'final_layer_norm': 'encoder.layers.*.final_layer_norm', 'encoder.layer_norm': 'encoder.layer_norm', 'encoder.layer_norm_for_extract': 'layer_norm_for_extract', 'w2v_model.layer_norm': 'feature_projection.layer_norm', 'quantizer.weight_proj': 'quantizer.weight_proj', 'quantizer.vars': 'quantizer.codevectors', 'project_q': 'project_q', 'final_proj': 'project_hid', 'w2v_encoder.proj': 'lm_head', 'label_embs_concat': 'label_embeddings_concat', 'mask_emb': 'masked_spec_embed', 'spk_proj': 'speaker_proj', } A : Optional[Any] = [ 'lm_head', 'quantizer.weight_proj', 'quantizer.codevectors', 'project_q', 'project_hid', 'label_embeddings_concat', 'speaker_proj', 'layer_norm_for_extract', ] def __lowerCAmelCase ( a__ , a__ , a__ , a__ , a__ ) -> Dict: for attribute in key.split('''.''' ): __a = getattr(a__ , a__ ) if weight_type is not None: __a = getattr(a__ , a__ ).shape else: __a = hf_pointer.shape if hf_shape != value.shape: raise ValueError( F"""Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be""" F""" {value.shape} for {full_name}""" ) if weight_type == "weight": __a = value elif weight_type == "weight_g": __a = value elif weight_type == "weight_v": __a = value elif weight_type == "bias": __a = value else: __a = value logger.info(F"""{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.""" ) def __lowerCAmelCase ( a__ , a__ ) -> List[str]: __a = [] __a = fairseq_model.state_dict() __a = hf_model.unispeech_sat.feature_extractor for name, value in fairseq_dict.items(): __a = False if "conv_layers" in name: load_conv_layer( a__ , a__ , a__ , a__ , hf_model.config.feat_extract_norm == '''group''' , ) __a = True else: for key, mapped_key in MAPPING.items(): __a = '''unispeech_sat.''' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0]: if "layer_norm_for_extract" in name and (".".join(name.split('''.''' )[:-1] ) != key): # special case since naming is very similar continue __a = True if "*" in mapped_key: __a = name.split(a__ )[0].split('''.''' )[-2] __a = mapped_key.replace('''*''' , a__ ) if "weight_g" in name: __a = '''weight_g''' elif "weight_v" in name: __a = '''weight_v''' elif "bias" in name: __a = '''bias''' elif "weight" in name: # TODO: don't match quantizer.weight_proj __a = '''weight''' else: __a = None set_recursively(a__ , a__ , a__ , a__ , a__ ) continue if not is_used: unused_weights.append(a__ ) logger.warning(F"""Unused weights: {unused_weights}""" ) def __lowerCAmelCase ( a__ , a__ , a__ , a__ , a__ ) -> int: __a = full_name.split('''conv_layers.''' )[-1] __a = name.split('''.''' ) __a = int(items[0] ) __a = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) __a = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) __a = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor[layer_id].layer_norm.bias.data.shape} was found.""" ) __a = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.""" ) __a = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(a__ ) @torch.no_grad() def __lowerCAmelCase ( a__ , a__ , a__=None , a__=None , a__=True ) -> Tuple: if config_path is not None: __a = UniSpeechSatConfig.from_pretrained(a__ ) else: __a = UniSpeechSatConfig() __a = '''''' if is_finetuned: __a = UniSpeechSatForCTC(a__ ) else: __a = UniSpeechSatForPreTraining(a__ ) __a , __a , __a = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] )} ) __a = model[0].eval() recursively_load_weights(a__ , a__ ) hf_wavavec.save_pretrained(a__ ) if __name__ == "__main__": A : List[Any] = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint') parser.add_argument('--dict_path', default=None, type=str, help='Path to dict of fine-tuned model') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') parser.add_argument( '--not_finetuned', action='store_true', help='Whether the model to convert is a fine-tuned model or not' ) A : Dict = parser.parse_args() convert_unispeech_sat_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
33
0
"""simple docstring""" import pytest import datasets # Import fixture modules as plugins UpperCamelCase_ = ['tests.fixtures.files', 'tests.fixtures.hub', 'tests.fixtures.fsspec'] def UpperCamelCase ( UpperCAmelCase , UpperCAmelCase ) ->List[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 ( UpperCAmelCase ) ->str: """simple docstring""" config.addinivalue_line("markers" , "torchaudio_latest: mark test to run with torchaudio>=0.12" ) @pytest.fixture(autouse=UpperCAmelCase ) def UpperCamelCase ( UpperCAmelCase , UpperCAmelCase ) ->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(UpperCAmelCase ) ) monkeypatch.setattr("datasets.config.HF_METRICS_CACHE" , str(UpperCAmelCase ) ) monkeypatch.setattr("datasets.config.HF_MODULES_CACHE" , str(UpperCAmelCase ) ) a_ = test_hf_datasets_cache / "downloads" monkeypatch.setattr("datasets.config.DOWNLOADED_DATASETS_PATH" , str(UpperCAmelCase ) ) a_ = test_hf_datasets_cache / "downloads" / "extracted" monkeypatch.setattr("datasets.config.EXTRACTED_DATASETS_PATH" , str(UpperCAmelCase ) ) @pytest.fixture(autouse=UpperCAmelCase , scope="session" ) def UpperCamelCase ( ) ->Any: """simple docstring""" datasets.disable_progress_bar() @pytest.fixture(autouse=UpperCAmelCase ) def UpperCamelCase ( UpperCAmelCase ) ->Optional[Any]: """simple docstring""" monkeypatch.setattr("datasets.config.HF_UPDATE_DOWNLOAD_COUNTS" , UpperCAmelCase ) @pytest.fixture def UpperCamelCase ( UpperCAmelCase ) ->Tuple: """simple docstring""" monkeypatch.setattr("sqlalchemy.util.deprecations.SILENCE_UBER_WARNING" , UpperCAmelCase )
243
"""simple docstring""" import argparse import glob import importlib.util import os import re import black from doc_builder.style_doc import style_docstrings_in_code # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py UpperCamelCase_ = 'src/diffusers' UpperCamelCase_ = '.' # This is to make sure the diffusers module imported is the one in the repo. UpperCamelCase_ = importlib.util.spec_from_file_location( 'diffusers', os.path.join(DIFFUSERS_PATH, '__init__.py'), submodule_search_locations=[DIFFUSERS_PATH], ) UpperCamelCase_ = spec.loader.load_module() def UpperCamelCase ( UpperCAmelCase , UpperCAmelCase ) ->Dict: """simple docstring""" return line.startswith(UpperCAmelCase ) or len(UpperCAmelCase ) <= 1 or re.search(r"^\s*\)(\s*->.*:|:)\s*$" , UpperCAmelCase ) is not None def UpperCamelCase ( UpperCAmelCase ) ->Any: """simple docstring""" a_ = object_name.split("." ) a_ = 0 # First let's find the module where our object lives. a_ = parts[i] while i < len(UpperCAmelCase ) and not os.path.isfile(os.path.join(UpperCAmelCase , F'''{module}.py''' ) ): i += 1 if i < len(UpperCAmelCase ): a_ = os.path.join(UpperCAmelCase , parts[i] ) if i >= len(UpperCAmelCase ): raise ValueError(F'''`object_name` should begin with the name of a module of diffusers but got {object_name}.''' ) with open(os.path.join(UpperCAmelCase , F'''{module}.py''' ) , "r" , encoding="utf-8" , newline="\n" ) as f: a_ = f.readlines() # Now let's find the class / func in the code! a_ = "" a_ = 0 for name in parts[i + 1 :]: while ( line_index < len(UpperCAmelCase ) and re.search(rF'''^{indent}(class|def)\s+{name}(\(|\:)''' , lines[line_index] ) is None ): line_index += 1 indent += " " line_index += 1 if line_index >= len(UpperCAmelCase ): raise ValueError(F''' {object_name} does not match any function or class in {module}.''' ) # We found the beginning of the class / func, now let's find the end (when the indent diminishes). a_ = line_index while line_index < len(UpperCAmelCase ) and _should_continue(lines[line_index] , UpperCAmelCase ): line_index += 1 # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 a_ = lines[start_index:line_index] return "".join(UpperCAmelCase ) UpperCamelCase_ = re.compile(R'^(\s*)#\s*Copied from\s+diffusers\.(\S+\.\S+)\s*($|\S.*$)') UpperCamelCase_ = re.compile(R'^\s*(\S+)->(\S+)(\s+.*|$)') UpperCamelCase_ = re.compile(R'<FILL\s+[^>]*>') def UpperCamelCase ( UpperCAmelCase ) ->int: """simple docstring""" a_ = code.split("\n" ) a_ = 0 while idx < len(UpperCAmelCase ) and len(lines[idx] ) == 0: idx += 1 if idx < len(UpperCAmelCase ): return re.search(r"^(\s*)\S" , lines[idx] ).groups()[0] return "" def UpperCamelCase ( UpperCAmelCase ) ->int: """simple docstring""" a_ = len(get_indent(UpperCAmelCase ) ) > 0 if has_indent: a_ = F'''class Bla:\n{code}''' a_ = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=119 , preview=UpperCAmelCase ) a_ = black.format_str(UpperCAmelCase , mode=UpperCAmelCase ) a_ , a_ = style_docstrings_in_code(UpperCAmelCase ) return result[len("class Bla:\n" ) :] if has_indent else result def UpperCamelCase ( UpperCAmelCase , UpperCAmelCase=False ) ->str: """simple docstring""" with open(UpperCAmelCase , "r" , encoding="utf-8" , newline="\n" ) as f: a_ = f.readlines() a_ = [] a_ = 0 # Not a for loop cause `lines` is going to change (if `overwrite=True`). while line_index < len(UpperCAmelCase ): a_ = _re_copy_warning.search(lines[line_index] ) if search is None: line_index += 1 continue # There is some copied code here, let's retrieve the original. a_ , a_ , a_ = search.groups() a_ = find_code_in_diffusers(UpperCAmelCase ) a_ = get_indent(UpperCAmelCase ) a_ = line_index + 1 if indent == theoretical_indent else line_index + 2 a_ = theoretical_indent a_ = start_index # Loop to check the observed code, stop when indentation diminishes or if we see a End copy comment. a_ = True while line_index < len(UpperCAmelCase ) and should_continue: line_index += 1 if line_index >= len(UpperCAmelCase ): break a_ = lines[line_index] a_ = _should_continue(UpperCAmelCase , UpperCAmelCase ) and re.search(F'''^{indent}# End copy''' , UpperCAmelCase ) is None # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 a_ = lines[start_index:line_index] a_ = "".join(UpperCAmelCase ) # Remove any nested `Copied from` comments to avoid circular copies a_ = [line for line in theoretical_code.split("\n" ) if _re_copy_warning.search(UpperCAmelCase ) is None] a_ = "\n".join(UpperCAmelCase ) # Before comparing, use the `replace_pattern` on the original code. if len(UpperCAmelCase ) > 0: a_ = replace_pattern.replace("with" , "" ).split("," ) a_ = [_re_replace_pattern.search(UpperCAmelCase ) for p in patterns] for pattern in patterns: if pattern is None: continue a_ , a_ , a_ = pattern.groups() a_ = re.sub(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) if option.strip() == "all-casing": a_ = re.sub(obja.lower() , obja.lower() , UpperCAmelCase ) a_ = re.sub(obja.upper() , obja.upper() , UpperCAmelCase ) # Blackify after replacement. To be able to do that, we need the header (class or function definition) # from the previous line a_ = blackify(lines[start_index - 1] + theoretical_code ) a_ = theoretical_code[len(lines[start_index - 1] ) :] # Test for a diff and act accordingly. if observed_code != theoretical_code: diffs.append([object_name, start_index] ) if overwrite: a_ = lines[:start_index] + [theoretical_code] + lines[line_index:] a_ = start_index + 1 if overwrite and len(UpperCAmelCase ) > 0: # Warn the user a file has been modified. print(F'''Detected changes, rewriting {filename}.''' ) with open(UpperCAmelCase , "w" , encoding="utf-8" , newline="\n" ) as f: f.writelines(UpperCAmelCase ) return diffs def UpperCamelCase ( UpperCAmelCase = False ) ->int: """simple docstring""" a_ = glob.glob(os.path.join(UpperCAmelCase , "**/*.py" ) , recursive=UpperCAmelCase ) a_ = [] for filename in all_files: a_ = is_copy_consistent(UpperCAmelCase , UpperCAmelCase ) diffs += [F'''- {filename}: copy does not match {d[0]} at line {d[1]}''' for d in new_diffs] if not overwrite and len(UpperCAmelCase ) > 0: a_ = "\n".join(UpperCAmelCase ) raise Exception( "Found the following copy inconsistencies:\n" + diff + "\nRun `make fix-copies` or `python utils/check_copies.py --fix_and_overwrite` to fix them." ) if __name__ == "__main__": UpperCamelCase_ = argparse.ArgumentParser() parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.') UpperCamelCase_ = parser.parse_args() check_copies(args.fix_and_overwrite)
243
1
"""simple docstring""" from __future__ import annotations def A_ ( A__ ) -> str: if len(a_ ) == 0: return array a__ : List[str] = min(a_ ), max(a_ ) # Compute the variables a__ : str = _max - _min + 1 a__ : Dict = [0] * holes_range, [0] * holes_range # Make the sorting. for i in array: a__ : int = i - _min a__ : List[str] = i holes_repeat[index] += 1 # Makes the array back by replacing the numbers. a__ : Tuple = 0 for i in range(a_ ): while holes_repeat[i] > 0: a__ : Tuple = holes[i] index += 1 holes_repeat[i] -= 1 # Returns the sorted array. return array if __name__ == "__main__": import doctest doctest.testmod() lowercase : Tuple = input("""Enter numbers separated by comma:\n""") lowercase : Dict = [int(x) for x in user_input.split(""",""")] print(pigeon_sort(unsorted))
367
import unittest from transformers import AutoTokenizer, NystromformerConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( NystromformerForMaskedLM, NystromformerForMultipleChoice, NystromformerForQuestionAnswering, NystromformerForSequenceClassification, NystromformerForTokenClassification, NystromformerModel, ) from transformers.models.nystromformer.modeling_nystromformer import NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST class A__ : """simple docstring""" def __init__( self , lowercase , lowercase=13 , lowercase=7 , lowercase=True , lowercase=True , lowercase=True , lowercase=True , lowercase=99 , lowercase=32 , lowercase=5 , lowercase=4 , lowercase=37 , lowercase="gelu" , lowercase=0.1 , lowercase=0.1 , lowercase=512 , lowercase=16 , lowercase=2 , lowercase=0.02 , lowercase=3 , lowercase=4 , lowercase=None , ) -> List[Any]: '''simple docstring''' a__ : Any = parent a__ : int = batch_size a__ : Dict = seq_length a__ : Tuple = is_training a__ : Any = use_input_mask a__ : Optional[Any] = use_token_type_ids a__ : Dict = use_labels a__ : Optional[int] = vocab_size a__ : List[Any] = hidden_size a__ : int = num_hidden_layers a__ : Optional[Any] = num_attention_heads a__ : str = intermediate_size a__ : Optional[int] = hidden_act a__ : Dict = hidden_dropout_prob a__ : Optional[int] = attention_probs_dropout_prob a__ : Tuple = max_position_embeddings a__ : Dict = type_vocab_size a__ : Any = type_sequence_label_size a__ : List[str] = initializer_range a__ : List[str] = num_labels a__ : Optional[Any] = num_choices a__ : str = scope def __lowercase ( self) -> Union[str, Any]: '''simple docstring''' a__ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) a__ : Tuple = None if self.use_input_mask: a__ : Optional[int] = random_attention_mask([self.batch_size, self.seq_length]) a__ : Any = None if self.use_token_type_ids: a__ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size) a__ : str = None a__ : List[Any] = None a__ : List[str] = None if self.use_labels: a__ : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size) a__ : str = ids_tensor([self.batch_size, self.seq_length] , self.num_labels) a__ : str = ids_tensor([self.batch_size] , self.num_choices) a__ : Union[str, Any] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowercase ( self) -> Optional[int]: '''simple docstring''' return NystromformerConfig( 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=lowercase , initializer_range=self.initializer_range , ) def __lowercase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase) -> Optional[int]: '''simple docstring''' a__ : Union[str, Any] = NystromformerModel(config=lowercase) model.to(lowercase) model.eval() a__ : List[Any] = model(lowercase , attention_mask=lowercase , token_type_ids=lowercase) a__ : int = model(lowercase , token_type_ids=lowercase) a__ : Optional[Any] = model(lowercase) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def __lowercase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase) -> str: '''simple docstring''' a__ : List[str] = NystromformerForMaskedLM(config=lowercase) model.to(lowercase) model.eval() a__ : int = model(lowercase , attention_mask=lowercase , token_type_ids=lowercase , labels=lowercase) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def __lowercase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase) -> Union[str, Any]: '''simple docstring''' a__ : Any = NystromformerForQuestionAnswering(config=lowercase) model.to(lowercase) model.eval() a__ : str = model( lowercase , attention_mask=lowercase , token_type_ids=lowercase , start_positions=lowercase , end_positions=lowercase , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length)) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length)) def __lowercase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase) -> Optional[Any]: '''simple docstring''' a__ : int = self.num_labels a__ : Optional[Any] = NystromformerForSequenceClassification(lowercase) model.to(lowercase) model.eval() a__ : Tuple = model(lowercase , attention_mask=lowercase , token_type_ids=lowercase , labels=lowercase) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def __lowercase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase) -> List[str]: '''simple docstring''' a__ : Tuple = self.num_labels a__ : int = NystromformerForTokenClassification(config=lowercase) model.to(lowercase) model.eval() a__ : str = model(lowercase , attention_mask=lowercase , token_type_ids=lowercase , labels=lowercase) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels)) def __lowercase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase) -> Any: '''simple docstring''' a__ : Optional[int] = self.num_choices a__ : Tuple = NystromformerForMultipleChoice(config=lowercase) model.to(lowercase) model.eval() a__ : Optional[Any] = input_ids.unsqueeze(1).expand(-1 , self.num_choices , -1).contiguous() a__ : Tuple = token_type_ids.unsqueeze(1).expand(-1 , self.num_choices , -1).contiguous() a__ : str = input_mask.unsqueeze(1).expand(-1 , self.num_choices , -1).contiguous() a__ : Optional[int] = model( lowercase , attention_mask=lowercase , token_type_ids=lowercase , labels=lowercase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices)) def __lowercase ( self) -> Union[str, Any]: '''simple docstring''' a__ : List[Any] = self.prepare_config_and_inputs() ( ( a__ ) , ( a__ ) , ( a__ ) , ( a__ ) , ( a__ ) , ( a__ ) , ( a__ ) , ) : str = config_and_inputs a__ : Any = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class A__ ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ): """simple docstring""" __A : Any = ( ( NystromformerModel, NystromformerForMaskedLM, NystromformerForMultipleChoice, NystromformerForQuestionAnswering, NystromformerForSequenceClassification, NystromformerForTokenClassification, ) if is_torch_available() else () ) __A : str = ( { '''feature-extraction''': NystromformerModel, '''fill-mask''': NystromformerForMaskedLM, '''question-answering''': NystromformerForQuestionAnswering, '''text-classification''': NystromformerForSequenceClassification, '''token-classification''': NystromformerForTokenClassification, '''zero-shot''': NystromformerForSequenceClassification, } if is_torch_available() else {} ) __A : Optional[Any] = False __A : Tuple = False def __lowercase ( self) -> Optional[Any]: '''simple docstring''' a__ : int = NystromformerModelTester(self) a__ : Any = ConfigTester(self , config_class=lowercase , hidden_size=37) def __lowercase ( self) -> Any: '''simple docstring''' self.config_tester.run_common_tests() def __lowercase ( self) -> int: '''simple docstring''' a__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase) def __lowercase ( self) -> Tuple: '''simple docstring''' a__ : Tuple = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: a__ : Optional[Any] = type self.model_tester.create_and_check_model(*lowercase) def __lowercase ( self) -> Tuple: '''simple docstring''' a__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*lowercase) def __lowercase ( self) -> Any: '''simple docstring''' a__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*lowercase) def __lowercase ( self) -> Any: '''simple docstring''' a__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*lowercase) def __lowercase ( self) -> Union[str, Any]: '''simple docstring''' a__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*lowercase) def __lowercase ( self) -> int: '''simple docstring''' a__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*lowercase) @slow def __lowercase ( self) -> Optional[int]: '''simple docstring''' for model_name in NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a__ : int = NystromformerModel.from_pretrained(lowercase) self.assertIsNotNone(lowercase) @require_torch class A__ ( unittest.TestCase ): """simple docstring""" @slow def __lowercase ( self) -> Optional[Any]: '''simple docstring''' a__ : List[str] = NystromformerModel.from_pretrained('uw-madison/nystromformer-512') a__ : Tuple = torch.tensor([[0, 1, 2, 3, 4, 5]]) with torch.no_grad(): a__ : List[Any] = model(lowercase)[0] a__ : str = torch.Size((1, 6, 768)) self.assertEqual(output.shape , lowercase) a__ : str = torch.tensor( [[[-0.45_32, -0.09_36, 0.51_37], [-0.26_76, 0.06_28, 0.61_86], [-0.36_29, -0.17_26, 0.47_16]]]) self.assertTrue(torch.allclose(output[:, :3, :3] , lowercase , atol=1e-4)) @slow def __lowercase ( self) -> Optional[int]: '''simple docstring''' a__ : Any = 'the [MASK] of Belgium is Brussels' a__ : List[str] = AutoTokenizer.from_pretrained('uw-madison/nystromformer-512') a__ : Optional[int] = NystromformerForMaskedLM.from_pretrained('uw-madison/nystromformer-512') a__ : List[Any] = tokenizer(lowercase , return_tensors='pt') with torch.no_grad(): a__ : Union[str, Any] = model(encoding.input_ids).logits a__ : str = token_logits[:, 2, :].argmax(-1)[0] self.assertEqual(tokenizer.decode(lowercase) , 'capital')
225
0