code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
"""simple docstring""" import unittest from transformers import is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision, slow, torch_device if is_torch_available(): import torch from transformers import AutoModelForImageClassification if is_vision_available(): from transformers import AutoImageProcessor @require_torch @require_vision class __A ( unittest.TestCase ): """simple docstring""" @slow def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a =AutoImageProcessor.from_pretrained('''microsoft/dit-base-finetuned-rvlcdip''' ) a =AutoModelForImageClassification.from_pretrained('''microsoft/dit-base-finetuned-rvlcdip''' ) model.to(__A ) from datasets import load_dataset a =load_dataset('''nielsr/rvlcdip-demo''' ) a =dataset['''train'''][0]['''image'''].convert('''RGB''' ) a =image_processor(__A , return_tensors='''pt''' ).to(__A ) # forward pass with torch.no_grad(): a =model(**__A ) a =outputs.logits a =torch.Size((1, 16) ) self.assertEqual(logits.shape , __A ) a =torch.tensor( [-0.4_158, -0.4_092, -0.4_347] , device=__A , dtype=torch.float , ) self.assertTrue(torch.allclose(logits[0, :3] , __A , atol=1E-4 ) )
81
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowercase_ = { "configuration_roformer": ["ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "RoFormerConfig", "RoFormerOnnxConfig"], "tokenization_roformer": ["RoFormerTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["RoFormerTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "RoFormerForCausalLM", "RoFormerForMaskedLM", "RoFormerForMultipleChoice", "RoFormerForQuestionAnswering", "RoFormerForSequenceClassification", "RoFormerForTokenClassification", "RoFormerLayer", "RoFormerModel", "RoFormerPreTrainedModel", "load_tf_weights_in_roformer", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TFRoFormerForCausalLM", "TFRoFormerForMaskedLM", "TFRoFormerForMultipleChoice", "TFRoFormerForQuestionAnswering", "TFRoFormerForSequenceClassification", "TFRoFormerForTokenClassification", "TFRoFormerLayer", "TFRoFormerModel", "TFRoFormerPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "FlaxRoFormerForMaskedLM", "FlaxRoFormerForMultipleChoice", "FlaxRoFormerForQuestionAnswering", "FlaxRoFormerForSequenceClassification", "FlaxRoFormerForTokenClassification", "FlaxRoFormerModel", "FlaxRoFormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_roformer import ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, RoFormerConfig, RoFormerOnnxConfig from .tokenization_roformer import RoFormerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roformer_fast import RoFormerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roformer import ( ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, RoFormerForCausalLM, RoFormerForMaskedLM, RoFormerForMultipleChoice, RoFormerForQuestionAnswering, RoFormerForSequenceClassification, RoFormerForTokenClassification, RoFormerLayer, RoFormerModel, RoFormerPreTrainedModel, load_tf_weights_in_roformer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roformer import ( TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerLayer, TFRoFormerModel, TFRoFormerPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roformer import ( FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, FlaxRoFormerPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
45
0
import comet # From: unbabel-comet import torch import datasets A__ = datasets.logging.get_logger(__name__) A__ = """\ @inproceedings{rei-EtAl:2020:WMT, author = {Rei, Ricardo and Stewart, Craig and Farinha, Ana C and Lavie, Alon}, title = {Unbabel's Participation in the WMT20 Metrics Shared Task}, booktitle = {Proceedings of the Fifth Conference on Machine Translation}, month = {November}, year = {2020}, address = {Online}, publisher = {Association for Computational Linguistics}, pages = {909--918}, } @inproceedings{rei-etal-2020-comet, title = \"{COMET}: A Neural Framework for {MT} Evaluation\", author = \"Rei, Ricardo and Stewart, Craig and Farinha, Ana C and Lavie, Alon\", booktitle = \"Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP)\", month = nov, year = \"2020\", address = \"Online\", publisher = \"Association for Computational Linguistics\", url = \"https://www.aclweb.org/anthology/2020.emnlp-main.213\", pages = \"2685--2702\", } """ A__ = """\ Crosslingual Optimized Metric for Evaluation of Translation (COMET) is an open-source framework used to train Machine Translation metrics that achieve high levels of correlation with different types of human judgments (HTER, DA's or MQM). With the release of the framework the authors also released fully trained models that were used to compete in the WMT20 Metrics Shared Task achieving SOTA in that years competition. See the [README.md] file at https://unbabel.github.io/COMET/html/models.html for more information. """ A__ = """ COMET score. Args: `sources` (list of str): Source sentences `predictions` (list of str): candidate translations `references` (list of str): reference translations `cuda` (bool): If set to True, runs COMET using GPU `show_progress` (bool): Shows progress `model`: COMET model to be used. Will default to `wmt-large-da-estimator-1719` if None. Returns: `samples`: List of dictionaries with `src`, `mt`, `ref` and `score`. `scores`: List of scores. Examples: >>> comet_metric = datasets.load_metric('comet') >>> # comet_metric = load_metric('comet', 'wmt20-comet-da') # you can also choose which model to use >>> source = [\"Dem Feuer konnte Einhalt geboten werden\", \"Schulen und Kindergärten wurden eröffnet.\"] >>> hypothesis = [\"The fire could be stopped\", \"Schools and kindergartens were open\"] >>> reference = [\"They were able to control the fire.\", \"Schools and kindergartens opened\"] >>> results = comet_metric.compute(predictions=hypothesis, references=reference, sources=source) >>> print([round(v, 2) for v in results[\"scores\"]]) [0.19, 0.92] """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __lowerCAmelCase ( datasets.Metric ): def snake_case ( self ): """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage="""https://unbabel.github.io/COMET/html/index.html""" , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """sources""": datasets.Value("""string""" , id="""sequence""" ), """predictions""": datasets.Value("""string""" , id="""sequence""" ), """references""": datasets.Value("""string""" , id="""sequence""" ), } ) , codebase_urls=["""https://github.com/Unbabel/COMET"""] , reference_urls=[ """https://github.com/Unbabel/COMET""", """https://www.aclweb.org/anthology/2020.emnlp-main.213/""", """http://www.statmt.org/wmt20/pdf/2020.wmt-1.101.pdf6""", ] , ) def snake_case ( self , _snake_case ): """simple docstring""" if self.config_name == "default": _lowerCAmelCase = comet.load_from_checkpoint(comet.download_model("""wmt20-comet-da""" ) ) else: _lowerCAmelCase = comet.load_from_checkpoint(comet.download_model(self.config_name ) ) def snake_case ( self , _snake_case , _snake_case , _snake_case , _snake_case=None , _snake_case=False ): """simple docstring""" if gpus is None: _lowerCAmelCase = 1 if torch.cuda.is_available() else 0 _lowerCAmelCase = {"""src""": sources, """mt""": predictions, """ref""": references} _lowerCAmelCase = [dict(zip(_snake_case , _snake_case ) ) for t in zip(*data.values() )] _lowerCAmelCase , _lowerCAmelCase = self.scorer.predict(_snake_case , gpus=_snake_case , progress_bar=_snake_case ) return {"mean_score": mean_score, "scores": scores}
82
"""simple docstring""" import warnings from ..trainer import Trainer from ..utils import logging lowercase_ = logging.get_logger(__name__) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a=None , **_a ): warnings.warn( '''`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` ''' '''instead.''' , _a , ) super().__init__(args=_a , **_a )
45
0
'''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() snake_case_ : Optional[int] = logging.get_logger(__name__) def A__ ( UpperCAmelCase_ ): print('Loading config file...' ) def flatten_yaml_as_dict(UpperCAmelCase_ , UpperCAmelCase_="" , UpperCAmelCase_="." ): _UpperCamelCase : int = [] for k, v in d.items(): _UpperCamelCase : Optional[int] = 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_ ) _UpperCamelCase : Tuple = argparse.Namespace() with open(UpperCAmelCase_ , 'r' ) as yaml_file: try: _UpperCamelCase : int = yaml.load(UpperCAmelCase_ , Loader=yaml.FullLoader ) _UpperCamelCase : Optional[int] = 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__ ( UpperCAmelCase_ , UpperCAmelCase_ ): _UpperCamelCase : Dict = MobileViTVaConfig() _UpperCamelCase : Union[str, Any] = False # dataset if task_name.startswith('imagenet1k_' ): _UpperCamelCase : Dict = 1_0_0_0 if int(task_name.strip().split('_' )[-1] ) == 3_8_4: _UpperCamelCase : List[str] = 3_8_4 else: _UpperCamelCase : Union[str, Any] = 2_5_6 _UpperCamelCase : Union[str, Any] = 'imagenet-1k-id2label.json' elif task_name.startswith('imagenet21k_to_1k_' ): _UpperCamelCase : Optional[int] = 2_1_0_0_0 if int(task_name.strip().split('_' )[-1] ) == 3_8_4: _UpperCamelCase : Tuple = 3_8_4 else: _UpperCamelCase : Dict = 2_5_6 _UpperCamelCase : Any = 'imagenet-22k-id2label.json' elif task_name.startswith('ade20k_' ): _UpperCamelCase : Optional[Any] = 1_5_1 _UpperCamelCase : Any = 5_1_2 _UpperCamelCase : Optional[Any] = 'ade20k-id2label.json' _UpperCamelCase : Optional[int] = True elif task_name.startswith('voc_' ): _UpperCamelCase : Any = 2_1 _UpperCamelCase : List[str] = 5_1_2 _UpperCamelCase : Union[str, Any] = 'pascal-voc-id2label.json' _UpperCamelCase : Optional[Any] = True # orig_config _UpperCamelCase : Dict = load_orig_config_file(UpperCAmelCase_ ) assert getattr(UpperCAmelCase_ , 'model.classification.name' , -1 ) == "mobilevit_v2", "Invalid model" _UpperCamelCase : Dict = 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" _UpperCamelCase : Tuple = getattr(UpperCAmelCase_ , 'model.classification.activation.name' , 'swish' ) # config.image_size == getattr(orig_config, 'sampler.bs.crop_size_width', 256) if is_segmentation_model: _UpperCamelCase : List[str] = getattr(UpperCAmelCase_ , 'model.segmentation.output_stride' , 1_6 ) if "_deeplabv3" in task_name: _UpperCamelCase : Optional[Any] = getattr(UpperCAmelCase_ , 'model.segmentation.deeplabv3.aspp_rates' , [1_2, 2_4, 3_6] ) _UpperCamelCase : str = getattr(UpperCAmelCase_ , 'model.segmentation.deeplabv3.aspp_out_channels' , 5_1_2 ) _UpperCamelCase : List[str] = getattr(UpperCAmelCase_ , 'model.segmentation.deeplabv3.aspp_dropout' , 0.1 ) # id2label _UpperCamelCase : Dict = 'huggingface/label-files' _UpperCamelCase : Any = json.load(open(hf_hub_download(UpperCAmelCase_ , UpperCAmelCase_ , repo_type='dataset' ) , 'r' ) ) _UpperCamelCase : Tuple = {int(UpperCAmelCase_ ): v for k, v in idalabel.items()} _UpperCamelCase : Optional[Any] = idalabel _UpperCamelCase : int = {v: k for k, v in idalabel.items()} return config def A__ ( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ): _UpperCamelCase : List[Any] = dct.pop(UpperCAmelCase_ ) _UpperCamelCase : Union[str, Any] = val def A__ ( UpperCAmelCase_ , UpperCAmelCase_=False ): if base_model: _UpperCamelCase : Optional[int] = '' else: _UpperCamelCase : Union[str, Any] = 'mobilevitv2.' _UpperCamelCase : int = [] for k in state_dict.keys(): if k[:8] == "encoder.": _UpperCamelCase : int = k[8:] else: _UpperCamelCase : Any = k if ".block." in k: _UpperCamelCase : Optional[int] = k_new.replace('.block.' , '.' ) if ".conv." in k: _UpperCamelCase : Union[str, Any] = k_new.replace('.conv.' , '.convolution.' ) if ".norm." in k: _UpperCamelCase : List[Any] = k_new.replace('.norm.' , '.normalization.' ) if "conv_1." in k: _UpperCamelCase : Union[str, Any] = k_new.replace('conv_1.' , f'{model_prefix}conv_stem.' ) for i in [1, 2]: if f'layer_{i}.' in k: _UpperCamelCase : Optional[int] = k_new.replace(f'layer_{i}.' , f'{model_prefix}encoder.layer.{i-1}.layer.' ) if ".exp_1x1." in k: _UpperCamelCase : Dict = k_new.replace('.exp_1x1.' , '.expand_1x1.' ) if ".red_1x1." in k: _UpperCamelCase : List[str] = k_new.replace('.red_1x1.' , '.reduce_1x1.' ) for i in [3, 4, 5]: if f'layer_{i}.0.' in k: _UpperCamelCase : Tuple = 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: _UpperCamelCase : str = 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: _UpperCamelCase : Optional[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: _UpperCamelCase : List[Any] = [0, 1] elif i == 4: _UpperCamelCase : Any = [0, 1, 2, 3] elif i == 5: _UpperCamelCase : List[Any] = [0, 1, 2] for j in j_in: if f'layer_{i}.1.global_rep.{j}.' in k: _UpperCamelCase : Tuple = 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: _UpperCamelCase : Tuple = 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: _UpperCamelCase : 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: _UpperCamelCase : str = k_new.replace('pre_norm_attn.0.' , 'layernorm_before.' ) if "pre_norm_attn.1." in k: _UpperCamelCase : Optional[int] = k_new.replace('pre_norm_attn.1.' , 'attention.' ) if "pre_norm_ffn.0." in k: _UpperCamelCase : Tuple = k_new.replace('pre_norm_ffn.0.' , 'layernorm_after.' ) if "pre_norm_ffn.1." in k: _UpperCamelCase : Any = k_new.replace('pre_norm_ffn.1.' , 'ffn.conv1.' ) if "pre_norm_ffn.3." in k: _UpperCamelCase : Any = k_new.replace('pre_norm_ffn.3.' , 'ffn.conv2.' ) if "classifier.1." in k: _UpperCamelCase : Optional[int] = k_new.replace('classifier.1.' , 'classifier.' ) if "seg_head." in k: _UpperCamelCase : str = k_new.replace('seg_head.' , 'segmentation_head.' ) if ".aspp_layer." in k: _UpperCamelCase : Dict = k_new.replace('.aspp_layer.' , '.' ) if ".aspp_pool." in k: _UpperCamelCase : Union[str, Any] = k_new.replace('.aspp_pool.' , '.' ) rename_keys.append((k, k_new) ) return rename_keys def A__ ( UpperCAmelCase_ ): _UpperCamelCase : List[str] = [] 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__ ( ): _UpperCamelCase : Any = 'http://images.cocodataset.org/val2017/000000039769.jpg' # url = "https://cdn.britannica.com/86/141086-050-9D7C75EE/Gulfstream-G450-business-jet-passengers.jpg" _UpperCamelCase : str = Image.open(requests.get(UpperCAmelCase_ , stream=UpperCAmelCase_ ).raw ) return im @torch.no_grad() def A__ ( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ): _UpperCamelCase : Union[str, Any] = get_mobilevitva_config(UpperCAmelCase_ , UpperCAmelCase_ ) # load original state_dict _UpperCamelCase : Union[str, Any] = torch.load(UpperCAmelCase_ , map_location='cpu' ) # load huggingface model if task_name.startswith('ade20k_' ) or task_name.startswith('voc_' ): _UpperCamelCase : Optional[int] = MobileViTVaForSemanticSegmentation(UpperCAmelCase_ ).eval() _UpperCamelCase : Optional[int] = False else: _UpperCamelCase : Union[str, Any] = MobileViTVaForImageClassification(UpperCAmelCase_ ).eval() _UpperCamelCase : str = False # remove and rename some keys of load the original model _UpperCamelCase : Tuple = checkpoint remove_unused_keys(UpperCAmelCase_ ) _UpperCamelCase : Tuple = 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 _UpperCamelCase : Union[str, Any] = MobileViTImageProcessor(crop_size=config.image_size , size=config.image_size + 3_2 ) _UpperCamelCase : Any = image_processor(images=prepare_img() , return_tensors='pt' ) _UpperCamelCase : Optional[Any] = model(**UpperCAmelCase_ ) # verify classification model if task_name.startswith('imagenet' ): _UpperCamelCase : List[str] = outputs.logits _UpperCamelCase : List[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 _UpperCamelCase : List[str] = 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__": snake_case_ : Any = 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.' ) snake_case_ : int = parser.parse_args() convert_mobilevitva_checkpoint( args.task, args.orig_checkpoint_path, args.orig_config_path, args.pytorch_dump_folder_path )
83
"""simple docstring""" import math def lowercase ( lowerCAmelCase__ : list , lowerCAmelCase__ : int ) -> int: __a = len(lowerCAmelCase__ ) __a = int(math.floor(math.sqrt(lowerCAmelCase__ ) ) ) __a = 0 while arr[min(lowerCAmelCase__ , lowerCAmelCase__ ) - 1] < x: __a = step step += int(math.floor(math.sqrt(lowerCAmelCase__ ) ) ) if prev >= n: return -1 while arr[prev] < x: __a = prev + 1 if prev == min(lowerCAmelCase__ , lowerCAmelCase__ ): return -1 if arr[prev] == x: return prev return -1 if __name__ == "__main__": lowercase_ = input("Enter numbers separated by a comma:\n").strip() lowercase_ = [int(item) for item in user_input.split(",")] lowercase_ = int(input("Enter the number to be searched:\n")) lowercase_ = jump_search(arr, x) if res == -1: print("Number not found!") else: print(F'''Number {x} is at index {res}''')
45
0
"""simple docstring""" class _SCREAMING_SNAKE_CASE : def __init__( self ) -> int: lowerCAmelCase_ :List[str] = """""" lowerCAmelCase_ :List[Any] = """""" lowerCAmelCase_ :Union[str, Any] = [] def __lowerCAmelCase ( self , __A , __A ) -> int: if m == -1: return n + 1 elif n == -1: return m + 1 elif self.dp[m][n] > -1: return self.dp[m][n] else: if self.worda[m] == self.worda[n]: lowerCAmelCase_ :List[Any] = self.__min_dist_top_down_dp(m - 1 , n - 1 ) else: lowerCAmelCase_ :int = self.__min_dist_top_down_dp(__A , n - 1 ) lowerCAmelCase_ :Dict = self.__min_dist_top_down_dp(m - 1 , __A ) lowerCAmelCase_ :Optional[int] = self.__min_dist_top_down_dp(m - 1 , n - 1 ) lowerCAmelCase_ :Tuple = 1 + min(__A , __A , __A ) return self.dp[m][n] def __lowerCAmelCase ( self , __A , __A ) -> int: lowerCAmelCase_ :List[str] = worda lowerCAmelCase_ :int = worda lowerCAmelCase_ :int = [[-1 for _ in range(len(__A ) )] for _ in range(len(__A ) )] return self.__min_dist_top_down_dp(len(__A ) - 1 , len(__A ) - 1 ) def __lowerCAmelCase ( self , __A , __A ) -> int: lowerCAmelCase_ :Optional[Any] = worda lowerCAmelCase_ :Dict = worda lowerCAmelCase_ :str = len(__A ) lowerCAmelCase_ :Union[str, Any] = len(__A ) lowerCAmelCase_ :List[str] = [[0 for _ in range(n + 1 )] for _ in range(m + 1 )] for i in range(m + 1 ): for j in range(n + 1 ): if i == 0: # first string is empty lowerCAmelCase_ :int = j elif j == 0: # second string is empty lowerCAmelCase_ :int = i elif worda[i - 1] == worda[j - 1]: # last characters are equal lowerCAmelCase_ :Union[str, Any] = self.dp[i - 1][j - 1] else: lowerCAmelCase_ :Union[str, Any] = self.dp[i][j - 1] lowerCAmelCase_ :Tuple = self.dp[i - 1][j] lowerCAmelCase_ :Dict = self.dp[i - 1][j - 1] lowerCAmelCase_ :Tuple = 1 + min(__A , __A , __A ) return self.dp[m][n] if __name__ == "__main__": __UpperCAmelCase = EditDistance() print('****************** Testing Edit Distance DP Algorithm ******************') print() __UpperCAmelCase = input('Enter the first string: ').strip() __UpperCAmelCase = input('Enter the second string: ').strip() print() print(F"""The minimum edit distance is: {solver.min_dist_top_down(Sa, Sa)}""") print(F"""The minimum edit distance is: {solver.min_dist_bottom_up(Sa, Sa)}""") print() print('*************** End of Testing Edit Distance DP Algorithm ***************')
84
"""simple docstring""" lowercase_ = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] lowercase_ = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] lowercase_ = { 0: "Sunday", 1: "Monday", 2: "Tuesday", 3: "Wednesday", 4: "Thursday", 5: "Friday", 6: "Saturday", } def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : int , lowerCAmelCase__ : int ) -> str: assert len(str(lowerCAmelCase__ ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 12, "month should be between 1 to 12" assert 1 <= day <= 31, "day should be between 1 to 31" # Doomsday algorithm: __a = year // 100 __a = (5 * (century % 4) + 2) % 7 __a = year % 100 __a = centurian % 12 __a = ( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 __a = ( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 400) == 0) else DOOMSDAY_LEAP[month - 1] ) __a = (dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
45
0
'''simple docstring''' import os import time from dataclasses import dataclass, field from enum import Enum from typing import Dict, List, Optional, Union import torch from filelock import FileLock from torch.utils.data import Dataset from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging from ..processors.squad import SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features _SCREAMING_SNAKE_CASE : Tuple = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE : List[str] = list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys()) _SCREAMING_SNAKE_CASE : Tuple = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class _snake_case : lowerCAmelCase_ : str = field( default=lowercase_ , metadata={"help": "Model type selected in the list: " + ", ".join(lowercase_ )} ) lowerCAmelCase_ : str = field( default=lowercase_ , metadata={"help": "The input data dir. Should contain the .json files for the SQuAD task."} ) lowerCAmelCase_ : int = field( default=128 , metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) lowerCAmelCase_ : int = field( default=128 , metadata={"help": "When splitting up a long document into chunks, how much stride to take between chunks."} , ) lowerCAmelCase_ : int = field( default=64 , metadata={ "help": ( "The maximum number of tokens for the question. Questions longer than this will " "be truncated to this length." ) } , ) lowerCAmelCase_ : int = field( default=30 , metadata={ "help": ( "The maximum length of an answer that can be generated. This is needed because the start " "and end predictions are not conditioned on one another." ) } , ) lowerCAmelCase_ : bool = field( default=lowercase_ , metadata={"help": "Overwrite the cached training and evaluation sets"} ) lowerCAmelCase_ : bool = field( default=lowercase_ , metadata={"help": "If true, the SQuAD examples contain some that do not have an answer."} ) lowerCAmelCase_ : float = field( default=0.0 , metadata={"help": "If null_score - best_non_null is greater than the threshold predict null."} ) lowerCAmelCase_ : int = field( default=20 , metadata={"help": "If null_score - best_non_null is greater than the threshold predict null."} ) lowerCAmelCase_ : int = field( default=0 , metadata={ "help": ( "language id of input for language-specific xlm models (see" " tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)" ) } , ) lowerCAmelCase_ : int = field(default=1 , metadata={"help": "multiple threads for converting example to features"} ) class _snake_case ( lowercase_ ): lowerCAmelCase_ : int = "train" lowerCAmelCase_ : Tuple = "dev" class _snake_case ( lowercase_ ): lowerCAmelCase_ : SquadDataTrainingArguments lowerCAmelCase_ : List[SquadFeatures] lowerCAmelCase_ : Split lowerCAmelCase_ : bool def __init__( self , a__ , a__ , a__ = None , a__ = Split.train , a__ = False , a__ = None , a__ = "pt" , ) -> Any: '''simple docstring''' snake_case_ = args snake_case_ = is_language_sensitive snake_case_ = SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor() if isinstance(a__ , a__ ): try: snake_case_ = Split[mode] except KeyError: raise KeyError("mode is not a valid split name" ) snake_case_ = mode # Load data features from cache or dataset file snake_case_ = "v2" if args.version_2_with_negative else "v1" snake_case_ = os.path.join( cache_dir if cache_dir is not None else args.data_dir , F'cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}' , ) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. snake_case_ = cached_features_file + ".lock" with FileLock(a__ ): if os.path.exists(a__ ) and not args.overwrite_cache: snake_case_ = time.time() snake_case_ = torch.load(a__ ) # Legacy cache files have only features, while new cache files # will have dataset and examples also. snake_case_ = self.old_features["features"] snake_case_ = self.old_features.get("dataset" , a__ ) snake_case_ = self.old_features.get("examples" , a__ ) logger.info( F'Loading features from cached file {cached_features_file} [took %.3f s]' , time.time() - start ) if self.dataset is None or self.examples is None: logger.warning( F'Deleting cached file {cached_features_file} will allow dataset and examples to be cached in' " future run" ) else: if mode == Split.dev: snake_case_ = self.processor.get_dev_examples(args.data_dir ) else: snake_case_ = self.processor.get_train_examples(args.data_dir ) snake_case_ , snake_case_ = squad_convert_examples_to_features( examples=self.examples , tokenizer=a__ , max_seq_length=args.max_seq_length , doc_stride=args.doc_stride , max_query_length=args.max_query_length , is_training=mode == Split.train , threads=args.threads , return_dataset=a__ , ) snake_case_ = time.time() torch.save( {"features": self.features, "dataset": self.dataset, "examples": self.examples} , a__ , ) # ^ This seems to take a lot of time so I want to investigate why and how we can improve. logger.info( F'Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]' ) def __len__( self ) -> str: '''simple docstring''' return len(self.features ) def __getitem__( self , a__ ) -> Dict[str, torch.Tensor]: '''simple docstring''' snake_case_ = self.features[i] snake_case_ = torch.tensor(feature.input_ids , dtype=torch.long ) snake_case_ = torch.tensor(feature.attention_mask , dtype=torch.long ) snake_case_ = torch.tensor(feature.token_type_ids , dtype=torch.long ) snake_case_ = torch.tensor(feature.cls_index , dtype=torch.long ) snake_case_ = torch.tensor(feature.p_mask , dtype=torch.float ) snake_case_ = torch.tensor(feature.is_impossible , dtype=torch.float ) snake_case_ = { "input_ids": input_ids, "attention_mask": attention_mask, "token_type_ids": token_type_ids, } if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]: del inputs["token_type_ids"] if self.args.model_type in ["xlnet", "xlm"]: inputs.update({"cls_index": cls_index, "p_mask": p_mask} ) if self.args.version_2_with_negative: inputs.update({"is_impossible": is_impossible} ) if self.is_language_sensitive: inputs.update({"langs": (torch.ones(input_ids.shape , dtype=torch.intaa ) * self.args.lang_id)} ) if self.mode == Split.train: snake_case_ = torch.tensor(feature.start_position , dtype=torch.long ) snake_case_ = torch.tensor(feature.end_position , dtype=torch.long ) inputs.update({"start_positions": start_positions, "end_positions": end_positions} ) return inputs
85
"""simple docstring""" def lowercase ( lowerCAmelCase__ : list ) -> bool: if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise ValueError('''Input series is not valid, valid series - [2, 4, 6]''' ) if len(lowerCAmelCase__ ) == 0: raise ValueError('''Input list must be a non empty list''' ) if len(lowerCAmelCase__ ) == 1: return True __a = series[1] - series[0] for index in range(len(lowerCAmelCase__ ) - 1 ): if series[index + 1] - series[index] != common_diff: return False return True def lowercase ( lowerCAmelCase__ : list ) -> float: if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise ValueError('''Input series is not valid, valid series - [2, 4, 6]''' ) if len(lowerCAmelCase__ ) == 0: raise ValueError('''Input list must be a non empty list''' ) __a = 0 for val in series: answer += val return answer / len(lowerCAmelCase__ ) if __name__ == "__main__": import doctest doctest.testmod()
45
0
"""simple docstring""" def __lowerCAmelCase (_UpperCamelCase = 1000 ): __lowerCAmelCase , __lowerCAmelCase : Optional[int] = 1, 1 __lowerCAmelCase : int = 2 while True: __lowerCAmelCase : Optional[int] = 0 __lowerCAmelCase : List[str] = fa + fa __lowerCAmelCase , __lowerCAmelCase : Optional[Any] = fa, f index += 1 for _ in str(_UpperCamelCase ): i += 1 if i == n: break return index if __name__ == "__main__": print(solution(int(str(input()).strip())))
86
"""simple docstring""" from argparse import ArgumentParser, Namespace from ..utils import logging from . import BaseTransformersCLICommand def lowercase ( lowerCAmelCase__ : Namespace ) -> Tuple: return ConvertCommand( args.model_type , args.tf_checkpoint , args.pytorch_dump_output , args.config , args.finetuning_task_name ) lowercase_ = "\ntransformers can only be used from the commandline to convert TensorFlow models in PyTorch, In that case, it requires\nTensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installation instructions.\n" class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' @staticmethod def __UpperCAmelCase ( _a ): __a = parser.add_parser( '''convert''' , help='''CLI tool to run convert model from original author checkpoints to Transformers PyTorch checkpoints.''' , ) train_parser.add_argument('''--model_type''' , type=_a , required=_a , help='''Model\'s type.''' ) train_parser.add_argument( '''--tf_checkpoint''' , type=_a , required=_a , help='''TensorFlow checkpoint path or folder.''' ) train_parser.add_argument( '''--pytorch_dump_output''' , type=_a , required=_a , help='''Path to the PyTorch saved model output.''' ) train_parser.add_argument('''--config''' , type=_a , default='''''' , help='''Configuration file path or folder.''' ) train_parser.add_argument( '''--finetuning_task_name''' , type=_a , default=_a , help='''Optional fine-tuning task name if the TF model was a finetuned model.''' , ) train_parser.set_defaults(func=_a ) def __init__( self , _a , _a , _a , _a , _a , *_a , ): __a = logging.get_logger('''transformers-cli/converting''' ) self._logger.info(f'''Loading model {model_type}''' ) __a = model_type __a = tf_checkpoint __a = pytorch_dump_output __a = config __a = finetuning_task_name def __UpperCAmelCase ( self ): if self._model_type == "albert": try: from ..models.albert.convert_albert_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "bert": try: from ..models.bert.convert_bert_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "funnel": try: from ..models.funnel.convert_funnel_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "t5": try: from ..models.ta.convert_ta_original_tf_checkpoint_to_pytorch import convert_tf_checkpoint_to_pytorch except ImportError: raise ImportError(_a ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "gpt": from ..models.openai.convert_openai_original_tf_checkpoint_to_pytorch import ( convert_openai_checkpoint_to_pytorch, ) convert_openai_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "transfo_xl": try: from ..models.transfo_xl.convert_transfo_xl_original_tf_checkpoint_to_pytorch import ( convert_transfo_xl_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) if "ckpt" in self._tf_checkpoint.lower(): __a = self._tf_checkpoint __a = '''''' else: __a = self._tf_checkpoint __a = '''''' convert_transfo_xl_checkpoint_to_pytorch( _a , self._config , self._pytorch_dump_output , _a ) elif self._model_type == "gpt2": try: from ..models.gpta.convert_gpta_original_tf_checkpoint_to_pytorch import ( convert_gpta_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_gpta_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "xlnet": try: from ..models.xlnet.convert_xlnet_original_tf_checkpoint_to_pytorch import ( convert_xlnet_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_xlnet_checkpoint_to_pytorch( self._tf_checkpoint , self._config , self._pytorch_dump_output , self._finetuning_task_name ) elif self._model_type == "xlm": from ..models.xlm.convert_xlm_original_pytorch_checkpoint_to_pytorch import ( convert_xlm_checkpoint_to_pytorch, ) convert_xlm_checkpoint_to_pytorch(self._tf_checkpoint , self._pytorch_dump_output ) elif self._model_type == "lxmert": from ..models.lxmert.convert_lxmert_original_tf_checkpoint_to_pytorch import ( convert_lxmert_checkpoint_to_pytorch, ) convert_lxmert_checkpoint_to_pytorch(self._tf_checkpoint , self._pytorch_dump_output ) elif self._model_type == "rembert": from ..models.rembert.convert_rembert_tf_checkpoint_to_pytorch import ( convert_rembert_tf_checkpoint_to_pytorch, ) convert_rembert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) else: raise ValueError( '''--model_type should be selected in the list [bert, gpt, gpt2, t5, transfo_xl, xlnet, xlm, lxmert]''' )
45
0
from typing import List import jiwer import jiwer.transforms as tr from packaging import version import datasets from datasets.config import PY_VERSION if PY_VERSION < version.parse('''3.8'''): import importlib_metadata else: import importlib.metadata as importlib_metadata UpperCamelCase = '''''' if version.parse(importlib_metadata.version('''jiwer''')) < version.parse('''2.3.0'''): class snake_case_ ( tr.AbstractTransform ): def __init__( self : int , lowercase_ : str = " " ) -> Optional[Any]: lowercase__ : Optional[int] = sentence_delimiter def __UpperCamelCase ( self : Any , lowercase_ : str ) -> List[str]: return list(lowercase_ ) def __UpperCamelCase ( self : Optional[int] , lowercase_ : List[str] ) -> Union[str, Any]: lowercase__ : str = [] for sent_idx, sentence in enumerate(lowercase_ ): chars.extend(self.process_string(lowercase_ ) ) if self.sentence_delimiter is not None and self.sentence_delimiter != "" and sent_idx < len(lowercase_ ) - 1: chars.append(self.sentence_delimiter ) return chars UpperCamelCase = tr.Compose( [tr.RemoveMultipleSpaces(), tr.Strip(), SentencesToListOfCharacters(SENTENCE_DELIMITER)] ) else: UpperCamelCase = tr.Compose( [ tr.RemoveMultipleSpaces(), tr.Strip(), tr.ReduceToSingleSentence(SENTENCE_DELIMITER), tr.ReduceToListOfListOfChars(), ] ) UpperCamelCase = '''\ @inproceedings{inproceedings, author = {Morris, Andrew and Maier, Viktoria and Green, Phil}, year = {2004}, month = {01}, pages = {}, title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.} } ''' UpperCamelCase = '''\ Character error rate (CER) is a common metric of the performance of an automatic speech recognition system. CER is similar to Word Error Rate (WER), but operates on character instead of word. Please refer to docs of WER for further information. Character error rate can be computed as: CER = (S + D + I) / N = (S + D + I) / (S + D + C) where S is the number of substitutions, D is the number of deletions, I is the number of insertions, C is the number of correct characters, N is the number of characters in the reference (N=S+D+C). CER\'s output is not always a number between 0 and 1, in particular when there is a high number of insertions. This value is often associated to the percentage of characters that were incorrectly predicted. The lower the value, the better the performance of the ASR system with a CER of 0 being a perfect score. ''' UpperCamelCase = ''' Computes CER score of transcribed segments against references. Args: references: list of references for each speech input. predictions: list of transcribtions to score. concatenate_texts: Whether or not to concatenate sentences before evaluation, set to True for more accurate result. Returns: (float): the character error rate Examples: >>> predictions = ["this is the prediction", "there is an other sample"] >>> references = ["this is the reference", "there is another one"] >>> cer = datasets.load_metric("cer") >>> cer_score = cer.compute(predictions=predictions, references=references) >>> print(cer_score) 0.34146341463414637 ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,_KWARGS_DESCRIPTION ) class snake_case_ ( datasets.Metric ): def __UpperCamelCase ( self : Tuple ) -> Any: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Value("string" , id="sequence" ), } ) , codebase_urls=["https://github.com/jitsi/jiwer/"] , reference_urls=[ "https://en.wikipedia.org/wiki/Word_error_rate", "https://sites.google.com/site/textdigitisation/qualitymeasures/computingerrorrates", ] , ) def __UpperCamelCase ( self : List[str] , lowercase_ : Any , lowercase_ : List[str] , lowercase_ : Union[str, Any]=False ) -> Union[str, Any]: if concatenate_texts: return jiwer.compute_measures( lowercase_ , lowercase_ , truth_transform=lowercase_ , hypothesis_transform=lowercase_ , )["wer"] lowercase__ : List[str] = 0 lowercase__ : Dict = 0 for prediction, reference in zip(lowercase_ , lowercase_ ): lowercase__ : Union[str, Any] = jiwer.compute_measures( lowercase_ , lowercase_ , truth_transform=lowercase_ , hypothesis_transform=lowercase_ , ) incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"] total += measures["substitutions"] + measures["deletions"] + measures["hits"] return incorrect / total
87
"""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 lowercase_ = logging.get_logger(__name__) lowercase_ = { "microsoft/beit-base-patch16-224-pt22k": ( "https://huggingface.co/microsoft/beit-base-patch16-224-pt22k/resolve/main/config.json" ), # See all BEiT models at https://huggingface.co/models?filter=beit } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : List[str] = 'beit' def __init__( self , _a=8_192 , _a=768 , _a=12 , _a=12 , _a=3_072 , _a="gelu" , _a=0.0 , _a=0.0 , _a=0.02 , _a=1E-12 , _a=224 , _a=16 , _a=3 , _a=False , _a=False , _a=False , _a=False , _a=0.1 , _a=0.1 , _a=True , _a=[3, 5, 7, 11] , _a=[1, 2, 3, 6] , _a=True , _a=0.4 , _a=256 , _a=1 , _a=False , _a=255 , **_a , ): super().__init__(**_a ) __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 = initializer_range __a = layer_norm_eps __a = image_size __a = patch_size __a = num_channels __a = use_mask_token __a = use_absolute_position_embeddings __a = use_relative_position_bias __a = use_shared_relative_position_bias __a = layer_scale_init_value __a = drop_path_rate __a = use_mean_pooling # decode head attributes (semantic segmentation) __a = out_indices __a = pool_scales # auxiliary head attributes (semantic segmentation) __a = use_auxiliary_head __a = auxiliary_loss_weight __a = auxiliary_channels __a = auxiliary_num_convs __a = auxiliary_concat_input __a = semantic_loss_ignore_index class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : List[Any] = version.parse('1.11' ) @property def __UpperCAmelCase ( self ): return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def __UpperCAmelCase ( self ): return 1E-4
45
0
import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bart import BartTokenizer __lowerCAmelCase : Any = logging.get_logger(__name__) __lowerCAmelCase : Dict = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'} # See all BART models at https://huggingface.co/models?filter=bart __lowerCAmelCase : Dict = { 'vocab_file': { 'facebook/bart-base': 'https://huggingface.co/facebook/bart-base/resolve/main/vocab.json', 'facebook/bart-large': 'https://huggingface.co/facebook/bart-large/resolve/main/vocab.json', 'facebook/bart-large-mnli': 'https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json', 'facebook/bart-large-cnn': 'https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json', 'facebook/bart-large-xsum': 'https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json', 'yjernite/bart_eli5': 'https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json', }, 'merges_file': { 'facebook/bart-base': 'https://huggingface.co/facebook/bart-base/resolve/main/merges.txt', 'facebook/bart-large': 'https://huggingface.co/facebook/bart-large/resolve/main/merges.txt', 'facebook/bart-large-mnli': 'https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt', 'facebook/bart-large-cnn': 'https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt', 'facebook/bart-large-xsum': 'https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt', 'yjernite/bart_eli5': 'https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt', }, 'tokenizer_file': { 'facebook/bart-base': 'https://huggingface.co/facebook/bart-base/resolve/main/tokenizer.json', 'facebook/bart-large': 'https://huggingface.co/facebook/bart-large/resolve/main/tokenizer.json', 'facebook/bart-large-mnli': 'https://huggingface.co/facebook/bart-large-mnli/resolve/main/tokenizer.json', 'facebook/bart-large-cnn': 'https://huggingface.co/facebook/bart-large-cnn/resolve/main/tokenizer.json', 'facebook/bart-large-xsum': 'https://huggingface.co/facebook/bart-large-xsum/resolve/main/tokenizer.json', 'yjernite/bart_eli5': 'https://huggingface.co/yjernite/bart_eli5/resolve/main/tokenizer.json', }, } __lowerCAmelCase : str = { 'facebook/bart-base': 1024, 'facebook/bart-large': 1024, 'facebook/bart-large-mnli': 1024, 'facebook/bart-large-cnn': 1024, 'facebook/bart-large-xsum': 1024, 'yjernite/bart_eli5': 1024, } class UpperCAmelCase_ ( _A ): '''simple docstring''' a__ = VOCAB_FILES_NAMES a__ = PRETRAINED_VOCAB_FILES_MAP a__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a__ = ["""input_ids""", """attention_mask"""] a__ = BartTokenizer def __init__( self : Any , UpperCamelCase__ : Union[str, Any]=None , UpperCamelCase__ : Optional[Any]=None , UpperCamelCase__ : List[Any]=None , UpperCamelCase__ : List[Any]="replace" , UpperCamelCase__ : Union[str, Any]="<s>" , UpperCamelCase__ : Optional[Any]="</s>" , UpperCamelCase__ : Optional[int]="</s>" , UpperCamelCase__ : Tuple="<s>" , UpperCamelCase__ : Optional[Any]="<unk>" , UpperCamelCase__ : Any="<pad>" , UpperCamelCase__ : int="<mask>" , UpperCamelCase__ : Any=False , UpperCamelCase__ : Optional[int]=True , **UpperCamelCase__ : str , ) -> Dict: """simple docstring""" super().__init__( UpperCamelCase__ , UpperCamelCase__ , tokenizer_file=UpperCamelCase__ , errors=UpperCamelCase__ , bos_token=UpperCamelCase__ , eos_token=UpperCamelCase__ , sep_token=UpperCamelCase__ , cls_token=UpperCamelCase__ , unk_token=UpperCamelCase__ , pad_token=UpperCamelCase__ , mask_token=UpperCamelCase__ , add_prefix_space=UpperCamelCase__ , trim_offsets=UpperCamelCase__ , **UpperCamelCase__ , ) __magic_name__ = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("""add_prefix_space""" , UpperCamelCase__ ) != add_prefix_space: __magic_name__ = getattr(UpperCamelCase__ , pre_tok_state.pop("""type""" ) ) __magic_name__ = add_prefix_space __magic_name__ = pre_tok_class(**UpperCamelCase__ ) __magic_name__ = add_prefix_space # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__` __magic_name__ = """post_processor""" __magic_name__ = getattr(self.backend_tokenizer , UpperCamelCase__ , UpperCamelCase__ ) if tokenizer_component_instance: __magic_name__ = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: __magic_name__ = tuple(state["""sep"""] ) if "cls" in state: __magic_name__ = tuple(state["""cls"""] ) __magic_name__ = False if state.get("""add_prefix_space""" , UpperCamelCase__ ) != add_prefix_space: __magic_name__ = add_prefix_space __magic_name__ = True if state.get("""trim_offsets""" , UpperCamelCase__ ) != trim_offsets: __magic_name__ = trim_offsets __magic_name__ = True if changes_to_apply: __magic_name__ = getattr(UpperCamelCase__ , state.pop("""type""" ) ) __magic_name__ = component_class(**UpperCamelCase__ ) setattr(self.backend_tokenizer , UpperCamelCase__ , UpperCamelCase__ ) @property def _lowercase ( self : Tuple ) -> str: """simple docstring""" if self._mask_token is None: if self.verbose: logger.error("""Using mask_token, but it is not set yet.""" ) return None return str(self._mask_token ) @mask_token.setter def _lowercase ( self : Dict , UpperCamelCase__ : List[Any] ) -> Dict: """simple docstring""" __magic_name__ = AddedToken(UpperCamelCase__ , lstrip=UpperCamelCase__ , rstrip=UpperCamelCase__ ) if isinstance(UpperCamelCase__ , UpperCamelCase__ ) else value __magic_name__ = value def _lowercase ( self : Tuple , *UpperCamelCase__ : Dict , **UpperCamelCase__ : List[Any] ) -> BatchEncoding: """simple docstring""" __magic_name__ = kwargs.get("""is_split_into_words""" , UpperCamelCase__ ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True ''' """to use it with pretokenized inputs.""" ) return super()._batch_encode_plus(*UpperCamelCase__ , **UpperCamelCase__ ) def _lowercase ( self : List[Any] , *UpperCamelCase__ : Any , **UpperCamelCase__ : Optional[Any] ) -> BatchEncoding: """simple docstring""" __magic_name__ = kwargs.get("""is_split_into_words""" , UpperCamelCase__ ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True ''' """to use it with pretokenized inputs.""" ) return super()._encode_plus(*UpperCamelCase__ , **UpperCamelCase__ ) def _lowercase ( self : List[str] , UpperCamelCase__ : str , UpperCamelCase__ : Optional[str] = None ) -> Tuple[str]: """simple docstring""" __magic_name__ = self._tokenizer.model.save(UpperCamelCase__ , name=UpperCamelCase__ ) return tuple(UpperCamelCase__ ) def _lowercase ( self : str , UpperCamelCase__ : Any , UpperCamelCase__ : int=None ) -> Any: """simple docstring""" __magic_name__ = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def _lowercase ( self : Union[str, Any] , UpperCamelCase__ : List[int] , UpperCamelCase__ : Optional[List[int]] = None ) -> List[int]: """simple docstring""" __magic_name__ = [self.sep_token_id] __magic_name__ = [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]
88
"""simple docstring""" def lowercase ( lowerCAmelCase__ : str ) -> list: if n_term == "": return [] __a = [] for temp in range(int(lowerCAmelCase__ ) ): series.append(f'''1/{temp + 1}''' if series else '''1''' ) return series if __name__ == "__main__": lowercase_ = input("Enter the last number (nth term) of the Harmonic Series") print("Formula of Harmonic Series => 1+1/2+1/3 ..... 1/n") print(harmonic_series(nth_term))
45
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __lowerCAmelCase = logging.get_logger(__name__) __lowerCAmelCase = { '''caidas/swin2sr-classicalsr-x2-64''': ( '''https://huggingface.co/caidas/swin2sr-classicalsr-x2-64/resolve/main/config.json''' ), } class __magic_name__ ( _UpperCamelCase ): lowerCAmelCase : List[str] = 'swin2sr' lowerCAmelCase : str = { 'hidden_size': 'embed_dim', 'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers', } def __init__( self : Union[str, Any] ,_UpperCAmelCase : Tuple=64 ,_UpperCAmelCase : str=1 ,_UpperCAmelCase : List[Any]=3 ,_UpperCAmelCase : Any=180 ,_UpperCAmelCase : Optional[Any]=[6, 6, 6, 6, 6, 6] ,_UpperCAmelCase : Any=[6, 6, 6, 6, 6, 6] ,_UpperCAmelCase : int=8 ,_UpperCAmelCase : Any=2.0 ,_UpperCAmelCase : Optional[Any]=True ,_UpperCAmelCase : Tuple=0.0 ,_UpperCAmelCase : Optional[int]=0.0 ,_UpperCAmelCase : Tuple=0.1 ,_UpperCAmelCase : List[str]="gelu" ,_UpperCAmelCase : Tuple=False ,_UpperCAmelCase : Optional[int]=0.02 ,_UpperCAmelCase : Union[str, Any]=1E-5 ,_UpperCAmelCase : int=2 ,_UpperCAmelCase : Tuple=1.0 ,_UpperCAmelCase : Union[str, Any]="1conv" ,_UpperCAmelCase : Tuple="pixelshuffle" ,**_UpperCAmelCase : List[str] ,): super().__init__(**_UpperCAmelCase ) _a : List[str] = image_size _a : Dict = patch_size _a : Optional[int] = num_channels _a : Optional[int] = embed_dim _a : Union[str, Any] = depths _a : Optional[int] = len(_UpperCAmelCase ) _a : Optional[Any] = num_heads _a : str = window_size _a : Optional[Any] = mlp_ratio _a : Optional[int] = qkv_bias _a : Tuple = hidden_dropout_prob _a : List[Any] = attention_probs_dropout_prob _a : Any = drop_path_rate _a : str = hidden_act _a : Tuple = use_absolute_embeddings _a : Dict = layer_norm_eps _a : Any = initializer_range _a : Optional[Any] = upscale _a : int = img_range _a : Union[str, Any] = resi_connection _a : int = upsampler
89
"""simple docstring""" from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import pyarrow as pa if TYPE_CHECKING: from .features import FeatureType @dataclass class __lowerCAmelCase : '''simple docstring''' __UpperCAmelCase : List[str] __UpperCAmelCase : Optional[str] = None # Automatically constructed __UpperCAmelCase : ClassVar[str] = "dict" __UpperCAmelCase : ClassVar[Any] = None __UpperCAmelCase : str = field(default='Translation' , init=__SCREAMING_SNAKE_CASE , repr=__SCREAMING_SNAKE_CASE ) def __call__( self ): return pa.struct({lang: pa.string() for lang in sorted(self.languages )} ) def __UpperCAmelCase ( self ): from .features import Value return {k: Value('''string''' ) for k in sorted(self.languages )} @dataclass class __lowerCAmelCase : '''simple docstring''' __UpperCAmelCase : Optional[List] = None __UpperCAmelCase : Optional[int] = None __UpperCAmelCase : Optional[str] = None # Automatically constructed __UpperCAmelCase : ClassVar[str] = "dict" __UpperCAmelCase : ClassVar[Any] = None __UpperCAmelCase : str = field(default='TranslationVariableLanguages' , init=__SCREAMING_SNAKE_CASE , repr=__SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self ): __a = sorted(set(self.languages ) ) if self.languages else None __a = len(self.languages ) if self.languages else None def __call__( self ): return pa.struct({'''language''': pa.list_(pa.string() ), '''translation''': pa.list_(pa.string() )} ) def __UpperCAmelCase ( self , _a ): __a = set(self.languages ) if self.languages and set(_a ) - lang_set: raise ValueError( f'''Some languages in example ({', '.join(sorted(set(_a ) - lang_set ) )}) are not in valid set ({', '.join(_a )}).''' ) # Convert dictionary into tuples, splitting out cases where there are # multiple translations for a single language. __a = [] for lang, text in translation_dict.items(): if isinstance(_a , _a ): translation_tuples.append((lang, text) ) else: translation_tuples.extend([(lang, el) for el in text] ) # Ensure translations are in ascending order by language code. __a , __a = zip(*sorted(_a ) ) return {"language": languages, "translation": translations} def __UpperCAmelCase ( self ): from .features import Sequence, Value return { "language": Sequence(Value('''string''' ) ), "translation": Sequence(Value('''string''' ) ), }
45
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __A = { "configuration_data2vec_audio": ["DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP", "Data2VecAudioConfig"], "configuration_data2vec_text": [ "DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP", "Data2VecTextConfig", "Data2VecTextOnnxConfig", ], "configuration_data2vec_vision": [ "DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP", "Data2VecVisionConfig", "Data2VecVisionOnnxConfig", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ "DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST", "Data2VecAudioForAudioFrameClassification", "Data2VecAudioForCTC", "Data2VecAudioForSequenceClassification", "Data2VecAudioForXVector", "Data2VecAudioModel", "Data2VecAudioPreTrainedModel", ] __A = [ "DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST", "Data2VecTextForCausalLM", "Data2VecTextForMaskedLM", "Data2VecTextForMultipleChoice", "Data2VecTextForQuestionAnswering", "Data2VecTextForSequenceClassification", "Data2VecTextForTokenClassification", "Data2VecTextModel", "Data2VecTextPreTrainedModel", ] __A = [ "DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST", "Data2VecVisionForImageClassification", "Data2VecVisionForMaskedImageModeling", "Data2VecVisionForSemanticSegmentation", "Data2VecVisionModel", "Data2VecVisionPreTrainedModel", ] if is_tf_available(): __A = [ "TFData2VecVisionForImageClassification", "TFData2VecVisionForSemanticSegmentation", "TFData2VecVisionModel", "TFData2VecVisionPreTrainedModel", ] if TYPE_CHECKING: from .configuration_dataavec_audio import DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecAudioConfig from .configuration_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecTextConfig, DataaVecTextOnnxConfig, ) from .configuration_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecVisionConfig, DataaVecVisionOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_dataavec_audio import ( DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecAudioForAudioFrameClassification, DataaVecAudioForCTC, DataaVecAudioForSequenceClassification, DataaVecAudioForXVector, DataaVecAudioModel, DataaVecAudioPreTrainedModel, ) from .modeling_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecTextForCausalLM, DataaVecTextForMaskedLM, DataaVecTextForMultipleChoice, DataaVecTextForQuestionAnswering, DataaVecTextForSequenceClassification, DataaVecTextForTokenClassification, DataaVecTextModel, DataaVecTextPreTrainedModel, ) from .modeling_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecVisionForImageClassification, DataaVecVisionForMaskedImageModeling, DataaVecVisionForSemanticSegmentation, DataaVecVisionModel, DataaVecVisionPreTrainedModel, ) if is_tf_available(): from .modeling_tf_dataavec_vision import ( TFDataaVecVisionForImageClassification, TFDataaVecVisionForSemanticSegmentation, TFDataaVecVisionModel, TFDataaVecVisionPreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
90
"""simple docstring""" def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list ) -> List[Any]: _enforce_args(lowerCAmelCase__ , lowerCAmelCase__ ) if n == 0: return 0 __a = float('''-inf''' ) for i in range(1 , n + 1 ): __a = max( lowerCAmelCase__ , prices[i - 1] + naive_cut_rod_recursive(n - i , lowerCAmelCase__ ) ) return max_revue def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list ) -> List[str]: _enforce_args(lowerCAmelCase__ , lowerCAmelCase__ ) __a = [float('''-inf''' ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list , lowerCAmelCase__ : list ) -> Union[str, Any]: if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: __a = float('''-inf''' ) for i in range(1 , n + 1 ): __a = max( lowerCAmelCase__ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , lowerCAmelCase__ , lowerCAmelCase__ ) , ) __a = max_revenue return max_rev[n] def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list ) -> Dict: _enforce_args(lowerCAmelCase__ , lowerCAmelCase__ ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. __a = [float('''-inf''' ) for _ in range(n + 1 )] __a = 0 for i in range(1 , n + 1 ): __a = max_rev[i] for j in range(1 , i + 1 ): __a = max(lowerCAmelCase__ , prices[j - 1] + max_rev[i - j] ) __a = max_revenue_i return max_rev[n] def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list ) -> str: if n < 0: __a = f'''n must be greater than or equal to 0. Got n = {n}''' raise ValueError(lowerCAmelCase__ ) if n > len(lowerCAmelCase__ ): __a = ( '''Each integral piece of rod must have a corresponding price. ''' f'''Got n = {n} but length of prices = {len(lowerCAmelCase__ )}''' ) raise ValueError(lowerCAmelCase__ ) def lowercase ( ) -> int: __a = [6, 10, 12, 15, 20, 23] __a = len(lowerCAmelCase__ ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. __a = 36 __a = top_down_cut_rod(lowerCAmelCase__ , lowerCAmelCase__ ) __a = bottom_up_cut_rod(lowerCAmelCase__ , lowerCAmelCase__ ) __a = naive_cut_rod_recursive(lowerCAmelCase__ , lowerCAmelCase__ ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
45
0
"""simple docstring""" import sys from typing import Tuple import numpy as np import torch from PIL import Image from torch import nn from transformers.image_utils import PILImageResampling from utils import img_tensorize class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Any , lowercase_ : Dict , lowercase_ : Union[str, Any]=sys.maxsize): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = '''bilinear''' SCREAMING_SNAKE_CASE_ : Optional[int] = max_size SCREAMING_SNAKE_CASE_ : Any = short_edge_length def __call__( self : str , lowercase_ : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = [] for img in imgs: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = img.shape[:2] # later: provide list and randomly choose index for resize SCREAMING_SNAKE_CASE_ : Any = np.random.randint(self.short_edge_length[0] , self.short_edge_length[1] + 1) if size == 0: return img SCREAMING_SNAKE_CASE_ : Dict = size * 1.0 / min(lowercase_ , lowercase_) if h < w: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : int = size, scale * w else: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Any = scale * h, size if max(lowercase_ , lowercase_) > self.max_size: SCREAMING_SNAKE_CASE_ : List[str] = self.max_size * 1.0 / max(lowercase_ , lowercase_) SCREAMING_SNAKE_CASE_ : Any = newh * scale SCREAMING_SNAKE_CASE_ : str = neww * scale SCREAMING_SNAKE_CASE_ : int = int(neww + 0.5) SCREAMING_SNAKE_CASE_ : Union[str, Any] = int(newh + 0.5) if img.dtype == np.uinta: SCREAMING_SNAKE_CASE_ : Tuple = Image.fromarray(lowercase_) SCREAMING_SNAKE_CASE_ : Optional[Any] = pil_image.resize((neww, newh) , PILImageResampling.BILINEAR) SCREAMING_SNAKE_CASE_ : int = np.asarray(lowercase_) else: SCREAMING_SNAKE_CASE_ : int = img.permute(2 , 0 , 1).unsqueeze(0) # 3, 0, 1) # hw(c) -> nchw SCREAMING_SNAKE_CASE_ : int = nn.functional.interpolate( lowercase_ , (newh, neww) , mode=self.interp_method , align_corners=lowercase_).squeeze(0) img_augs.append(lowercase_) return img_augs class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Tuple , lowercase_ : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = ResizeShortestEdge([cfg.INPUT.MIN_SIZE_TEST, cfg.INPUT.MIN_SIZE_TEST] , cfg.INPUT.MAX_SIZE_TEST) SCREAMING_SNAKE_CASE_ : Any = cfg.INPUT.FORMAT SCREAMING_SNAKE_CASE_ : List[str] = cfg.SIZE_DIVISIBILITY SCREAMING_SNAKE_CASE_ : List[str] = cfg.PAD_VALUE SCREAMING_SNAKE_CASE_ : List[Any] = cfg.INPUT.MAX_SIZE_TEST SCREAMING_SNAKE_CASE_ : List[Any] = cfg.MODEL.DEVICE SCREAMING_SNAKE_CASE_ : List[str] = torch.tensor(cfg.MODEL.PIXEL_STD).to(self.device).view(len(cfg.MODEL.PIXEL_STD) , 1 , 1) SCREAMING_SNAKE_CASE_ : Tuple = torch.tensor(cfg.MODEL.PIXEL_MEAN).to(self.device).view(len(cfg.MODEL.PIXEL_STD) , 1 , 1) SCREAMING_SNAKE_CASE_ : Dict = lambda lowercase_: (x - self.pixel_mean) / self.pixel_std def _SCREAMING_SNAKE_CASE ( self : Any , lowercase_ : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = tuple(max(lowercase_) for s in zip(*[img.shape for img in images])) SCREAMING_SNAKE_CASE_ : List[str] = [im.shape[-2:] for im in images] SCREAMING_SNAKE_CASE_ : int = [ nn.functional.pad( lowercase_ , [0, max_size[-1] - size[1], 0, max_size[-2] - size[0]] , value=self.pad_value , ) for size, im in zip(lowercase_ , lowercase_) ] return torch.stack(lowercase_), torch.tensor(lowercase_) def __call__( self : Tuple , lowercase_ : Optional[int] , lowercase_ : List[Any]=False): '''simple docstring''' with torch.no_grad(): if not isinstance(lowercase_ , lowercase_): SCREAMING_SNAKE_CASE_ : Optional[Any] = [images] if single_image: assert len(lowercase_) == 1 for i in range(len(lowercase_)): if isinstance(images[i] , torch.Tensor): images.insert(lowercase_ , images.pop(lowercase_).to(self.device).float()) elif not isinstance(images[i] , torch.Tensor): images.insert( lowercase_ , torch.as_tensor(img_tensorize(images.pop(lowercase_) , input_format=self.input_format)) .to(self.device) .float() , ) # resize smallest edge SCREAMING_SNAKE_CASE_ : List[Any] = torch.tensor([im.shape[:2] for im in images]) SCREAMING_SNAKE_CASE_ : Optional[int] = self.aug(lowercase_) # transpose images and convert to torch tensors # images = [torch.as_tensor(i.astype("float32")).permute(2, 0, 1).to(self.device) for i in images] # now normalize before pad to avoid useless arithmetic SCREAMING_SNAKE_CASE_ : Optional[Any] = [self.normalizer(lowercase_) for x in images] # now pad them to do the following operations SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : int = self.pad(lowercase_) # Normalize if self.size_divisibility > 0: raise NotImplementedError() # pad SCREAMING_SNAKE_CASE_ : Optional[int] = torch.true_divide(lowercase_ , lowercase_) if single_image: return images[0], sizes[0], scales_yx[0] else: return images, sizes, scales_yx def _A (__a , __a ) -> Dict: """simple docstring""" boxes[:, 0::2] *= scale_yx[:, 1] boxes[:, 1::2] *= scale_yx[:, 0] return boxes def _A (__a , __a ) -> Any: """simple docstring""" assert torch.isfinite(__a ).all(), "Box tensor contains infinite or NaN!" SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[Any] = box_size tensor[:, 0].clamp_(min=0 , max=__a ) tensor[:, 1].clamp_(min=0 , max=__a ) tensor[:, 2].clamp_(min=0 , max=__a ) tensor[:, 3].clamp_(min=0 , max=__a )
91
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) lowercase_ = {"configuration_unispeech": ["UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP", "UniSpeechConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST", "UniSpeechForCTC", "UniSpeechForPreTraining", "UniSpeechForSequenceClassification", "UniSpeechModel", "UniSpeechPreTrainedModel", ] if TYPE_CHECKING: from .configuration_unispeech import UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_unispeech import ( UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST, UniSpeechForCTC, UniSpeechForPreTraining, UniSpeechForSequenceClassification, UniSpeechModel, UniSpeechPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
45
0
import logging from transformers import PretrainedConfig UpperCamelCase__ = logging.getLogger(__name__) UpperCamelCase__ = { """bertabs-finetuned-cnndm""": """https://huggingface.co/remi/bertabs-finetuned-cnndm-extractive-abstractive-summarization/resolve/main/config.json""", } class a__ ( snake_case__ ): _a : Optional[int] = """bertabs""" def __init__( self , _A=3_0_5_2_2 , _A=5_1_2 , _A=6 , _A=5_1_2 , _A=8 , _A=5_1_2 , _A=0.2 , _A=6 , _A=7_6_8 , _A=8 , _A=2_0_4_8 , _A=0.2 , **_A , ): """simple docstring""" super().__init__(**_A ) __lowerCAmelCase = vocab_size __lowerCAmelCase = max_pos __lowerCAmelCase = enc_layers __lowerCAmelCase = enc_hidden_size __lowerCAmelCase = enc_heads __lowerCAmelCase = enc_ff_size __lowerCAmelCase = enc_dropout __lowerCAmelCase = dec_layers __lowerCAmelCase = dec_hidden_size __lowerCAmelCase = dec_heads __lowerCAmelCase = dec_ff_size __lowerCAmelCase = dec_dropout
92
"""simple docstring""" import unittest import torch from torch import nn from diffusers.models.activations import get_activation class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = get_activation('''swish''' ) self.assertIsInstance(_a , nn.SiLU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def __UpperCAmelCase ( self ): __a = get_activation('''silu''' ) self.assertIsInstance(_a , nn.SiLU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def __UpperCAmelCase ( self ): __a = get_activation('''mish''' ) self.assertIsInstance(_a , nn.Mish ) self.assertEqual(act(torch.tensor(-200 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def __UpperCAmelCase ( self ): __a = get_activation('''gelu''' ) self.assertIsInstance(_a , nn.GELU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 )
45
0
'''simple docstring''' import unittest import numpy as np from transformers import MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING, TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING from transformers.pipelines import AudioClassificationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_torchaudio, slow, ) from .test_pipelines_common import ANY @is_pipeline_test class lowerCAmelCase__ ( unittest.TestCase ): lowerCAmelCase_ = MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING lowerCAmelCase_ = TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : str = AudioClassificationPipeline(model=__SCREAMING_SNAKE_CASE , feature_extractor=__SCREAMING_SNAKE_CASE ) # test with a raw waveform lowercase_ : Tuple = np.zeros((3_40_00,) ) lowercase_ : str = np.zeros((1_40_00,) ) return audio_classifier, [audioa, audio] def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ , lowercase_ : List[str] = examples lowercase_ : Tuple = audio_classifier(__SCREAMING_SNAKE_CASE ) # by default a model is initialized with num_labels=2 self.assertEqual( __SCREAMING_SNAKE_CASE , [ {'''score''': ANY(__SCREAMING_SNAKE_CASE ), '''label''': ANY(__SCREAMING_SNAKE_CASE )}, {'''score''': ANY(__SCREAMING_SNAKE_CASE ), '''label''': ANY(__SCREAMING_SNAKE_CASE )}, ] , ) lowercase_ : int = audio_classifier(__SCREAMING_SNAKE_CASE , top_k=1 ) self.assertEqual( __SCREAMING_SNAKE_CASE , [ {'''score''': ANY(__SCREAMING_SNAKE_CASE ), '''label''': ANY(__SCREAMING_SNAKE_CASE )}, ] , ) self.run_torchaudio(__SCREAMING_SNAKE_CASE ) @require_torchaudio def _snake_case ( self , __SCREAMING_SNAKE_CASE ): """simple docstring""" import datasets # test with a local file lowercase_ : Optional[int] = datasets.load_dataset('''hf-internal-testing/librispeech_asr_dummy''' , '''clean''' , split='''validation''' ) lowercase_ : Any = dataset[0]['''audio''']['''array'''] lowercase_ : Tuple = audio_classifier(__SCREAMING_SNAKE_CASE ) self.assertEqual( __SCREAMING_SNAKE_CASE , [ {'''score''': ANY(__SCREAMING_SNAKE_CASE ), '''label''': ANY(__SCREAMING_SNAKE_CASE )}, {'''score''': ANY(__SCREAMING_SNAKE_CASE ), '''label''': ANY(__SCREAMING_SNAKE_CASE )}, ] , ) @require_torch def _snake_case ( self ): """simple docstring""" lowercase_ : str = '''anton-l/wav2vec2-random-tiny-classifier''' lowercase_ : str = pipeline('''audio-classification''' , model=__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = np.ones((80_00,) ) lowercase_ : List[Any] = audio_classifier(__SCREAMING_SNAKE_CASE , top_k=4 ) lowercase_ : Dict = [ {'''score''': 0.0_842, '''label''': '''no'''}, {'''score''': 0.0_838, '''label''': '''up'''}, {'''score''': 0.0_837, '''label''': '''go'''}, {'''score''': 0.0_834, '''label''': '''right'''}, ] lowercase_ : Optional[int] = [ {'''score''': 0.0_845, '''label''': '''stop'''}, {'''score''': 0.0_844, '''label''': '''on'''}, {'''score''': 0.0_841, '''label''': '''right'''}, {'''score''': 0.0_834, '''label''': '''left'''}, ] self.assertIn(nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [EXPECTED_OUTPUT, EXPECTED_OUTPUT_PT_2] ) lowercase_ : List[str] = {'''array''': np.ones((80_00,) ), '''sampling_rate''': audio_classifier.feature_extractor.sampling_rate} lowercase_ : Dict = audio_classifier(__SCREAMING_SNAKE_CASE , top_k=4 ) self.assertIn(nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [EXPECTED_OUTPUT, EXPECTED_OUTPUT_PT_2] ) @require_torch @slow def _snake_case ( self ): """simple docstring""" import datasets lowercase_ : Any = '''superb/wav2vec2-base-superb-ks''' lowercase_ : Optional[Any] = pipeline('''audio-classification''' , model=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = datasets.load_dataset('''anton-l/superb_dummy''' , '''ks''' , split='''test''' ) lowercase_ : int = np.array(dataset[3]['''speech'''] , dtype=np.floataa ) lowercase_ : Optional[Any] = audio_classifier(__SCREAMING_SNAKE_CASE , top_k=4 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=3 ) , [ {'''score''': 0.981, '''label''': '''go'''}, {'''score''': 0.007, '''label''': '''up'''}, {'''score''': 0.006, '''label''': '''_unknown_'''}, {'''score''': 0.001, '''label''': '''down'''}, ] , ) @require_tf @unittest.skip('''Audio classification is not implemented for TF''' ) def _snake_case ( self ): """simple docstring""" pass
93
"""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 : '''simple docstring''' def __init__( self , _a , ): __a = parent __a = 13 __a = 7 __a = True __a = True __a = True __a = 99 __a = 32 __a = 2 __a = 4 __a = 37 __a = '''gelu''' __a = 0.1 __a = 0.1 __a = 512 __a = 16 __a = 2 __a = 0.02 __a = 3 __a = 4 __a = None def __UpperCAmelCase ( self ): __a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a = None if self.use_input_mask: __a = random_attention_mask([self.batch_size, self.seq_length] ) __a = None __a = None __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __a = ids_tensor([self.batch_size] , self.num_choices ) __a = 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 __UpperCAmelCase ( self ): ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = self.prepare_config_and_inputs() __a = True __a = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __a = 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 __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a ): __a = TFEsmModel(config=_a ) __a = {'''input_ids''': input_ids, '''attention_mask''': input_mask} __a = model(_a ) __a = [input_ids, input_mask] __a = model(_a ) __a = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a , _a , ): __a = True __a = TFEsmModel(config=_a ) __a = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''encoder_hidden_states''': encoder_hidden_states, '''encoder_attention_mask''': encoder_attention_mask, } __a = model(_a ) __a = [input_ids, input_mask] __a = model(_a , encoder_hidden_states=_a ) # Also check the case where encoder outputs are not passed __a = model(_a , attention_mask=_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a ): __a = TFEsmForMaskedLM(config=_a ) __a = model([input_ids, input_mask] ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a ): __a = self.num_labels __a = TFEsmForTokenClassification(config=_a ) __a = {'''input_ids''': input_ids, '''attention_mask''': input_mask} __a = model(_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCAmelCase ( self ): __a = self.prepare_config_and_inputs() ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = config_and_inputs __a = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_tf class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : int = ( ( TFEsmModel, TFEsmForMaskedLM, TFEsmForSequenceClassification, TFEsmForTokenClassification, ) if is_tf_available() else () ) __UpperCAmelCase : Tuple = ( { 'feature-extraction': TFEsmModel, 'fill-mask': TFEsmForMaskedLM, 'text-classification': TFEsmForSequenceClassification, 'token-classification': TFEsmForTokenClassification, 'zero-shot': TFEsmForSequenceClassification, } if is_tf_available() else {} ) __UpperCAmelCase : Tuple = False __UpperCAmelCase : Union[str, Any] = False def __UpperCAmelCase ( self ): __a = TFEsmModelTester(self ) __a = ConfigTester(self , config_class=_a , hidden_size=37 ) def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_a ) @slow def __UpperCAmelCase ( self ): for model_name in TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = TFEsmModel.from_pretrained(_a ) self.assertIsNotNone(_a ) @unittest.skip('''Protein models do not support embedding resizing.''' ) def __UpperCAmelCase ( self ): pass @unittest.skip('''Protein models do not support embedding resizing.''' ) 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(_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 __a = model.get_bias() assert isinstance(_a , _a ) for k, v in name.items(): assert isinstance(_a , tf.Variable ) else: __a = model.get_output_embeddings() assert x is None __a = model.get_bias() assert name is None @require_tf class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @slow def __UpperCAmelCase ( self ): __a = TFEsmForMaskedLM.from_pretrained('''facebook/esm2_t6_8M_UR50D''' ) __a = tf.constant([[0, 1, 2, 3, 4, 5]] ) __a = model(_a )[0] __a = [1, 6, 33] self.assertEqual(list(output.numpy().shape ) , _a ) # compare the actual values for a slice. __a = tf.constant( [ [ [8.92_1518, -10.58_9814, -6.467_1307], [-6.396_7156, -13.91_1377, -1.121_1915], [-7.78_1247, -13.95_1557, -3.74_0592], ] ] ) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-2 ) ) @slow def __UpperCAmelCase ( self ): __a = TFEsmModel.from_pretrained('''facebook/esm2_t6_8M_UR50D''' ) __a = tf.constant([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] ) __a = model(_a )[0] # compare the actual values for a slice. __a = tf.constant( [ [ [0.1444_3092, 0.5412_5327, 0.324_7739], [0.3034_0484, 0.0052_6676, 0.3107_7722], [0.3227_8043, -0.2498_7096, 0.341_4628], ] ] ) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4 ) )
45
0
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices snake_case : Optional[int] = logging.get_logger(__name__) snake_case : Any = { '''microsoft/swin-tiny-patch4-window7-224''': ( '''https://huggingface.co/microsoft/swin-tiny-patch4-window7-224/resolve/main/config.json''' ), # See all Swin models at https://huggingface.co/models?filter=swin } class _snake_case ( _snake_case , _snake_case ): SCREAMING_SNAKE_CASE__ = 'swin' SCREAMING_SNAKE_CASE__ = { 'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers', } def __init__( self , _lowerCamelCase=224 , _lowerCamelCase=4 , _lowerCamelCase=3 , _lowerCamelCase=96 , _lowerCamelCase=[2, 2, 6, 2] , _lowerCamelCase=[3, 6, 12, 24] , _lowerCamelCase=7 , _lowerCamelCase=4.0 , _lowerCamelCase=True , _lowerCamelCase=0.0 , _lowerCamelCase=0.0 , _lowerCamelCase=0.1 , _lowerCamelCase="gelu" , _lowerCamelCase=False , _lowerCamelCase=0.02 , _lowerCamelCase=1e-5 , _lowerCamelCase=32 , _lowerCamelCase=None , _lowerCamelCase=None , **_lowerCamelCase , ): super().__init__(**_lowerCamelCase ) a :Optional[Any] = image_size a :List[Any] = patch_size a :Any = num_channels a :str = embed_dim a :str = depths a :Optional[Any] = len(_lowerCamelCase ) a :int = num_heads a :str = window_size a :List[Any] = mlp_ratio a :Union[str, Any] = qkv_bias a :Optional[Any] = hidden_dropout_prob a :List[Any] = attention_probs_dropout_prob a :Any = drop_path_rate a :Dict = hidden_act a :Union[str, Any] = use_absolute_embeddings a :Tuple = layer_norm_eps a :Optional[Any] = initializer_range a :List[str] = encoder_stride # 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 :List[str] = int(embed_dim * 2 ** (len(_lowerCamelCase ) - 1) ) a :List[Any] = ['''stem'''] + [F'''stage{idx}''' for idx in range(1 , len(_lowerCamelCase ) + 1 )] a , a :Dict = get_aligned_output_features_output_indices( out_features=_lowerCamelCase , out_indices=_lowerCamelCase , stage_names=self.stage_names ) class _snake_case ( _snake_case ): SCREAMING_SNAKE_CASE__ = version.parse('1.11' ) @property def SCREAMING_SNAKE_CASE__ ( self ): return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def SCREAMING_SNAKE_CASE__ ( self ): return 1e-4
94
"""simple docstring""" def lowercase ( lowerCAmelCase__ : int ) -> str: if number > 0: raise ValueError('''input must be a negative integer''' ) __a = len(bin(lowerCAmelCase__ )[3:] ) __a = bin(abs(lowerCAmelCase__ ) - (1 << binary_number_length) )[3:] __a = ( ( '''1''' + '''0''' * (binary_number_length - len(lowerCAmelCase__ )) + twos_complement_number ) if number < 0 else '''0''' ) return "0b" + twos_complement_number if __name__ == "__main__": import doctest doctest.testmod()
45
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 DeformableDetrImageProcessor class __lowerCAmelCase ( unittest.TestCase): def __init__( self , lowerCAmelCase__ , lowerCAmelCase__=7 , lowerCAmelCase__=3 , lowerCAmelCase__=3_0 , lowerCAmelCase__=4_0_0 , lowerCAmelCase__=True , lowerCAmelCase__=None , lowerCAmelCase__=True , lowerCAmelCase__=[0.5, 0.5, 0.5] , lowerCAmelCase__=[0.5, 0.5, 0.5] , lowerCAmelCase__=True , lowerCAmelCase__=1 / 2_5_5 , lowerCAmelCase__=True , ) -> str: '''simple docstring''' a__ : str =size if size is not None else {"shortest_edge": 1_8, "longest_edge": 1_3_3_3} a__ : Tuple =parent a__ : Any =batch_size a__ : int =num_channels a__ : List[str] =min_resolution a__ : Tuple =max_resolution a__ : Tuple =do_resize a__ : Dict =size a__ : List[str] =do_normalize a__ : Optional[Any] =image_mean a__ : Tuple =image_std a__ : Dict =do_rescale a__ : List[Any] =rescale_factor a__ : Optional[Any] =do_pad def _lowercase ( self ) -> Any: '''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 _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__=False ) -> Any: '''simple docstring''' if not batched: a__ : Tuple =image_inputs[0] if isinstance(lowerCAmelCase__ , Image.Image ): a__ , a__ : Union[str, Any] =image.size else: a__ , a__ : Optional[int] =image.shape[1], image.shape[2] if w < h: a__ : Optional[int] =int(self.size["shortest_edge"] * h / w ) a__ : List[Any] =self.size["shortest_edge"] elif w > h: a__ : Dict =self.size["shortest_edge"] a__ : List[Any] =int(self.size["shortest_edge"] * w / h ) else: a__ : List[Any] =self.size["shortest_edge"] a__ : int =self.size["shortest_edge"] else: a__ : List[Any] =[] for image in image_inputs: a__ , a__ : Optional[int] =self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) a__ : Any =max(lowerCAmelCase__ , key=lambda lowerCAmelCase__ : item[0] )[0] a__ : Union[str, Any] =max(lowerCAmelCase__ , key=lambda lowerCAmelCase__ : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class __lowerCAmelCase ( UpperCamelCase__ , unittest.TestCase): _lowercase : Tuple = DeformableDetrImageProcessor if is_vision_available() else None def _lowercase ( self ) -> Tuple: '''simple docstring''' a__ : List[str] =DeformableDetrImageProcessingTester(self ) @property def _lowercase ( self ) -> Dict: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def _lowercase ( self ) -> Tuple: '''simple docstring''' a__ : 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 _lowercase ( self ) -> str: '''simple docstring''' a__ : Optional[int] =self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"shortest_edge": 1_8, "longest_edge": 1_3_3_3} ) self.assertEqual(image_processor.do_pad , lowerCAmelCase__ ) a__ : List[str] =self.image_processing_class.from_dict( self.image_processor_dict , size=4_2 , max_size=8_4 , pad_and_return_pixel_mask=lowerCAmelCase__ ) self.assertEqual(image_processor.size , {"shortest_edge": 4_2, "longest_edge": 8_4} ) self.assertEqual(image_processor.do_pad , lowerCAmelCase__ ) def _lowercase ( self ) -> Dict: '''simple docstring''' pass def _lowercase ( self ) -> Tuple: '''simple docstring''' a__ : Optional[int] =self.image_processing_class(**self.image_processor_dict ) # create random PIL images a__ : List[Any] =prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCAmelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCAmelCase__ , Image.Image ) # Test not batched input a__ : List[Any] =image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values a__ , a__ : List[Any] =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 a__ , a__ : List[str] =self.image_processor_tester.get_expected_values(lowerCAmelCase__ , batched=lowerCAmelCase__ ) a__ : Optional[int] =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 _lowercase ( self ) -> Optional[Any]: '''simple docstring''' a__ : List[Any] =self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors a__ : int =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 a__ : Union[str, Any] =image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values a__ , a__ : Dict =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 a__ : Union[str, Any] =image_processing(lowerCAmelCase__ , return_tensors="pt" ).pixel_values a__ , a__ : List[str] =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 _lowercase ( self ) -> int: '''simple docstring''' a__ : List[str] =self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors a__ : Union[str, Any] =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 a__ : int =image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values a__ , a__ : List[Any] =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 a__ : Union[str, Any] =image_processing(lowerCAmelCase__ , return_tensors="pt" ).pixel_values a__ , a__ : Tuple =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 _lowercase ( self ) -> Optional[int]: '''simple docstring''' a__ : int =Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_annotations.txt" , "r" ) as f: a__ : Optional[int] =json.loads(f.read() ) a__ : Any ={"image_id": 3_9_7_6_9, "annotations": target} # encode them a__ : Union[str, Any] =DeformableDetrImageProcessor() a__ : Tuple =image_processing(images=lowerCAmelCase__ , annotations=lowerCAmelCase__ , return_tensors="pt" ) # verify pixel values a__ : Tuple =torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding["pixel_values"].shape , lowerCAmelCase__ ) a__ : Any =torch.tensor([0.27_96, 0.31_38, 0.34_81] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , lowerCAmelCase__ , atol=1E-4 ) ) # verify area a__ : List[Any] =torch.tensor([58_87.96_00, 1_12_50.20_61, 48_93_53.84_38, 83_71_22.75_00, 14_79_67.51_56, 16_57_32.34_38] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , lowerCAmelCase__ ) ) # verify boxes a__ : Any =torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , lowerCAmelCase__ ) a__ : Optional[Any] =torch.tensor([0.55_03, 0.27_65, 0.06_04, 0.22_15] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , lowerCAmelCase__ , atol=1E-3 ) ) # verify image_id a__ : int =torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , lowerCAmelCase__ ) ) # verify is_crowd a__ : str =torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , lowerCAmelCase__ ) ) # verify class_labels a__ : List[str] =torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , lowerCAmelCase__ ) ) # verify orig_size a__ : Optional[int] =torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , lowerCAmelCase__ ) ) # verify size a__ : int =torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , lowerCAmelCase__ ) ) @slow def _lowercase ( self ) -> List[str]: '''simple docstring''' a__ : 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: a__ : int =json.loads(f.read() ) a__ : List[str] ={"file_name": "000000039769.png", "image_id": 3_9_7_6_9, "segments_info": target} a__ : List[Any] =pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic" ) # encode them a__ : Any =DeformableDetrImageProcessor(format="coco_panoptic" ) a__ : Optional[Any] =image_processing(images=lowerCAmelCase__ , annotations=lowerCAmelCase__ , masks_path=lowerCAmelCase__ , return_tensors="pt" ) # verify pixel values a__ : Union[str, Any] =torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding["pixel_values"].shape , lowerCAmelCase__ ) a__ : Union[str, Any] =torch.tensor([0.27_96, 0.31_38, 0.34_81] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , lowerCAmelCase__ , atol=1E-4 ) ) # verify area a__ : Dict =torch.tensor([14_79_79.68_75, 16_55_27.04_69, 48_46_38.59_38, 1_12_92.93_75, 58_79.65_62, 76_34.11_47] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , lowerCAmelCase__ ) ) # verify boxes a__ : Optional[int] =torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , lowerCAmelCase__ ) a__ : Any =torch.tensor([0.26_25, 0.54_37, 0.46_88, 0.86_25] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , lowerCAmelCase__ , atol=1E-3 ) ) # verify image_id a__ : int =torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , lowerCAmelCase__ ) ) # verify is_crowd a__ : List[str] =torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , lowerCAmelCase__ ) ) # verify class_labels a__ : Optional[Any] =torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , lowerCAmelCase__ ) ) # verify masks a__ : int =8_2_2_8_7_3 self.assertEqual(encoding["labels"][0]["masks"].sum().item() , lowerCAmelCase__ ) # verify orig_size a__ : List[str] =torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , lowerCAmelCase__ ) ) # verify size a__ : int =torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , lowerCAmelCase__ ) )
95
"""simple docstring""" def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : list[str] ) -> str: __a = '''''' for word_or_phrase in separated: if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise Exception('''join() accepts only strings to be joined''' ) joined += word_or_phrase + separator return joined.strip(lowerCAmelCase__ ) if __name__ == "__main__": from doctest import testmod testmod()
45
0
"""simple docstring""" from typing import Optional, Tuple, Union import flax import flax.linen as nn import jax import jax.numpy as jnp from flax.core.frozen_dict import FrozenDict from ..configuration_utils import ConfigMixin, flax_register_to_config from ..utils import BaseOutput from .embeddings_flax import FlaxTimestepEmbedding, FlaxTimesteps from .modeling_flax_utils import FlaxModelMixin from .unet_ad_blocks_flax import ( FlaxCrossAttnDownBlockaD, FlaxCrossAttnUpBlockaD, FlaxDownBlockaD, FlaxUNetMidBlockaDCrossAttn, FlaxUpBlockaD, ) @flax.struct.dataclass class lowerCAmelCase__ ( lowercase ): '''simple docstring''' lowerCamelCase__ = 42 @flax_register_to_config class lowerCAmelCase__ ( nn.Module, lowercase, lowercase ): '''simple docstring''' lowerCamelCase__ = 32 lowerCamelCase__ = 4 lowerCamelCase__ = 4 lowerCamelCase__ = ( "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D", ) lowerCamelCase__ = ("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D") lowerCamelCase__ = False lowerCamelCase__ = (3_20, 6_40, 12_80, 12_80) lowerCamelCase__ = 2 lowerCamelCase__ = 8 lowerCamelCase__ = None lowerCamelCase__ = 12_80 lowerCamelCase__ = 0.0 lowerCamelCase__ = False lowerCamelCase__ = jnp.floataa lowerCamelCase__ = True lowerCamelCase__ = 0 lowerCamelCase__ = False def A_ ( self , lowercase ): # init input tensors _lowerCamelCase : Optional[int] = (1, self.in_channels, self.sample_size, self.sample_size) _lowerCamelCase : Tuple = jnp.zeros(lowercase , dtype=jnp.floataa ) _lowerCamelCase : str = jnp.ones((1,) , dtype=jnp.intaa ) _lowerCamelCase : Optional[Any] = jnp.zeros((1, 1, self.cross_attention_dim) , dtype=jnp.floataa ) _lowerCamelCase, _lowerCamelCase : Dict = jax.random.split(lowercase ) _lowerCamelCase : Union[str, Any] = {'params': params_rng, 'dropout': dropout_rng} return self.init(lowercase , lowercase , lowercase , lowercase )["params"] def A_ ( self ): _lowerCamelCase : Any = self.block_out_channels _lowerCamelCase : int = block_out_channels[0] * 4 if self.num_attention_heads is not None: raise ValueError( 'At the moment it is not possible to define the number of attention heads via `num_attention_heads` because of a naming issue as described in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131. Passing `num_attention_heads` will only be supported in diffusers v0.19.' ) # If `num_attention_heads` is not defined (which is the case for most models) # it will default to `attention_head_dim`. This looks weird upon first reading it and it is. # The reason for this behavior is to correct for incorrectly named variables that were introduced # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking # which is why we correct for the naming here. _lowerCamelCase : str = self.num_attention_heads or self.attention_head_dim # input _lowerCamelCase : Optional[int] = nn.Conv( block_out_channels[0] , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) # time _lowerCamelCase : List[str] = FlaxTimesteps( block_out_channels[0] , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.config.freq_shift ) _lowerCamelCase : str = FlaxTimestepEmbedding(lowercase , dtype=self.dtype ) _lowerCamelCase : Optional[Any] = self.only_cross_attention if isinstance(lowercase , lowercase ): _lowerCamelCase : str = (only_cross_attention,) * len(self.down_block_types ) if isinstance(lowercase , lowercase ): _lowerCamelCase : Union[str, Any] = (num_attention_heads,) * len(self.down_block_types ) # down _lowerCamelCase : int = [] _lowerCamelCase : Dict = block_out_channels[0] for i, down_block_type in enumerate(self.down_block_types ): _lowerCamelCase : Dict = output_channel _lowerCamelCase : List[str] = block_out_channels[i] _lowerCamelCase : Union[str, Any] = i == len(lowercase ) - 1 if down_block_type == "CrossAttnDownBlock2D": _lowerCamelCase : str = FlaxCrossAttnDownBlockaD( in_channels=lowercase , out_channels=lowercase , dropout=self.dropout , num_layers=self.layers_per_block , num_attention_heads=num_attention_heads[i] , add_downsample=not is_final_block , use_linear_projection=self.use_linear_projection , only_cross_attention=only_cross_attention[i] , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) else: _lowerCamelCase : int = FlaxDownBlockaD( in_channels=lowercase , out_channels=lowercase , dropout=self.dropout , num_layers=self.layers_per_block , add_downsample=not is_final_block , dtype=self.dtype , ) down_blocks.append(lowercase ) _lowerCamelCase : int = down_blocks # mid _lowerCamelCase : List[str] = FlaxUNetMidBlockaDCrossAttn( in_channels=block_out_channels[-1] , dropout=self.dropout , num_attention_heads=num_attention_heads[-1] , use_linear_projection=self.use_linear_projection , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) # up _lowerCamelCase : str = [] _lowerCamelCase : List[str] = list(reversed(lowercase ) ) _lowerCamelCase : Any = list(reversed(lowercase ) ) _lowerCamelCase : List[Any] = list(reversed(lowercase ) ) _lowerCamelCase : Any = reversed_block_out_channels[0] for i, up_block_type in enumerate(self.up_block_types ): _lowerCamelCase : Optional[Any] = output_channel _lowerCamelCase : Optional[Any] = reversed_block_out_channels[i] _lowerCamelCase : Optional[int] = reversed_block_out_channels[min(i + 1 , len(lowercase ) - 1 )] _lowerCamelCase : str = i == len(lowercase ) - 1 if up_block_type == "CrossAttnUpBlock2D": _lowerCamelCase : Any = FlaxCrossAttnUpBlockaD( in_channels=lowercase , out_channels=lowercase , prev_output_channel=lowercase , num_layers=self.layers_per_block + 1 , num_attention_heads=reversed_num_attention_heads[i] , add_upsample=not is_final_block , dropout=self.dropout , use_linear_projection=self.use_linear_projection , only_cross_attention=only_cross_attention[i] , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) else: _lowerCamelCase : int = FlaxUpBlockaD( in_channels=lowercase , out_channels=lowercase , prev_output_channel=lowercase , num_layers=self.layers_per_block + 1 , add_upsample=not is_final_block , dropout=self.dropout , dtype=self.dtype , ) up_blocks.append(lowercase ) _lowerCamelCase : Dict = output_channel _lowerCamelCase : int = up_blocks # out _lowerCamelCase : Union[str, Any] = nn.GroupNorm(num_groups=32 , epsilon=1E-5 ) _lowerCamelCase : Optional[int] = nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__( self , lowercase , lowercase , lowercase , lowercase=None , lowercase=None , lowercase = True , lowercase = False , ): # 1. time if not isinstance(lowercase , jnp.ndarray ): _lowerCamelCase : int = jnp.array([timesteps] , dtype=jnp.intaa ) elif isinstance(lowercase , jnp.ndarray ) and len(timesteps.shape ) == 0: _lowerCamelCase : Tuple = timesteps.astype(dtype=jnp.floataa ) _lowerCamelCase : Dict = jnp.expand_dims(lowercase , 0 ) _lowerCamelCase : int = self.time_proj(lowercase ) _lowerCamelCase : Optional[Any] = self.time_embedding(lowercase ) # 2. pre-process _lowerCamelCase : Union[str, Any] = jnp.transpose(lowercase , (0, 2, 3, 1) ) _lowerCamelCase : Union[str, Any] = self.conv_in(lowercase ) # 3. down _lowerCamelCase : Optional[int] = (sample,) for down_block in self.down_blocks: if isinstance(lowercase , lowercase ): _lowerCamelCase, _lowerCamelCase : int = down_block(lowercase , lowercase , lowercase , deterministic=not train ) else: _lowerCamelCase, _lowerCamelCase : List[str] = down_block(lowercase , lowercase , deterministic=not train ) down_block_res_samples += res_samples if down_block_additional_residuals is not None: _lowerCamelCase : List[Any] = () for down_block_res_sample, down_block_additional_residual in zip( lowercase , lowercase ): down_block_res_sample += down_block_additional_residual new_down_block_res_samples += (down_block_res_sample,) _lowerCamelCase : List[Any] = new_down_block_res_samples # 4. mid _lowerCamelCase : Tuple = self.mid_block(lowercase , lowercase , lowercase , deterministic=not train ) if mid_block_additional_residual is not None: sample += mid_block_additional_residual # 5. up for up_block in self.up_blocks: _lowerCamelCase : Dict = down_block_res_samples[-(self.layers_per_block + 1) :] _lowerCamelCase : List[Any] = down_block_res_samples[: -(self.layers_per_block + 1)] if isinstance(lowercase , lowercase ): _lowerCamelCase : str = up_block( lowercase , temb=lowercase , encoder_hidden_states=lowercase , res_hidden_states_tuple=lowercase , deterministic=not train , ) else: _lowerCamelCase : int = up_block(lowercase , temb=lowercase , res_hidden_states_tuple=lowercase , deterministic=not train ) # 6. post-process _lowerCamelCase : Optional[int] = self.conv_norm_out(lowercase ) _lowerCamelCase : Any = nn.silu(lowercase ) _lowerCamelCase : Optional[int] = self.conv_out(lowercase ) _lowerCamelCase : Any = jnp.transpose(lowercase , (0, 3, 1, 2) ) if not return_dict: return (sample,) return FlaxUNetaDConditionOutput(sample=lowercase )
96
"""simple docstring""" lowercase_ = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" def lowercase ( lowerCAmelCase__ : bytes ) -> bytes: # Make sure the supplied data is a bytes-like object if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): __a = f'''a bytes-like object is required, not \'{data.__class__.__name__}\'''' raise TypeError(lowerCAmelCase__ ) __a = ''''''.join(bin(lowerCAmelCase__ )[2:].zfill(8 ) for byte in data ) __a = len(lowerCAmelCase__ ) % 6 != 0 if padding_needed: # The padding that will be added later __a = b'''=''' * ((6 - len(lowerCAmelCase__ ) % 6) // 2) # Append binary_stream with arbitrary binary digits (0's by default) to make its # length a multiple of 6. binary_stream += "0" * (6 - len(lowerCAmelCase__ ) % 6) else: __a = b'''''' # Encode every 6 binary digits to their corresponding Base64 character return ( "".join( B64_CHARSET[int(binary_stream[index : index + 6] , 2 )] for index in range(0 , len(lowerCAmelCase__ ) , 6 ) ).encode() + padding ) def lowercase ( lowerCAmelCase__ : str ) -> bytes: # Make sure encoded_data is either a string or a bytes-like object if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): __a = ( '''argument should be a bytes-like object or ASCII string, ''' f'''not \'{encoded_data.__class__.__name__}\'''' ) raise TypeError(lowerCAmelCase__ ) # In case encoded_data is a bytes-like object, make sure it contains only # ASCII characters so we convert it to a string object if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): try: __a = encoded_data.decode('''utf-8''' ) except UnicodeDecodeError: raise ValueError('''base64 encoded data should only contain ASCII characters''' ) __a = encoded_data.count('''=''' ) # Check if the encoded string contains non base64 characters if padding: assert all( char in B64_CHARSET for char in encoded_data[:-padding] ), "Invalid base64 character(s) found." else: assert all( char in B64_CHARSET for char in encoded_data ), "Invalid base64 character(s) found." # Check the padding assert len(lowerCAmelCase__ ) % 4 == 0 and padding < 3, "Incorrect padding" if padding: # Remove padding if there is one __a = encoded_data[:-padding] __a = ''''''.join( bin(B64_CHARSET.index(lowerCAmelCase__ ) )[2:].zfill(6 ) for char in encoded_data )[: -padding * 2] else: __a = ''''''.join( bin(B64_CHARSET.index(lowerCAmelCase__ ) )[2:].zfill(6 ) for char in encoded_data ) __a = [ int(binary_stream[index : index + 8] , 2 ) for index in range(0 , len(lowerCAmelCase__ ) , 8 ) ] return bytes(lowerCAmelCase__ ) if __name__ == "__main__": import doctest doctest.testmod()
45
0
'''simple docstring''' from typing import Any def a ( __a ) -> list[Any]: '''simple docstring''' if not input_list: return [] UpperCamelCase__ :str = [input_list.count(__a ) for value in input_list] UpperCamelCase__ :Dict = max(__a ) # Gets the maximum count in the input list. # Gets values of modes return sorted({input_list[i] for i, value in enumerate(__a ) if value == y} ) if __name__ == "__main__": import doctest doctest.testmod()
97
"""simple docstring""" 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 __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = inspect.getfile(accelerate.test_utils ) __a = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_script.py'''] ) __a = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_distributed_data_loop.py'''] ) __a = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_ops.py'''] ) @require_multi_gpu def __UpperCAmelCase ( self ): print(f'''Found {torch.cuda.device_count()} devices.''' ) __a = ['''torchrun''', f'''--nproc_per_node={torch.cuda.device_count()}''', self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(_a , env=os.environ.copy() ) @require_multi_gpu def __UpperCAmelCase ( self ): print(f'''Found {torch.cuda.device_count()} devices.''' ) __a = ['''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(_a , env=os.environ.copy() ) @require_multi_gpu def __UpperCAmelCase ( self ): __a = ['''torchrun''', f'''--nproc_per_node={torch.cuda.device_count()}''', inspect.getfile(self.__class__ )] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(_a , env=os.environ.copy() ) @require_multi_gpu def __UpperCAmelCase ( self ): print(f'''Found {torch.cuda.device_count()} devices, using 2 devices only''' ) __a = ['''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(_a , env=os.environ.copy() ) if __name__ == "__main__": lowercase_ = Accelerator() lowercase_ = (accelerator.state.process_index + 2, 1_0) lowercase_ = torch.randint(0, 1_0, shape).to(accelerator.device) lowercase_ = "" lowercase_ = 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)." lowercase_ = 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." lowercase_ = 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)
45
0
"""simple docstring""" from argparse import ArgumentParser, Namespace from ..utils import logging from . import BaseTransformersCLICommand def a_ ( lowerCamelCase ): return ConvertCommand( args.model_type , args.tf_checkpoint , args.pytorch_dump_output , args.config , args.finetuning_task_name ) lowerCAmelCase__ : List[Any] = '\ntransformers can only be used from the commandline to convert TensorFlow models in PyTorch, In that case, it requires\nTensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installation instructions.\n' class snake_case ( __UpperCAmelCase ): """simple docstring""" @staticmethod def __lowerCAmelCase ( lowerCamelCase__ : ArgumentParser ): UpperCAmelCase__ = parser.add_parser( 'convert' ,help='CLI tool to run convert model from original author checkpoints to Transformers PyTorch checkpoints.' ,) train_parser.add_argument('--model_type' ,type=lowerCamelCase__ ,required=lowerCamelCase__ ,help='Model\'s type.' ) train_parser.add_argument( '--tf_checkpoint' ,type=lowerCamelCase__ ,required=lowerCamelCase__ ,help='TensorFlow checkpoint path or folder.' ) train_parser.add_argument( '--pytorch_dump_output' ,type=lowerCamelCase__ ,required=lowerCamelCase__ ,help='Path to the PyTorch saved model output.' ) train_parser.add_argument('--config' ,type=lowerCamelCase__ ,default='' ,help='Configuration file path or folder.' ) train_parser.add_argument( '--finetuning_task_name' ,type=lowerCamelCase__ ,default=lowerCamelCase__ ,help='Optional fine-tuning task name if the TF model was a finetuned model.' ,) train_parser.set_defaults(func=lowerCamelCase__ ) def __init__( self : List[Any] ,lowerCamelCase__ : str ,lowerCamelCase__ : str ,lowerCamelCase__ : str ,lowerCamelCase__ : str ,lowerCamelCase__ : str ,*lowerCamelCase__ : Any ,): UpperCAmelCase__ = logging.get_logger('transformers-cli/converting' ) self._logger.info(f'''Loading model {model_type}''' ) UpperCAmelCase__ = model_type UpperCAmelCase__ = tf_checkpoint UpperCAmelCase__ = pytorch_dump_output UpperCAmelCase__ = config UpperCAmelCase__ = finetuning_task_name def __lowerCAmelCase ( self : str ): if self._model_type == "albert": try: from ..models.albert.convert_albert_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(lowerCamelCase__ ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint ,self._config ,self._pytorch_dump_output ) elif self._model_type == "bert": try: from ..models.bert.convert_bert_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(lowerCamelCase__ ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint ,self._config ,self._pytorch_dump_output ) elif self._model_type == "funnel": try: from ..models.funnel.convert_funnel_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(lowerCamelCase__ ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint ,self._config ,self._pytorch_dump_output ) elif self._model_type == "t5": try: from ..models.ta.convert_ta_original_tf_checkpoint_to_pytorch import convert_tf_checkpoint_to_pytorch except ImportError: raise ImportError(lowerCamelCase__ ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint ,self._config ,self._pytorch_dump_output ) elif self._model_type == "gpt": from ..models.openai.convert_openai_original_tf_checkpoint_to_pytorch import ( convert_openai_checkpoint_to_pytorch, ) convert_openai_checkpoint_to_pytorch(self._tf_checkpoint ,self._config ,self._pytorch_dump_output ) elif self._model_type == "transfo_xl": try: from ..models.transfo_xl.convert_transfo_xl_original_tf_checkpoint_to_pytorch import ( convert_transfo_xl_checkpoint_to_pytorch, ) except ImportError: raise ImportError(lowerCamelCase__ ) if "ckpt" in self._tf_checkpoint.lower(): UpperCAmelCase__ = self._tf_checkpoint UpperCAmelCase__ = '' else: UpperCAmelCase__ = self._tf_checkpoint UpperCAmelCase__ = '' convert_transfo_xl_checkpoint_to_pytorch( lowerCamelCase__ ,self._config ,self._pytorch_dump_output ,lowerCamelCase__ ) elif self._model_type == "gpt2": try: from ..models.gpta.convert_gpta_original_tf_checkpoint_to_pytorch import ( convert_gpta_checkpoint_to_pytorch, ) except ImportError: raise ImportError(lowerCamelCase__ ) convert_gpta_checkpoint_to_pytorch(self._tf_checkpoint ,self._config ,self._pytorch_dump_output ) elif self._model_type == "xlnet": try: from ..models.xlnet.convert_xlnet_original_tf_checkpoint_to_pytorch import ( convert_xlnet_checkpoint_to_pytorch, ) except ImportError: raise ImportError(lowerCamelCase__ ) convert_xlnet_checkpoint_to_pytorch( self._tf_checkpoint ,self._config ,self._pytorch_dump_output ,self._finetuning_task_name ) elif self._model_type == "xlm": from ..models.xlm.convert_xlm_original_pytorch_checkpoint_to_pytorch import ( convert_xlm_checkpoint_to_pytorch, ) convert_xlm_checkpoint_to_pytorch(self._tf_checkpoint ,self._pytorch_dump_output ) elif self._model_type == "lxmert": from ..models.lxmert.convert_lxmert_original_tf_checkpoint_to_pytorch import ( convert_lxmert_checkpoint_to_pytorch, ) convert_lxmert_checkpoint_to_pytorch(self._tf_checkpoint ,self._pytorch_dump_output ) elif self._model_type == "rembert": from ..models.rembert.convert_rembert_tf_checkpoint_to_pytorch import ( convert_rembert_tf_checkpoint_to_pytorch, ) convert_rembert_tf_checkpoint_to_pytorch(self._tf_checkpoint ,self._config ,self._pytorch_dump_output ) else: raise ValueError( '--model_type should be selected in the list [bert, gpt, gpt2, t5, transfo_xl, xlnet, xlm, lxmert]' )
98
"""simple docstring""" import numpy as np def lowercase ( lowerCAmelCase__ : np.ndarray , lowerCAmelCase__ : float ) -> np.ndarray: return np.where(vector > 0 , lowerCAmelCase__ , (alpha * (np.exp(lowerCAmelCase__ ) - 1)) ) if __name__ == "__main__": import doctest doctest.testmod()
45
0
import doctest import logging import os import unittest from pathlib import Path from typing import List, Union import transformers from transformers.testing_utils import require_tf, require_torch, slow lowercase : List[Any] = logging.getLogger() @unittest.skip('''Temporarily disable the doc tests.''' ) @require_torch @require_tf @slow class A__ ( unittest.TestCase ): """simple docstring""" def __lowercase ( self , lowercase , lowercase = None , lowercase = None , lowercase = None , lowercase = True , ) -> Any: '''simple docstring''' a__ : int = [file for file in os.listdir(lowercase) if os.path.isfile(os.path.join(lowercase , lowercase))] if identifier is not None: a__ : int = [file for file in files if identifier in file] if n_identifier is not None: if isinstance(lowercase , lowercase): for n_ in n_identifier: a__ : List[str] = [file for file in files if n_ not in file] else: a__ : Union[str, Any] = [file for file in files if n_identifier not in file] a__ : Union[str, Any] = ignore_files or [] ignore_files.append('__init__.py') a__ : Tuple = [file for file in files if file not in ignore_files] for file in files: # Open all files print('Testing' , lowercase) if only_modules: a__ : Optional[Any] = file.split('.')[0] try: a__ : Any = getattr(lowercase , lowercase) a__ : Union[str, Any] = doctest.DocTestSuite(lowercase) a__ : Tuple = unittest.TextTestRunner().run(lowercase) self.assertIs(len(result.failures) , 0) except AttributeError: logger.info(F'{module_identifier} is not a module.') else: a__ : List[Any] = doctest.testfile(str('..' / directory / file) , optionflags=doctest.ELLIPSIS) self.assertIs(result.failed , 0) def __lowercase ( self) -> str: '''simple docstring''' a__ : Dict = Path('src/transformers') a__ : int = 'modeling' a__ : List[str] = [ 'modeling_ctrl.py', 'modeling_tf_ctrl.py', ] self.analyze_directory(lowercase , identifier=lowercase , ignore_files=lowercase) def __lowercase ( self) -> Union[str, Any]: '''simple docstring''' a__ : str = Path('src/transformers') a__ : List[str] = 'tokenization' self.analyze_directory(lowercase , identifier=lowercase) def __lowercase ( self) -> List[str]: '''simple docstring''' a__ : List[str] = Path('src/transformers') a__ : List[str] = 'configuration' self.analyze_directory(lowercase , identifier=lowercase) def __lowercase ( self) -> Optional[Any]: '''simple docstring''' a__ : Dict = Path('src/transformers') a__ : Dict = ['configuration', 'modeling', 'tokenization'] self.analyze_directory(lowercase , n_identifier=lowercase) def __lowercase ( self) -> List[str]: '''simple docstring''' a__ : Optional[int] = Path('docs/source') a__ : int = ['favicon.ico'] self.analyze_directory(lowercase , ignore_files=lowercase , only_modules=lowercase)
99
"""simple docstring""" def lowercase ( lowerCAmelCase__ : str = "The quick brown fox jumps over the lazy dog" , ) -> bool: __a = set() # Replace all the whitespace in our sentence __a = input_str.replace(''' ''' , '''''' ) for alpha in input_str: if "a" <= alpha.lower() <= "z": frequency.add(alpha.lower() ) return len(lowerCAmelCase__ ) == 26 def lowercase ( lowerCAmelCase__ : str = "The quick brown fox jumps over the lazy dog" , ) -> bool: __a = [False] * 26 for char in input_str: if char.islower(): __a = True elif char.isupper(): __a = True return all(lowerCAmelCase__ ) def lowercase ( lowerCAmelCase__ : str = "The quick brown fox jumps over the lazy dog" , ) -> bool: return len({char for char in input_str.lower() if char.isalpha()} ) == 26 def lowercase ( ) -> None: from timeit import timeit __a = '''from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest''' print(timeit('''is_pangram()''' , setup=lowerCAmelCase__ ) ) print(timeit('''is_pangram_faster()''' , setup=lowerCAmelCase__ ) ) print(timeit('''is_pangram_fastest()''' , setup=lowerCAmelCase__ ) ) # 5.348480500048026, 2.6477354579837993, 1.8470395830227062 # 5.036091582966037, 2.644472333951853, 1.8869528750656173 if __name__ == "__main__": import doctest doctest.testmod() benchmark()
45
0
"""simple docstring""" from __future__ import annotations from math import gcd def _lowerCAmelCase ( UpperCamelCase_ , UpperCamelCase_ = 2 , UpperCamelCase_ = 1 , UpperCamelCase_ = 3 , ): # A value less than 2 can cause an infinite loop in the algorithm. if num < 2: raise ValueError("""The input value cannot be less than 2""" ) # Because of the relationship between ``f(f(x))`` and ``f(x)``, this # algorithm struggles to find factors that are divisible by two. # As a workaround, we specifically check for two and even inputs. # See: https://math.stackexchange.com/a/2856214/165820 if num > 2 and num % 2 == 0: return 2 # Pollard's Rho algorithm requires a function that returns pseudorandom # values between 0 <= X < ``num``. It doesn't need to be random in the # sense that the output value is cryptographically secure or difficult # to calculate, it only needs to be random in the sense that all output # values should be equally likely to appear. # For this reason, Pollard suggested using ``f(x) = (x**2 - 1) % num`` # However, the success of Pollard's algorithm isn't guaranteed and is # determined in part by the initial seed and the chosen random function. # To make retries easier, we will instead use ``f(x) = (x**2 + C) % num`` # where ``C`` is a value that we can modify between each attempt. def rand_fn(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> int: return (pow(UpperCamelCase_ , 2 ) + step) % modulus for _ in range(UpperCamelCase_ ): # These track the position within the cycle detection logic. __SCREAMING_SNAKE_CASE = seed __SCREAMING_SNAKE_CASE = seed while True: # At each iteration, the tortoise moves one step and the hare moves two. __SCREAMING_SNAKE_CASE = rand_fn(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) __SCREAMING_SNAKE_CASE = rand_fn(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) __SCREAMING_SNAKE_CASE = rand_fn(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) # At some point both the tortoise and the hare will enter a cycle whose # length ``p`` is a divisor of ``num``. Once in that cycle, at some point # the tortoise and hare will end up on the same value modulo ``p``. # We can detect when this happens because the position difference between # the tortoise and the hare will share a common divisor with ``num``. __SCREAMING_SNAKE_CASE = gcd(hare - tortoise , UpperCamelCase_ ) if divisor == 1: # No common divisor yet, just keep searching. continue else: # We found a common divisor! if divisor == num: # Unfortunately, the divisor is ``num`` itself and is useless. break else: # The divisor is a nontrivial factor of ``num``! return divisor # If we made it here, then this attempt failed. # We need to pick a new starting seed for the tortoise and hare # in addition to a new step value for the random function. # To keep this example implementation deterministic, the # new values will be generated based on currently available # values instead of using something like ``random.randint``. # We can use the hare's position as the new seed. # This is actually what Richard Brent's the "optimized" variant does. __SCREAMING_SNAKE_CASE = hare # The new step value for the random function can just be incremented. # At first the results will be similar to what the old function would # have produced, but the value will quickly diverge after a bit. step += 1 # We haven't found a divisor within the requested number of attempts. # We were unlucky or ``num`` itself is actually prime. return None if __name__ == "__main__": import argparse __magic_name__ = argparse.ArgumentParser() parser.add_argument( "num", type=int, help="The value to find a divisor of", ) parser.add_argument( "--attempts", type=int, default=3, help="The number of attempts before giving up", ) __magic_name__ = parser.parse_args() __magic_name__ = pollard_rho(args.num, attempts=args.attempts) if divisor is None: print(F"""{args.num} is probably prime""") else: __magic_name__ = args.num // divisor print(F"""{args.num} = {divisor} * {quotient}""")
100
"""simple docstring""" import gc import unittest from transformers import CTRLConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, CTRLForSequenceClassification, CTRLLMHeadModel, CTRLModel, ) class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a=14 , _a=7 , _a=True , _a=True , _a=True , _a=True , _a=True , _a=99 , _a=32 , _a=5 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=16 , _a=2 , _a=0.02 , _a=3 , _a=4 , _a=None , ): __a = parent __a = batch_size __a = seq_length __a = is_training __a = use_token_type_ids __a = use_input_mask __a = use_labels __a = use_mc_token_ids __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = type_vocab_size __a = type_sequence_label_size __a = initializer_range __a = num_labels __a = num_choices __a = scope __a = self.vocab_size - 1 def __UpperCAmelCase ( self ): __a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a = None if self.use_input_mask: __a = random_attention_mask([self.batch_size, self.seq_length] ) __a = None if self.use_token_type_ids: __a = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __a = None if self.use_mc_token_ids: __a = ids_tensor([self.batch_size, self.num_choices] , self.seq_length ) __a = None __a = None __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __a = ids_tensor([self.batch_size] , self.num_choices ) __a = self.get_config() __a = ids_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 ) return ( config, input_ids, input_mask, head_mask, token_type_ids, mc_token_ids, sequence_labels, token_labels, choice_labels, ) def __UpperCAmelCase ( self ): return CTRLConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , pad_token_id=self.pad_token_id , ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , *_a ): __a = CTRLModel(config=_a ) model.to(_a ) model.eval() model(_a , token_type_ids=_a , head_mask=_a ) model(_a , token_type_ids=_a ) __a = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(len(result.past_key_values ) , config.n_layer ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , *_a ): __a = CTRLLMHeadModel(_a ) model.to(_a ) model.eval() __a = model(_a , token_type_ids=_a , labels=_a ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self ): __a = self.prepare_config_and_inputs() ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = config_and_inputs __a = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''head_mask''': head_mask} return config, inputs_dict def __UpperCAmelCase ( self , _a , _a , _a , _a , *_a ): __a = self.num_labels __a = CTRLForSequenceClassification(_a ) model.to(_a ) model.eval() __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = model(_a , token_type_ids=_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) @require_torch class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : str = (CTRLModel, CTRLLMHeadModel, CTRLForSequenceClassification) if is_torch_available() else () __UpperCAmelCase : Union[str, Any] = (CTRLLMHeadModel,) if is_torch_available() else () __UpperCAmelCase : Union[str, Any] = ( { 'feature-extraction': CTRLModel, 'text-classification': CTRLForSequenceClassification, 'text-generation': CTRLLMHeadModel, 'zero-shot': CTRLForSequenceClassification, } if is_torch_available() else {} ) __UpperCAmelCase : Optional[Any] = True __UpperCAmelCase : List[Any] = False __UpperCAmelCase : str = False def __UpperCAmelCase ( self , _a , _a , _a , _a , _a ): if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests": # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers. # `CTRLConfig` was never used in pipeline tests, either because of a missing checkpoint or because a tiny # config could not be created. return True return False def __UpperCAmelCase ( self ): __a = CTRLModelTester(self ) __a = ConfigTester(self , config_class=_a , n_embd=37 ) def __UpperCAmelCase ( self ): super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() torch.cuda.empty_cache() def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_ctrl_model(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*_a ) @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def __UpperCAmelCase ( self ): pass @slow def __UpperCAmelCase ( self ): for model_name in CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = CTRLModel.from_pretrained(_a ) self.assertIsNotNone(_a ) @unittest.skip('''The model doesn\'t support left padding''' ) # and it's not used enough to be worth fixing :) def __UpperCAmelCase ( self ): pass @require_torch class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() torch.cuda.empty_cache() @slow def __UpperCAmelCase ( self ): __a = CTRLLMHeadModel.from_pretrained('''ctrl''' ) model.to(_a ) __a = torch.tensor( [[11_859, 0, 1_611, 8]] , dtype=torch.long , device=_a ) # Legal the president is __a = [ 11_859, 0, 1_611, 8, 5, 150, 26_449, 2, 19, 348, 469, 3, 2_595, 48, 20_740, 246_533, 246_533, 19, 30, 5, ] # Legal the president is a good guy and I don't want to lose my job. \n \n I have a __a = model.generate(_a , do_sample=_a ) self.assertListEqual(output_ids[0].tolist() , _a )
45
0
import gc import unittest from diffusers import FlaxStableDiffusionInpaintPipeline from diffusers.utils import is_flax_available, load_image, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard @slow @require_flax class lowercase ( unittest.TestCase ): def A__ ( self): # clean up the VRAM after each test super().tearDown() gc.collect() def A__ ( self): lowercase = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/sd2-inpaint/init_image.png''') lowercase = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png''') lowercase = '''xvjiarui/stable-diffusion-2-inpainting''' lowercase , lowercase = FlaxStableDiffusionInpaintPipeline.from_pretrained(A__ ,safety_checker=A__) lowercase = '''Face of a yellow cat, high resolution, sitting on a park bench''' lowercase = jax.random.PRNGKey(0) lowercase = 5_0 lowercase = jax.device_count() lowercase = num_samples * [prompt] lowercase = num_samples * [init_image] lowercase = num_samples * [mask_image] lowercase , lowercase , lowercase = pipeline.prepare_inputs(A__ ,A__ ,A__) # shard inputs and rng lowercase = replicate(A__) lowercase = jax.random.split(A__ ,jax.device_count()) lowercase = shard(A__) lowercase = shard(A__) lowercase = shard(A__) lowercase = pipeline( A__ ,A__ ,A__ ,A__ ,A__ ,A__ ,jit=A__) lowercase = output.images.reshape(A__ ,5_1_2 ,5_1_2 ,3) lowercase = images[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] lowercase = jnp.asarray(jax.device_get(image_slice.flatten())) lowercase = jnp.array( [0.3611307, 0.37649736, 0.3757408, 0.38213953, 0.39295167, 0.3841631, 0.41554978, 0.4137475, 0.4217084]) print(f'output_slice: {output_slice}') assert jnp.abs(output_slice - expected_slice).max() < 1E-2
101
"""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, ) lowercase_ = {"configuration_xglm": ["XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP", "XGLMConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["XGLMTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["XGLMTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "XGLM_PRETRAINED_MODEL_ARCHIVE_LIST", "XGLMForCausalLM", "XGLMModel", "XGLMPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "FlaxXGLMForCausalLM", "FlaxXGLMModel", "FlaxXGLMPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST", "TFXGLMForCausalLM", "TFXGLMModel", "TFXGLMPreTrainedModel", ] if TYPE_CHECKING: from .configuration_xglm import XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XGLMConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm import XGLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm_fast import XGLMTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xglm import XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, XGLMForCausalLM, XGLMModel, XGLMPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_xglm import FlaxXGLMForCausalLM, FlaxXGLMModel, FlaxXGLMPreTrainedModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, TFXGLMPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure)
45
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available SCREAMING_SNAKE_CASE : Optional[Any] = { """configuration_m2m_100""": ["""M2M_100_PRETRAINED_CONFIG_ARCHIVE_MAP""", """M2M100Config""", """M2M100OnnxConfig"""], """tokenization_m2m_100""": ["""M2M100Tokenizer"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE : List[Any] = [ """M2M_100_PRETRAINED_MODEL_ARCHIVE_LIST""", """M2M100ForConditionalGeneration""", """M2M100Model""", """M2M100PreTrainedModel""", ] if TYPE_CHECKING: from .configuration_mam_aaa import M2M_100_PRETRAINED_CONFIG_ARCHIVE_MAP, MaMaaaConfig, MaMaaaOnnxConfig from .tokenization_mam_aaa import MaMaaaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mam_aaa import ( M2M_100_PRETRAINED_MODEL_ARCHIVE_LIST, MaMaaaForConditionalGeneration, MaMaaaModel, MaMaaaPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE : List[str] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
102
"""simple docstring""" 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 lowercase_ = re.compile("[^A-Za-z_0-9]") # parameters used in DuplicationIndex lowercase_ = 1_0 lowercase_ = 2_5_6 def lowercase ( lowerCAmelCase__ : List[str] ) -> Optional[MinHash]: if len(lowerCAmelCase__ ) < MIN_NUM_TOKENS: return None __a = MinHash(num_perm=lowerCAmelCase__ ) for token in set(lowerCAmelCase__ ): min_hash.update(token.encode() ) return min_hash def lowercase ( lowerCAmelCase__ : str ) -> Set[str]: return {t for t in NON_ALPHA.split(lowerCAmelCase__ ) if len(t.strip() ) > 0} class __lowerCAmelCase : '''simple docstring''' def __init__( self , *, _a = 0.85 , ): __a = duplication_jaccard_threshold __a = NUM_PERM __a = MinHashLSH(threshold=self._duplication_jaccard_threshold , num_perm=self._num_perm ) __a = defaultdict(_a ) def __UpperCAmelCase ( self , _a , _a ): __a = 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 __UpperCAmelCase ( self ): __a = [] for base, duplicates in self._duplicate_clusters.items(): __a = [base] + list(_a ) # reformat the cluster to be a list of dict __a = [{'''base_index''': el[0], '''repo_name''': el[1], '''path''': el[2]} for el in cluster] duplicate_clusters.append(_a ) return duplicate_clusters def __UpperCAmelCase ( self , _a ): __a = self.get_duplicate_clusters() with open(_a , '''w''' ) as f: json.dump(_a , _a ) def lowercase ( lowerCAmelCase__ : List[str] ) -> int: __a , __a = element __a = 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 lowercase ( lowerCAmelCase__ : Type[Dataset] ) -> str: 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 lowercase ( lowerCAmelCase__ : Type[Dataset] , lowerCAmelCase__ : float ) -> Dict: __a = 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 lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : str ) -> float: __a = get_tokens(lowerCAmelCase__ ) __a = get_tokens(lowerCAmelCase__ ) return len(tokensa & tokensa ) / len(tokensa | tokensa ) lowercase_ = None def lowercase ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Union[str, Any] ) -> Any: __a = [] for elementa in cluster: __a = _shared_dataset[elementa['''base_index''']]['''content'''] for elementa in extremes: __a = _shared_dataset[elementa['''base_index''']]['''content'''] if jaccard_similarity(lowerCAmelCase__ , lowerCAmelCase__ ) >= jaccard_threshold: elementa["copies"] += 1 break else: __a = 1 extremes.append(lowerCAmelCase__ ) return extremes def lowercase ( lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Optional[int] ) -> Optional[int]: global _shared_dataset __a = dataset __a = [] __a = 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 lowercase ( lowerCAmelCase__ : Type[Dataset] , lowerCAmelCase__ : float = 0.85 ) -> Tuple[Type[Dataset], List[List[Dict]]]: __a = make_duplicate_clusters(lowerCAmelCase__ , lowerCAmelCase__ ) __a = {x['''base_index'''] for cluster in duplicate_clusters for x in cluster} __a = {} __a = find_extremes(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) for extremes in extremes_clusters: for element in extremes: __a = element __a = duplicate_indices - set(extreme_dict.keys() ) __a = 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: __a = element['''base_index'''] in extreme_dict if element["is_extreme"]: __a = 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
45
0
class __snake_case : def __init__( self : str , A_ : Dict , A_ : Optional[int]): lowerCAmelCase_ : str = name lowerCAmelCase_ : List[Any] = val def __str__( self : List[str]): return F"""{self.__class__.__name__}({self.name}, {self.val})""" def __lt__( self : List[str] , A_ : Tuple): return self.val < other.val class __snake_case : def __init__( self : int , A_ : Dict): lowerCAmelCase_ : List[str] = {} lowerCAmelCase_ : Any = {} lowerCAmelCase_ : Dict = self.build_heap(A_) def __getitem__( self : List[str] , A_ : List[Any]): return self.get_value(A_) def UpperCAmelCase__ ( self : List[Any] , A_ : str): return (idx - 1) // 2 def UpperCAmelCase__ ( self : int , A_ : List[str]): return idx * 2 + 1 def UpperCAmelCase__ ( self : str , A_ : List[Any]): return idx * 2 + 2 def UpperCAmelCase__ ( self : Optional[Any] , A_ : Tuple): return self.heap_dict[key] def UpperCAmelCase__ ( self : Union[str, Any] , A_ : Tuple): lowerCAmelCase_ : Dict = len(A_) - 1 lowerCAmelCase_ : List[Any] = self.get_parent_idx(A_) for idx, i in enumerate(A_): lowerCAmelCase_ : List[str] = idx lowerCAmelCase_ : Any = i.val for i in range(A_ , -1 , -1): self.sift_down(A_ , A_) return array def UpperCAmelCase__ ( self : List[str] , A_ : int , A_ : Tuple): while True: lowerCAmelCase_ : Union[str, Any] = self.get_left_child_idx(A_) # noqa: E741 lowerCAmelCase_ : int = self.get_right_child_idx(A_) lowerCAmelCase_ : int = idx if l < len(A_) and array[l] < array[idx]: lowerCAmelCase_ : Any = l if r < len(A_) and array[r] < array[smallest]: lowerCAmelCase_ : List[str] = r if smallest != idx: lowerCAmelCase_ , lowerCAmelCase_ : List[Any] = array[smallest], array[idx] ( ( lowerCAmelCase_ ) , ( lowerCAmelCase_ ) , ) : List[Any] = ( self.idx_of_element[array[smallest]], self.idx_of_element[array[idx]], ) lowerCAmelCase_ : Union[str, Any] = smallest else: break def UpperCAmelCase__ ( self : Tuple , A_ : List[str]): lowerCAmelCase_ : Any = self.get_parent_idx(A_) while p >= 0 and self.heap[p] > self.heap[idx]: lowerCAmelCase_ , lowerCAmelCase_ : Optional[Any] = self.heap[idx], self.heap[p] lowerCAmelCase_ , lowerCAmelCase_ : Optional[Any] = ( self.idx_of_element[self.heap[idx]], self.idx_of_element[self.heap[p]], ) lowerCAmelCase_ : int = p lowerCAmelCase_ : Tuple = self.get_parent_idx(A_) def UpperCAmelCase__ ( self : Optional[Any]): return self.heap[0] def UpperCAmelCase__ ( self : Tuple): lowerCAmelCase_ , lowerCAmelCase_ : Optional[int] = self.heap[-1], self.heap[0] lowerCAmelCase_ , lowerCAmelCase_ : Any = ( self.idx_of_element[self.heap[-1]], self.idx_of_element[self.heap[0]], ) lowerCAmelCase_ : int = self.heap.pop() del self.idx_of_element[x] self.sift_down(0 , self.heap) return x def UpperCAmelCase__ ( self : Any , A_ : Any): self.heap.append(A_) lowerCAmelCase_ : Optional[int] = len(self.heap) - 1 lowerCAmelCase_ : Optional[int] = node.val self.sift_up(len(self.heap) - 1) def UpperCAmelCase__ ( self : List[Any]): return len(self.heap) == 0 def UpperCAmelCase__ ( self : Optional[int] , A_ : Optional[Any] , A_ : int): assert ( self.heap[self.idx_of_element[node]].val > new_value ), "newValue must be less that current value" lowerCAmelCase_ : Tuple = new_value lowerCAmelCase_ : Tuple = new_value self.sift_up(self.idx_of_element[node]) A__ : List[str] = Node('''R''', -1) A__ : Optional[Any] = Node('''B''', 6) A__ : List[str] = Node('''A''', 3) A__ : Optional[Any] = Node('''X''', 1) A__ : Tuple = Node('''E''', 4) # Use one of these two ways to generate Min-Heap # Generating Min-Heap from array A__ : Optional[Any] = MinHeap([r, b, a, x, e]) # Generating Min-Heap by Insert method # myMinHeap.insert(a) # myMinHeap.insert(b) # myMinHeap.insert(x) # myMinHeap.insert(r) # myMinHeap.insert(e) # Before print('''Min Heap - before decrease key''') for i in my_min_heap.heap: print(i) print('''Min Heap - After decrease key of node [B -> -17]''') my_min_heap.decrease_key(b, -17) # After for i in my_min_heap.heap: print(i) if __name__ == "__main__": import doctest doctest.testmod()
103
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowercase_ = { "configuration_roformer": ["ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "RoFormerConfig", "RoFormerOnnxConfig"], "tokenization_roformer": ["RoFormerTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["RoFormerTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "RoFormerForCausalLM", "RoFormerForMaskedLM", "RoFormerForMultipleChoice", "RoFormerForQuestionAnswering", "RoFormerForSequenceClassification", "RoFormerForTokenClassification", "RoFormerLayer", "RoFormerModel", "RoFormerPreTrainedModel", "load_tf_weights_in_roformer", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TFRoFormerForCausalLM", "TFRoFormerForMaskedLM", "TFRoFormerForMultipleChoice", "TFRoFormerForQuestionAnswering", "TFRoFormerForSequenceClassification", "TFRoFormerForTokenClassification", "TFRoFormerLayer", "TFRoFormerModel", "TFRoFormerPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "FlaxRoFormerForMaskedLM", "FlaxRoFormerForMultipleChoice", "FlaxRoFormerForQuestionAnswering", "FlaxRoFormerForSequenceClassification", "FlaxRoFormerForTokenClassification", "FlaxRoFormerModel", "FlaxRoFormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_roformer import ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, RoFormerConfig, RoFormerOnnxConfig from .tokenization_roformer import RoFormerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roformer_fast import RoFormerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roformer import ( ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, RoFormerForCausalLM, RoFormerForMaskedLM, RoFormerForMultipleChoice, RoFormerForQuestionAnswering, RoFormerForSequenceClassification, RoFormerForTokenClassification, RoFormerLayer, RoFormerModel, RoFormerPreTrainedModel, load_tf_weights_in_roformer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roformer import ( TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerLayer, TFRoFormerModel, TFRoFormerPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roformer import ( FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, FlaxRoFormerPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
45
0
'''simple docstring''' from __future__ import annotations from sys import maxsize from typing import Generic, TypeVar lowerCAmelCase__ = TypeVar('''T''') def _A ( A__ ): """simple docstring""" return (position - 1) // 2 def _A ( A__ ): """simple docstring""" return (2 * position) + 1 def _A ( A__ ): """simple docstring""" return (2 * position) + 2 class lowercase_ (Generic[T] ): """simple docstring""" def __init__( self : Union[str, Any] ): __lowercase = [] __lowercase = {} __lowercase = 0 def __len__( self : Optional[Any] ): return self.elements def __repr__( self : Any ): return str(self.heap ) def SCREAMING_SNAKE_CASE ( self : str ): # Check if the priority queue is empty return self.elements == 0 def SCREAMING_SNAKE_CASE ( self : str ,lowercase__ : T ,lowercase__ : int ): # Add an element with given priority to the queue self.heap.append((elem, weight) ) __lowercase = self.elements self.elements += 1 self._bubble_up(lowercase__ ) def SCREAMING_SNAKE_CASE ( self : int ): # Remove and return the element with lowest weight (highest priority) if self.elements > 1: self._swap_nodes(0 ,self.elements - 1 ) __lowercase , __lowercase = self.heap.pop() del self.position_map[elem] self.elements -= 1 if self.elements > 0: __lowercase , __lowercase = self.heap[0] self._bubble_down(lowercase__ ) return elem def SCREAMING_SNAKE_CASE ( self : Optional[Any] ,lowercase__ : T ,lowercase__ : int ): # Update the weight of the given key __lowercase = self.position_map[elem] __lowercase = (elem, weight) if position > 0: __lowercase = get_parent_position(lowercase__ ) __lowercase , __lowercase = self.heap[parent_position] if parent_weight > weight: self._bubble_up(lowercase__ ) else: self._bubble_down(lowercase__ ) else: self._bubble_down(lowercase__ ) def SCREAMING_SNAKE_CASE ( self : Dict ,lowercase__ : T ): # Place a node at the proper position (upward movement) [to be used internally # only] __lowercase = self.position_map[elem] if curr_pos == 0: return None __lowercase = get_parent_position(lowercase__ ) __lowercase , __lowercase = self.heap[curr_pos] __lowercase , __lowercase = self.heap[parent_position] if parent_weight > weight: self._swap_nodes(lowercase__ ,lowercase__ ) return self._bubble_up(lowercase__ ) return None def SCREAMING_SNAKE_CASE ( self : List[str] ,lowercase__ : T ): # Place a node at the proper position (downward movement) [to be used # internally only] __lowercase = self.position_map[elem] __lowercase , __lowercase = self.heap[curr_pos] __lowercase = get_child_left_position(lowercase__ ) __lowercase = get_child_right_position(lowercase__ ) if child_left_position < self.elements and child_right_position < self.elements: __lowercase , __lowercase = self.heap[child_left_position] __lowercase , __lowercase = self.heap[child_right_position] if child_right_weight < child_left_weight and child_right_weight < weight: self._swap_nodes(lowercase__ ,lowercase__ ) return self._bubble_down(lowercase__ ) if child_left_position < self.elements: __lowercase , __lowercase = self.heap[child_left_position] if child_left_weight < weight: self._swap_nodes(lowercase__ ,lowercase__ ) return self._bubble_down(lowercase__ ) else: return None if child_right_position < self.elements: __lowercase , __lowercase = self.heap[child_right_position] if child_right_weight < weight: self._swap_nodes(lowercase__ ,lowercase__ ) return self._bubble_down(lowercase__ ) return None def SCREAMING_SNAKE_CASE ( self : Optional[int] ,lowercase__ : int ,lowercase__ : int ): # Swap the nodes at the given positions __lowercase = self.heap[nodea_pos][0] __lowercase = self.heap[nodea_pos][0] __lowercase , __lowercase = ( self.heap[nodea_pos], self.heap[nodea_pos], ) __lowercase = nodea_pos __lowercase = nodea_pos class lowercase_ (Generic[T] ): """simple docstring""" def __init__( self : Any ): __lowercase = {} __lowercase = 0 def __repr__( self : Any ): return str(self.connections ) def __len__( self : Any ): return self.nodes def SCREAMING_SNAKE_CASE ( self : Dict ,lowercase__ : T ): # Add a node in the graph if it is not in the graph if node not in self.connections: __lowercase = {} self.nodes += 1 def SCREAMING_SNAKE_CASE ( self : Optional[Any] ,lowercase__ : T ,lowercase__ : T ,lowercase__ : int ): # Add an edge between 2 nodes in the graph self.add_node(lowercase__ ) self.add_node(lowercase__ ) __lowercase = weight __lowercase = weight def _A ( A__ , ): """simple docstring""" __lowercase = {node: maxsize for node in graph.connections} __lowercase = {node: None for node in graph.connections} __lowercase = MinPriorityQueue() for node, weight in dist.items(): priority_queue.push(A__ , A__ ) if priority_queue.is_empty(): return dist, parent # initialization __lowercase = priority_queue.extract_min() __lowercase = 0 for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __lowercase = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(A__ , dist[neighbour] ) __lowercase = node # running prim's algorithm while not priority_queue.is_empty(): __lowercase = priority_queue.extract_min() for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __lowercase = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(A__ , dist[neighbour] ) __lowercase = node return dist, parent
104
"""simple docstring""" import warnings from ..trainer import Trainer from ..utils import logging lowercase_ = logging.get_logger(__name__) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a=None , **_a ): warnings.warn( '''`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` ''' '''instead.''' , _a , ) super().__init__(args=_a , **_a )
45
0
"""simple docstring""" import argparse import os import torch from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) a : List[Any] = { '''sample_size''': 32, '''in_channels''': 3, '''out_channels''': 3, '''layers_per_block''': 2, '''num_class_embeds''': 1000, '''block_out_channels''': [32, 64], '''attention_head_dim''': 8, '''down_block_types''': [ '''ResnetDownsampleBlock2D''', '''AttnDownBlock2D''', ], '''up_block_types''': [ '''AttnUpBlock2D''', '''ResnetUpsampleBlock2D''', ], '''resnet_time_scale_shift''': '''scale_shift''', '''upsample_type''': '''resnet''', '''downsample_type''': '''resnet''', } a : int = { '''sample_size''': 64, '''in_channels''': 3, '''out_channels''': 3, '''layers_per_block''': 3, '''num_class_embeds''': 1000, '''block_out_channels''': [192, 192 * 2, 192 * 3, 192 * 4], '''attention_head_dim''': 64, '''down_block_types''': [ '''ResnetDownsampleBlock2D''', '''AttnDownBlock2D''', '''AttnDownBlock2D''', '''AttnDownBlock2D''', ], '''up_block_types''': [ '''AttnUpBlock2D''', '''AttnUpBlock2D''', '''AttnUpBlock2D''', '''ResnetUpsampleBlock2D''', ], '''resnet_time_scale_shift''': '''scale_shift''', '''upsample_type''': '''resnet''', '''downsample_type''': '''resnet''', } a : Tuple = { '''sample_size''': 256, '''in_channels''': 3, '''out_channels''': 3, '''layers_per_block''': 2, '''num_class_embeds''': None, '''block_out_channels''': [256, 256, 256 * 2, 256 * 2, 256 * 4, 256 * 4], '''attention_head_dim''': 64, '''down_block_types''': [ '''ResnetDownsampleBlock2D''', '''ResnetDownsampleBlock2D''', '''ResnetDownsampleBlock2D''', '''AttnDownBlock2D''', '''AttnDownBlock2D''', '''AttnDownBlock2D''', ], '''up_block_types''': [ '''AttnUpBlock2D''', '''AttnUpBlock2D''', '''AttnUpBlock2D''', '''ResnetUpsampleBlock2D''', '''ResnetUpsampleBlock2D''', '''ResnetUpsampleBlock2D''', ], '''resnet_time_scale_shift''': '''default''', '''upsample_type''': '''resnet''', '''downsample_type''': '''resnet''', } a : int = { '''num_train_timesteps''': 40, '''sigma_min''': 0.002, '''sigma_max''': 80.0, } a : Tuple = { '''num_train_timesteps''': 201, '''sigma_min''': 0.002, '''sigma_max''': 80.0, } a : List[Any] = { '''num_train_timesteps''': 151, '''sigma_min''': 0.002, '''sigma_max''': 80.0, } def _SCREAMING_SNAKE_CASE ( _lowercase : Any ) ->Union[str, Any]: '''simple docstring''' if isinstance(_lowercase , _lowercase ): return v if v.lower() in ("yes", "true", "t", "y", "1"): return True elif v.lower() in ("no", "false", "f", "n", "0"): return False else: raise argparse.ArgumentTypeError("boolean value expected" ) def _SCREAMING_SNAKE_CASE ( _lowercase : Dict , _lowercase : Union[str, Any] , _lowercase : List[Any] , _lowercase : Tuple , _lowercase : Any=False ) ->str: '''simple docstring''' a : Dict = checkpoint[F"""{old_prefix}.in_layers.0.weight"""] a : List[str] = checkpoint[F"""{old_prefix}.in_layers.0.bias"""] a : List[Any] = checkpoint[F"""{old_prefix}.in_layers.2.weight"""] a : str = checkpoint[F"""{old_prefix}.in_layers.2.bias"""] a : Optional[int] = checkpoint[F"""{old_prefix}.emb_layers.1.weight"""] a : str = checkpoint[F"""{old_prefix}.emb_layers.1.bias"""] a : List[str] = checkpoint[F"""{old_prefix}.out_layers.0.weight"""] a : Dict = checkpoint[F"""{old_prefix}.out_layers.0.bias"""] a : List[Any] = checkpoint[F"""{old_prefix}.out_layers.3.weight"""] a : Dict = checkpoint[F"""{old_prefix}.out_layers.3.bias"""] if has_skip: a : str = checkpoint[F"""{old_prefix}.skip_connection.weight"""] a : List[Any] = checkpoint[F"""{old_prefix}.skip_connection.bias"""] return new_checkpoint def _SCREAMING_SNAKE_CASE ( _lowercase : str , _lowercase : str , _lowercase : int , _lowercase : Tuple , _lowercase : List[str]=None ) ->Tuple: '''simple docstring''' a, a, a : Any = checkpoint[F"""{old_prefix}.qkv.weight"""].chunk(3 , dim=0 ) a, a, a : int = checkpoint[F"""{old_prefix}.qkv.bias"""].chunk(3 , dim=0 ) a : Tuple = checkpoint[F"""{old_prefix}.norm.weight"""] a : Dict = checkpoint[F"""{old_prefix}.norm.bias"""] a : Dict = weight_q.squeeze(-1 ).squeeze(-1 ) a : Optional[int] = bias_q.squeeze(-1 ).squeeze(-1 ) a : Tuple = weight_k.squeeze(-1 ).squeeze(-1 ) a : Optional[int] = bias_k.squeeze(-1 ).squeeze(-1 ) a : List[Any] = weight_v.squeeze(-1 ).squeeze(-1 ) a : Optional[Any] = bias_v.squeeze(-1 ).squeeze(-1 ) a : List[str] = ( checkpoint[F"""{old_prefix}.proj_out.weight"""].squeeze(-1 ).squeeze(-1 ) ) a : Optional[int] = checkpoint[F"""{old_prefix}.proj_out.bias"""].squeeze(-1 ).squeeze(-1 ) return new_checkpoint def _SCREAMING_SNAKE_CASE ( _lowercase : str , _lowercase : Any ) ->Tuple: '''simple docstring''' a : str = torch.load(_lowercase , map_location="cpu" ) a : List[Any] = {} a : List[str] = checkpoint["time_embed.0.weight"] a : Tuple = checkpoint["time_embed.0.bias"] a : List[Any] = checkpoint["time_embed.2.weight"] a : Dict = checkpoint["time_embed.2.bias"] if unet_config["num_class_embeds"] is not None: a : List[Any] = checkpoint["label_emb.weight"] a : Any = checkpoint["input_blocks.0.0.weight"] a : Optional[int] = checkpoint["input_blocks.0.0.bias"] a : Dict = unet_config["down_block_types"] a : Union[str, Any] = unet_config["layers_per_block"] a : int = unet_config["attention_head_dim"] a : Optional[Any] = unet_config["block_out_channels"] a : Any = 1 a : Union[str, Any] = channels_list[0] for i, layer_type in enumerate(_lowercase ): a : Optional[Any] = channels_list[i] a : str = current_channels != prev_channels if layer_type == "ResnetDownsampleBlock2D": for j in range(_lowercase ): a : List[str] = F"""down_blocks.{i}.resnets.{j}""" a : List[str] = F"""input_blocks.{current_layer}.0""" a : Union[str, Any] = True if j == 0 and downsample_block_has_skip else False a : Union[str, Any] = convert_resnet(_lowercase , _lowercase , _lowercase , _lowercase , has_skip=_lowercase ) current_layer += 1 elif layer_type == "AttnDownBlock2D": for j in range(_lowercase ): a : int = F"""down_blocks.{i}.resnets.{j}""" a : Optional[Any] = F"""input_blocks.{current_layer}.0""" a : Tuple = True if j == 0 and downsample_block_has_skip else False a : Union[str, Any] = convert_resnet(_lowercase , _lowercase , _lowercase , _lowercase , has_skip=_lowercase ) a : Any = F"""down_blocks.{i}.attentions.{j}""" a : Optional[Any] = F"""input_blocks.{current_layer}.1""" a : Optional[int] = convert_attention( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ) current_layer += 1 if i != len(_lowercase ) - 1: a : List[Any] = F"""down_blocks.{i}.downsamplers.0""" a : Any = F"""input_blocks.{current_layer}.0""" a : Union[str, Any] = convert_resnet(_lowercase , _lowercase , _lowercase , _lowercase ) current_layer += 1 a : Dict = current_channels # hardcoded the mid-block for now a : Dict = "mid_block.resnets.0" a : Any = "middle_block.0" a : Optional[int] = convert_resnet(_lowercase , _lowercase , _lowercase , _lowercase ) a : Optional[Any] = "mid_block.attentions.0" a : Tuple = "middle_block.1" a : int = convert_attention(_lowercase , _lowercase , _lowercase , _lowercase , _lowercase ) a : List[str] = "mid_block.resnets.1" a : Optional[int] = "middle_block.2" a : Optional[Any] = convert_resnet(_lowercase , _lowercase , _lowercase , _lowercase ) a : Optional[int] = 0 a : int = unet_config["up_block_types"] for i, layer_type in enumerate(_lowercase ): if layer_type == "ResnetUpsampleBlock2D": for j in range(layers_per_block + 1 ): a : Dict = F"""up_blocks.{i}.resnets.{j}""" a : List[Any] = F"""output_blocks.{current_layer}.0""" a : List[Any] = convert_resnet(_lowercase , _lowercase , _lowercase , _lowercase , has_skip=_lowercase ) current_layer += 1 if i != len(_lowercase ) - 1: a : List[Any] = F"""up_blocks.{i}.upsamplers.0""" a : Optional[Any] = F"""output_blocks.{current_layer-1}.1""" a : Any = convert_resnet(_lowercase , _lowercase , _lowercase , _lowercase ) elif layer_type == "AttnUpBlock2D": for j in range(layers_per_block + 1 ): a : Optional[Any] = F"""up_blocks.{i}.resnets.{j}""" a : Union[str, Any] = F"""output_blocks.{current_layer}.0""" a : Tuple = convert_resnet(_lowercase , _lowercase , _lowercase , _lowercase , has_skip=_lowercase ) a : Optional[Any] = F"""up_blocks.{i}.attentions.{j}""" a : List[Any] = F"""output_blocks.{current_layer}.1""" a : Optional[Any] = convert_attention( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ) current_layer += 1 if i != len(_lowercase ) - 1: a : Any = F"""up_blocks.{i}.upsamplers.0""" a : Union[str, Any] = F"""output_blocks.{current_layer-1}.2""" a : Optional[int] = convert_resnet(_lowercase , _lowercase , _lowercase , _lowercase ) a : Any = checkpoint["out.0.weight"] a : int = checkpoint["out.0.bias"] a : int = checkpoint["out.2.weight"] a : Dict = checkpoint["out.2.bias"] return new_checkpoint if __name__ == "__main__": a : Optional[int] = argparse.ArgumentParser() parser.add_argument('''--unet_path''', default=None, type=str, required=True, help='''Path to the unet.pt to convert.''') parser.add_argument( '''--dump_path''', default=None, type=str, required=True, help='''Path to output the converted UNet model.''' ) parser.add_argument('''--class_cond''', default=True, type=str, help='''Whether the model is class-conditional.''') a : List[str] = parser.parse_args() a : Tuple = strabool(args.class_cond) a : int = os.path.basename(args.unet_path) print(F'''Checkpoint: {ckpt_name}''') # Get U-Net config if "imagenet64" in ckpt_name: a : str = IMAGENET_64_UNET_CONFIG elif "256" in ckpt_name and (("bedroom" in ckpt_name) or ("cat" in ckpt_name)): a : Optional[int] = LSUN_256_UNET_CONFIG elif "test" in ckpt_name: a : Union[str, Any] = TEST_UNET_CONFIG else: raise ValueError(F'''Checkpoint type {ckpt_name} is not currently supported.''') if not args.class_cond: a : Optional[int] = None a : Optional[int] = con_pt_to_diffuser(args.unet_path, unet_config) a : Union[str, Any] = UNetaDModel(**unet_config) image_unet.load_state_dict(converted_unet_ckpt) # Get scheduler config if "cd" in ckpt_name or "test" in ckpt_name: a : List[str] = CD_SCHEDULER_CONFIG elif "ct" in ckpt_name and "imagenet64" in ckpt_name: a : Optional[int] = CT_IMAGENET_64_SCHEDULER_CONFIG elif "ct" in ckpt_name and "256" in ckpt_name and (("bedroom" in ckpt_name) or ("cat" in ckpt_name)): a : Any = CT_LSUN_256_SCHEDULER_CONFIG else: raise ValueError(F'''Checkpoint type {ckpt_name} is not currently supported.''') a : int = CMStochasticIterativeScheduler(**scheduler_config) a : int = ConsistencyModelPipeline(unet=image_unet, scheduler=cm_scheduler) consistency_model.save_pretrained(args.dump_path)
105
"""simple docstring""" import math def lowercase ( lowerCAmelCase__ : list , lowerCAmelCase__ : int ) -> int: __a = len(lowerCAmelCase__ ) __a = int(math.floor(math.sqrt(lowerCAmelCase__ ) ) ) __a = 0 while arr[min(lowerCAmelCase__ , lowerCAmelCase__ ) - 1] < x: __a = step step += int(math.floor(math.sqrt(lowerCAmelCase__ ) ) ) if prev >= n: return -1 while arr[prev] < x: __a = prev + 1 if prev == min(lowerCAmelCase__ , lowerCAmelCase__ ): return -1 if arr[prev] == x: return prev return -1 if __name__ == "__main__": lowercase_ = input("Enter numbers separated by a comma:\n").strip() lowercase_ = [int(item) for item in user_input.split(",")] lowercase_ = int(input("Enter the number to be searched:\n")) lowercase_ = jump_search(arr, x) if res == -1: print("Number not found!") else: print(F'''Number {x} is at index {res}''')
45
0
"""simple docstring""" from typing import Any class SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : Any ,lowercase_ : Any ): lowerCAmelCase__ : List[str] = data lowerCAmelCase__ : Any = None class SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self : List[str] ): lowerCAmelCase__ : Any = None def __lowerCAmelCase ( self : str ): lowerCAmelCase__ : Optional[Any] = self.head while temp is not None: print(temp.data ,end=''' ''' ) lowerCAmelCase__ : Union[str, Any] = temp.next print() def __lowerCAmelCase ( self : Dict ,lowercase_ : Any ): lowerCAmelCase__ : Union[str, Any] = Node(lowercase_ ) lowerCAmelCase__ : Any = self.head lowerCAmelCase__ : Union[str, Any] = new_node def __lowerCAmelCase ( self : Optional[Any] ,lowercase_ : Dict ,lowercase_ : List[str] ): if node_data_a == node_data_a: return else: lowerCAmelCase__ : Optional[int] = self.head while node_a is not None and node_a.data != node_data_a: lowerCAmelCase__ : Optional[Any] = node_a.next lowerCAmelCase__ : Dict = self.head while node_a is not None and node_a.data != node_data_a: lowerCAmelCase__ : List[Any] = node_a.next if node_a is None or node_a is None: return lowerCAmelCase__ ,lowerCAmelCase__ : Optional[Any] = node_a.data, node_a.data if __name__ == "__main__": __UpperCamelCase : Union[str, Any] = LinkedList() for i in range(5, 0, -1): ll.push(i) ll.print_list() ll.swap_nodes(1, 4) print('''After swapping''') ll.print_list()
106
"""simple docstring""" lowercase_ = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] lowercase_ = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] lowercase_ = { 0: "Sunday", 1: "Monday", 2: "Tuesday", 3: "Wednesday", 4: "Thursday", 5: "Friday", 6: "Saturday", } def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : int , lowerCAmelCase__ : int ) -> str: assert len(str(lowerCAmelCase__ ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 12, "month should be between 1 to 12" assert 1 <= day <= 31, "day should be between 1 to 31" # Doomsday algorithm: __a = year // 100 __a = (5 * (century % 4) + 2) % 7 __a = year % 100 __a = centurian % 12 __a = ( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 __a = ( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 400) == 0) else DOOMSDAY_LEAP[month - 1] ) __a = (dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
45
0
import inspect import unittest from transformers import RegNetConfig, is_flax_available from transformers.testing_utils import require_flax, slow from transformers.utils import cached_property, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.models.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class snake_case__ (unittest.TestCase ): """simple docstring""" def __init__( self : int , __lowerCamelCase : List[Any] , __lowerCamelCase : Tuple=3 , __lowerCamelCase : List[str]=32 , __lowerCamelCase : str=3 , __lowerCamelCase : Optional[int]=10 , __lowerCamelCase : str=[10, 20, 30, 40] , __lowerCamelCase : Tuple=[1, 1, 2, 1] , __lowerCamelCase : str=True , __lowerCamelCase : List[str]=True , __lowerCamelCase : Optional[int]="relu" , __lowerCamelCase : List[Any]=3 , __lowerCamelCase : Optional[int]=None , ) -> Any: 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(__lowerCamelCase ) def __UpperCAmelCase ( self : List[str] ) -> Dict: a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) a = self.get_config() return config, pixel_values def __UpperCAmelCase ( self : int ) -> Tuple: 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 , image_size=self.image_size , ) def __UpperCAmelCase ( self : List[str] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Any ) -> Dict: a = FlaxRegNetModel(config=__lowerCamelCase ) a = model(__lowerCamelCase ) # Output shape (b, c, h, w) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def __UpperCAmelCase ( self : Tuple , __lowerCamelCase : Tuple , __lowerCamelCase : List[Any] ) -> Optional[int]: a = self.num_labels a = FlaxRegNetForImageClassification(config=__lowerCamelCase ) a = model(__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCAmelCase ( self : int ) -> List[Any]: a = self.prepare_config_and_inputs() a , a = config_and_inputs a = {"pixel_values": pixel_values} return config, inputs_dict @require_flax class snake_case__ (_UpperCamelCase , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = (FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else () SCREAMING_SNAKE_CASE_ : str = False SCREAMING_SNAKE_CASE_ : Optional[Any] = False SCREAMING_SNAKE_CASE_ : List[str] = False def __UpperCAmelCase ( self : Any ) -> None: a = FlaxRegNetModelTester(self ) a = ConfigTester(self , config_class=__lowerCamelCase , has_text_modality=__lowerCamelCase ) def __UpperCAmelCase ( self : int ) -> Dict: self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def __UpperCAmelCase ( self : str ) -> Optional[Any]: return def __UpperCAmelCase ( self : Tuple ) -> List[Any]: a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCamelCase ) def __UpperCAmelCase ( self : List[Any] ) -> Tuple: a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase ) @unittest.skip(reason="RegNet does not use inputs_embeds" ) def __UpperCAmelCase ( self : Optional[Any] ) -> Tuple: pass @unittest.skip(reason="RegNet does not support input and output embeddings" ) def __UpperCAmelCase ( self : Tuple ) -> Dict: pass def __UpperCAmelCase ( self : Dict ) -> Optional[int]: 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.__call__ ) # 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 : Dict ) -> Tuple: def check_hidden_states_output(__lowerCamelCase : Dict , __lowerCamelCase : List[str] , __lowerCamelCase : List[str] ): a = model_class(__lowerCamelCase ) a = model(**self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) a = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states a = self.model_tester.num_stages self.assertEqual(len(__lowerCamelCase ) , expected_num_stages + 1 ) a , a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a = True check_hidden_states_output(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] a = True check_hidden_states_output(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) def __UpperCAmelCase ( self : Dict ) -> str: a , a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): a = self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) a = model_class(__lowerCamelCase ) @jax.jit def model_jitted(__lowerCamelCase : List[str] , **__lowerCamelCase : List[Any] ): return model(pixel_values=__lowerCamelCase , **__lowerCamelCase ) with self.subTest("JIT Enabled" ): a = model_jitted(**__lowerCamelCase ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): a = model_jitted(**__lowerCamelCase ).to_tuple() self.assertEqual(len(__lowerCamelCase ) , len(__lowerCamelCase ) ) for jitted_output, output in zip(__lowerCamelCase , __lowerCamelCase ): self.assertEqual(jitted_output.shape , output.shape ) def __magic_name__ ( ): '''simple docstring''' a = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_flax class snake_case__ (unittest.TestCase ): """simple docstring""" @cached_property def __UpperCAmelCase ( self : Any ) -> List[str]: return AutoImageProcessor.from_pretrained("facebook/regnet-y-040" ) if is_vision_available() else None @slow def __UpperCAmelCase ( self : List[Any] ) -> List[str]: a = FlaxRegNetForImageClassification.from_pretrained("facebook/regnet-y-040" ) a = self.default_image_processor a = prepare_img() a = image_processor(images=__lowerCamelCase , return_tensors="np" ) a = model(**__lowerCamelCase ) # verify the logits a = (1, 10_00) self.assertEqual(outputs.logits.shape , __lowerCamelCase ) a = jnp.array([-0.4_180, -1.5_051, -3.4_836] ) self.assertTrue(jnp.allclose(outputs.logits[0, :3] , __lowerCamelCase , atol=1e-4 ) )
107
"""simple docstring""" def lowercase ( lowerCAmelCase__ : list ) -> bool: if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise ValueError('''Input series is not valid, valid series - [2, 4, 6]''' ) if len(lowerCAmelCase__ ) == 0: raise ValueError('''Input list must be a non empty list''' ) if len(lowerCAmelCase__ ) == 1: return True __a = series[1] - series[0] for index in range(len(lowerCAmelCase__ ) - 1 ): if series[index + 1] - series[index] != common_diff: return False return True def lowercase ( lowerCAmelCase__ : list ) -> float: if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise ValueError('''Input series is not valid, valid series - [2, 4, 6]''' ) if len(lowerCAmelCase__ ) == 0: raise ValueError('''Input list must be a non empty list''' ) __a = 0 for val in series: answer += val return answer / len(lowerCAmelCase__ ) if __name__ == "__main__": import doctest doctest.testmod()
45
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available lowerCAmelCase__ = { '''configuration_bloom''': ['''BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BloomConfig''', '''BloomOnnxConfig'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = ['''BloomTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ '''BLOOM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BloomForCausalLM''', '''BloomModel''', '''BloomPreTrainedModel''', '''BloomForSequenceClassification''', '''BloomForTokenClassification''', '''BloomForQuestionAnswering''', ] if TYPE_CHECKING: from .configuration_bloom import BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP, BloomConfig, BloomOnnxConfig try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bloom_fast import BloomTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bloom import ( BLOOM_PRETRAINED_MODEL_ARCHIVE_LIST, BloomForCausalLM, BloomForQuestionAnswering, BloomForSequenceClassification, BloomForTokenClassification, BloomModel, BloomPreTrainedModel, ) else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
108
"""simple docstring""" from argparse import ArgumentParser, Namespace from ..utils import logging from . import BaseTransformersCLICommand def lowercase ( lowerCAmelCase__ : Namespace ) -> Tuple: return ConvertCommand( args.model_type , args.tf_checkpoint , args.pytorch_dump_output , args.config , args.finetuning_task_name ) lowercase_ = "\ntransformers can only be used from the commandline to convert TensorFlow models in PyTorch, In that case, it requires\nTensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installation instructions.\n" class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' @staticmethod def __UpperCAmelCase ( _a ): __a = parser.add_parser( '''convert''' , help='''CLI tool to run convert model from original author checkpoints to Transformers PyTorch checkpoints.''' , ) train_parser.add_argument('''--model_type''' , type=_a , required=_a , help='''Model\'s type.''' ) train_parser.add_argument( '''--tf_checkpoint''' , type=_a , required=_a , help='''TensorFlow checkpoint path or folder.''' ) train_parser.add_argument( '''--pytorch_dump_output''' , type=_a , required=_a , help='''Path to the PyTorch saved model output.''' ) train_parser.add_argument('''--config''' , type=_a , default='''''' , help='''Configuration file path or folder.''' ) train_parser.add_argument( '''--finetuning_task_name''' , type=_a , default=_a , help='''Optional fine-tuning task name if the TF model was a finetuned model.''' , ) train_parser.set_defaults(func=_a ) def __init__( self , _a , _a , _a , _a , _a , *_a , ): __a = logging.get_logger('''transformers-cli/converting''' ) self._logger.info(f'''Loading model {model_type}''' ) __a = model_type __a = tf_checkpoint __a = pytorch_dump_output __a = config __a = finetuning_task_name def __UpperCAmelCase ( self ): if self._model_type == "albert": try: from ..models.albert.convert_albert_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "bert": try: from ..models.bert.convert_bert_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "funnel": try: from ..models.funnel.convert_funnel_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "t5": try: from ..models.ta.convert_ta_original_tf_checkpoint_to_pytorch import convert_tf_checkpoint_to_pytorch except ImportError: raise ImportError(_a ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "gpt": from ..models.openai.convert_openai_original_tf_checkpoint_to_pytorch import ( convert_openai_checkpoint_to_pytorch, ) convert_openai_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "transfo_xl": try: from ..models.transfo_xl.convert_transfo_xl_original_tf_checkpoint_to_pytorch import ( convert_transfo_xl_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) if "ckpt" in self._tf_checkpoint.lower(): __a = self._tf_checkpoint __a = '''''' else: __a = self._tf_checkpoint __a = '''''' convert_transfo_xl_checkpoint_to_pytorch( _a , self._config , self._pytorch_dump_output , _a ) elif self._model_type == "gpt2": try: from ..models.gpta.convert_gpta_original_tf_checkpoint_to_pytorch import ( convert_gpta_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_gpta_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "xlnet": try: from ..models.xlnet.convert_xlnet_original_tf_checkpoint_to_pytorch import ( convert_xlnet_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_xlnet_checkpoint_to_pytorch( self._tf_checkpoint , self._config , self._pytorch_dump_output , self._finetuning_task_name ) elif self._model_type == "xlm": from ..models.xlm.convert_xlm_original_pytorch_checkpoint_to_pytorch import ( convert_xlm_checkpoint_to_pytorch, ) convert_xlm_checkpoint_to_pytorch(self._tf_checkpoint , self._pytorch_dump_output ) elif self._model_type == "lxmert": from ..models.lxmert.convert_lxmert_original_tf_checkpoint_to_pytorch import ( convert_lxmert_checkpoint_to_pytorch, ) convert_lxmert_checkpoint_to_pytorch(self._tf_checkpoint , self._pytorch_dump_output ) elif self._model_type == "rembert": from ..models.rembert.convert_rembert_tf_checkpoint_to_pytorch import ( convert_rembert_tf_checkpoint_to_pytorch, ) convert_rembert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) else: raise ValueError( '''--model_type should be selected in the list [bert, gpt, gpt2, t5, transfo_xl, xlnet, xlm, lxmert]''' )
45
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available A: Optional[Any] = { "configuration_tapas": ["TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP", "TapasConfig"], "tokenization_tapas": ["TapasTokenizer"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A: Optional[int] = [ "TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST", "TapasForMaskedLM", "TapasForQuestionAnswering", "TapasForSequenceClassification", "TapasModel", "TapasPreTrainedModel", "load_tf_weights_in_tapas", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A: List[str] = [ "TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST", "TFTapasForMaskedLM", "TFTapasForQuestionAnswering", "TFTapasForSequenceClassification", "TFTapasModel", "TFTapasPreTrainedModel", ] if TYPE_CHECKING: from .configuration_tapas import TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP, TapasConfig from .tokenization_tapas import TapasTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tapas import ( TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasPreTrainedModel, load_tf_weights_in_tapas, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_tapas import ( TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST, TFTapasForMaskedLM, TFTapasForQuestionAnswering, TFTapasForSequenceClassification, TFTapasModel, TFTapasPreTrainedModel, ) else: import sys A: Optional[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
109
"""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 lowercase_ = logging.get_logger(__name__) lowercase_ = { "microsoft/beit-base-patch16-224-pt22k": ( "https://huggingface.co/microsoft/beit-base-patch16-224-pt22k/resolve/main/config.json" ), # See all BEiT models at https://huggingface.co/models?filter=beit } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : List[str] = 'beit' def __init__( self , _a=8_192 , _a=768 , _a=12 , _a=12 , _a=3_072 , _a="gelu" , _a=0.0 , _a=0.0 , _a=0.02 , _a=1E-12 , _a=224 , _a=16 , _a=3 , _a=False , _a=False , _a=False , _a=False , _a=0.1 , _a=0.1 , _a=True , _a=[3, 5, 7, 11] , _a=[1, 2, 3, 6] , _a=True , _a=0.4 , _a=256 , _a=1 , _a=False , _a=255 , **_a , ): super().__init__(**_a ) __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 = initializer_range __a = layer_norm_eps __a = image_size __a = patch_size __a = num_channels __a = use_mask_token __a = use_absolute_position_embeddings __a = use_relative_position_bias __a = use_shared_relative_position_bias __a = layer_scale_init_value __a = drop_path_rate __a = use_mean_pooling # decode head attributes (semantic segmentation) __a = out_indices __a = pool_scales # auxiliary head attributes (semantic segmentation) __a = use_auxiliary_head __a = auxiliary_loss_weight __a = auxiliary_channels __a = auxiliary_num_convs __a = auxiliary_concat_input __a = semantic_loss_ignore_index class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : List[Any] = version.parse('1.11' ) @property def __UpperCAmelCase ( self ): return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def __UpperCAmelCase ( self ): return 1E-4
45
0
from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class _a ( UpperCamelCase__ ): _lowercase : Dict = ['''image_processor''', '''tokenizer'''] _lowercase : Union[str, Any] = '''BlipImageProcessor''' _lowercase : Tuple = '''AutoTokenizer''' def __init__( self: List[str] , UpperCamelCase_: List[str] , UpperCamelCase_: List[str] ) -> Any: """simple docstring""" lowercase__ = False super().__init__(UpperCamelCase_ , UpperCamelCase_ ) lowercase__ = self.image_processor def __call__( self: Tuple , UpperCamelCase_: ImageInput = None , UpperCamelCase_: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , UpperCamelCase_: bool = True , UpperCamelCase_: Union[bool, str, PaddingStrategy] = False , UpperCamelCase_: Union[bool, str, TruncationStrategy] = None , UpperCamelCase_: Optional[int] = None , UpperCamelCase_: int = 0 , UpperCamelCase_: Optional[int] = None , UpperCamelCase_: Optional[bool] = None , UpperCamelCase_: bool = False , UpperCamelCase_: bool = False , UpperCamelCase_: bool = False , UpperCamelCase_: bool = False , UpperCamelCase_: bool = False , UpperCamelCase_: bool = True , UpperCamelCase_: Optional[Union[str, TensorType]] = None , **UpperCamelCase_: List[Any] , ) -> BatchEncoding: """simple docstring""" if images is None and text is None: raise ValueError('''You have to specify either images or text.''' ) # Get only text if images is None: lowercase__ = self.tokenizer lowercase__ = self.tokenizer( text=UpperCamelCase_ , add_special_tokens=UpperCamelCase_ , padding=UpperCamelCase_ , truncation=UpperCamelCase_ , max_length=UpperCamelCase_ , stride=UpperCamelCase_ , pad_to_multiple_of=UpperCamelCase_ , return_attention_mask=UpperCamelCase_ , return_overflowing_tokens=UpperCamelCase_ , return_special_tokens_mask=UpperCamelCase_ , return_offsets_mapping=UpperCamelCase_ , return_token_type_ids=UpperCamelCase_ , return_length=UpperCamelCase_ , verbose=UpperCamelCase_ , return_tensors=UpperCamelCase_ , **UpperCamelCase_ , ) return text_encoding # add pixel_values lowercase__ = self.image_processor(UpperCamelCase_ , return_tensors=UpperCamelCase_ ) if text is not None: lowercase__ = self.tokenizer( text=UpperCamelCase_ , add_special_tokens=UpperCamelCase_ , padding=UpperCamelCase_ , truncation=UpperCamelCase_ , max_length=UpperCamelCase_ , stride=UpperCamelCase_ , pad_to_multiple_of=UpperCamelCase_ , return_attention_mask=UpperCamelCase_ , return_overflowing_tokens=UpperCamelCase_ , return_special_tokens_mask=UpperCamelCase_ , return_offsets_mapping=UpperCamelCase_ , return_token_type_ids=UpperCamelCase_ , return_length=UpperCamelCase_ , verbose=UpperCamelCase_ , return_tensors=UpperCamelCase_ , **UpperCamelCase_ , ) else: lowercase__ = None if text_encoding is not None: encoding_image_processor.update(UpperCamelCase_ ) return encoding_image_processor def lowerCamelCase_ ( self: List[str] , *UpperCamelCase_: Optional[Any] , **UpperCamelCase_: Optional[int] ) -> Any: """simple docstring""" return self.tokenizer.batch_decode(*UpperCamelCase_ , **UpperCamelCase_ ) def lowerCamelCase_ ( self: List[str] , *UpperCamelCase_: Optional[Any] , **UpperCamelCase_: Union[str, Any] ) -> Any: """simple docstring""" return self.tokenizer.decode(*UpperCamelCase_ , **UpperCamelCase_ ) @property # Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names def lowerCamelCase_ ( self: Dict ) -> int: """simple docstring""" lowercase__ = self.tokenizer.model_input_names lowercase__ = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
110
"""simple docstring""" def lowercase ( lowerCAmelCase__ : str ) -> list: if n_term == "": return [] __a = [] for temp in range(int(lowerCAmelCase__ ) ): series.append(f'''1/{temp + 1}''' if series else '''1''' ) return series if __name__ == "__main__": lowercase_ = input("Enter the last number (nth term) of the Harmonic Series") print("Formula of Harmonic Series => 1+1/2+1/3 ..... 1/n") print(harmonic_series(nth_term))
45
0
"""simple docstring""" import argparse import json import os import sys import tempfile import unittest from argparse import Namespace from dataclasses import dataclass, field from enum import Enum from pathlib import Path from typing import List, Literal, Optional import yaml from transformers import HfArgumentParser, TrainingArguments from transformers.hf_argparser import make_choice_type_function, string_to_bool # Since Python 3.10, we can use the builtin `|` operator for Union types # See PEP 604: https://peps.python.org/pep-0604 UpperCAmelCase__ = sys.version_info >= (3, 10) def _UpperCAmelCase ( __lowerCamelCase : Optional[Any]=None , __lowerCamelCase : Any=None ) -> Any: return field(default_factory=lambda: default , metadata=lowerCAmelCase__ ) @dataclass class lowerCAmelCase__ : __a = 42 __a = 42 __a = 42 __a = 42 @dataclass class lowerCAmelCase__ : __a = 42 __a = field(default="""toto""" , metadata={"""help""": """help message"""} ) @dataclass class lowerCAmelCase__ : __a = False __a = True __a = None class lowerCAmelCase__ ( __SCREAMING_SNAKE_CASE ): __a = 'titi' __a = 'toto' class lowerCAmelCase__ ( __SCREAMING_SNAKE_CASE ): __a = 'titi' __a = 'toto' __a = 42 @dataclass class lowerCAmelCase__ : __a = "toto" def lowercase ( self : List[str] ): _snake_case = BasicEnum(self.foo ) @dataclass class lowerCAmelCase__ : __a = "toto" def lowercase ( self : Tuple ): _snake_case = MixedTypeEnum(self.foo ) @dataclass class lowerCAmelCase__ : __a = None __a = field(default=__SCREAMING_SNAKE_CASE , metadata={"""help""": """help message"""} ) __a = None __a = list_field(default=[] ) __a = list_field(default=[] ) @dataclass class lowerCAmelCase__ : __a = list_field(default=[] ) __a = list_field(default=[1, 2, 3] ) __a = list_field(default=["""Hallo""", """Bonjour""", """Hello"""] ) __a = list_field(default=[0.1, 0.2, 0.3] ) @dataclass class lowerCAmelCase__ : __a = field() __a = field() __a = field() def lowercase ( self : Union[str, Any] ): _snake_case = BasicEnum(self.required_enum ) @dataclass class lowerCAmelCase__ : __a = 42 __a = field() __a = None __a = field(default="""toto""" , metadata={"""help""": """help message"""} ) __a = list_field(default=["""Hallo""", """Bonjour""", """Hello"""] ) if is_python_no_less_than_3_10: @dataclass class lowerCAmelCase__ : __a = False __a = True __a = None @dataclass class lowerCAmelCase__ : __a = None __a = field(default=__SCREAMING_SNAKE_CASE , metadata={"""help""": """help message"""} ) __a = None __a = list_field(default=[] ) __a = list_field(default=[] ) class lowerCAmelCase__ ( unittest.TestCase ): def lowercase ( self : str , _lowerCamelCase : str , _lowerCamelCase : Optional[Any] ): self.assertEqual(len(a._actions ) , len(b._actions ) ) for x, y in zip(a._actions , b._actions ): _snake_case = {k: v for k, v in vars(_a ).items() if k != '''container'''} _snake_case = {k: v for k, v in vars(_a ).items() if k != '''container'''} # Choices with mixed type have custom function as "type" # So we need to compare results directly for equality if xx.get('''choices''' , _a ) and yy.get('''choices''' , _a ): for expected_choice in yy["choices"] + xx["choices"]: self.assertEqual(xx['''type'''](_a ) , yy['''type'''](_a ) ) del xx["type"], yy["type"] self.assertEqual(_a , _a ) def lowercase ( self : Tuple ): _snake_case = HfArgumentParser(_a ) _snake_case = argparse.ArgumentParser() expected.add_argument('''--foo''' , type=_a , required=_a ) expected.add_argument('''--bar''' , type=_a , required=_a ) expected.add_argument('''--baz''' , type=_a , required=_a ) expected.add_argument('''--flag''' , type=_a , default=_a , const=_a , nargs='''?''' ) self.argparsersEqual(_a , _a ) _snake_case = ['''--foo''', '''1''', '''--baz''', '''quux''', '''--bar''', '''0.5'''] ((_snake_case ) , ) = parser.parse_args_into_dataclasses(_a , look_for_args_file=_a ) self.assertFalse(example.flag ) def lowercase ( self : Tuple ): _snake_case = HfArgumentParser(_a ) _snake_case = argparse.ArgumentParser() expected.add_argument('''--foo''' , default=42 , type=_a ) expected.add_argument('''--baz''' , default='''toto''' , type=_a , help='''help message''' ) self.argparsersEqual(_a , _a ) def lowercase ( self : List[str] ): _snake_case = argparse.ArgumentParser() expected.add_argument('''--foo''' , type=_a , default=_a , const=_a , nargs='''?''' ) expected.add_argument('''--baz''' , type=_a , default=_a , const=_a , nargs='''?''' ) # A boolean no_* argument always has to come after its "default: True" regular counter-part # and its default must be set to False expected.add_argument('''--no_baz''' , action='''store_false''' , default=_a , dest='''baz''' ) expected.add_argument('''--opt''' , type=_a , default=_a ) _snake_case = [WithDefaultBoolExample] if is_python_no_less_than_3_10: dataclass_types.append(_a ) for dataclass_type in dataclass_types: _snake_case = HfArgumentParser(_a ) self.argparsersEqual(_a , _a ) _snake_case = parser.parse_args([] ) self.assertEqual(_a , Namespace(foo=_a , baz=_a , opt=_a ) ) _snake_case = parser.parse_args(['''--foo''', '''--no_baz'''] ) self.assertEqual(_a , Namespace(foo=_a , baz=_a , opt=_a ) ) _snake_case = parser.parse_args(['''--foo''', '''--baz'''] ) self.assertEqual(_a , Namespace(foo=_a , baz=_a , opt=_a ) ) _snake_case = parser.parse_args(['''--foo''', '''True''', '''--baz''', '''True''', '''--opt''', '''True'''] ) self.assertEqual(_a , Namespace(foo=_a , baz=_a , opt=_a ) ) _snake_case = parser.parse_args(['''--foo''', '''False''', '''--baz''', '''False''', '''--opt''', '''False'''] ) self.assertEqual(_a , Namespace(foo=_a , baz=_a , opt=_a ) ) def lowercase ( self : Optional[int] ): _snake_case = HfArgumentParser(_a ) _snake_case = argparse.ArgumentParser() expected.add_argument( '''--foo''' , default='''toto''' , choices=['''titi''', '''toto''', 42] , type=make_choice_type_function(['''titi''', '''toto''', 42] ) , ) self.argparsersEqual(_a , _a ) _snake_case = parser.parse_args([] ) self.assertEqual(args.foo , '''toto''' ) _snake_case = parser.parse_args_into_dataclasses([] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.toto ) _snake_case = parser.parse_args(['''--foo''', '''titi'''] ) self.assertEqual(args.foo , '''titi''' ) _snake_case = parser.parse_args_into_dataclasses(['''--foo''', '''titi'''] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.titi ) _snake_case = parser.parse_args(['''--foo''', '''42'''] ) self.assertEqual(args.foo , 42 ) _snake_case = parser.parse_args_into_dataclasses(['''--foo''', '''42'''] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.fourtytwo ) def lowercase ( self : List[str] ): @dataclass class lowerCAmelCase__ : __a = "toto" _snake_case = HfArgumentParser(_a ) _snake_case = argparse.ArgumentParser() expected.add_argument( '''--foo''' , default='''toto''' , choices=('''titi''', '''toto''', 42) , type=make_choice_type_function(['''titi''', '''toto''', 42] ) , ) self.argparsersEqual(_a , _a ) _snake_case = parser.parse_args([] ) self.assertEqual(args.foo , '''toto''' ) _snake_case = parser.parse_args(['''--foo''', '''titi'''] ) self.assertEqual(args.foo , '''titi''' ) _snake_case = parser.parse_args(['''--foo''', '''42'''] ) self.assertEqual(args.foo , 42 ) def lowercase ( self : List[str] ): _snake_case = HfArgumentParser(_a ) _snake_case = argparse.ArgumentParser() expected.add_argument('''--foo_int''' , nargs='''+''' , default=[] , type=_a ) expected.add_argument('''--bar_int''' , nargs='''+''' , default=[1, 2, 3] , type=_a ) expected.add_argument('''--foo_str''' , nargs='''+''' , default=['''Hallo''', '''Bonjour''', '''Hello'''] , type=_a ) expected.add_argument('''--foo_float''' , nargs='''+''' , default=[0.1, 0.2, 0.3] , type=_a ) self.argparsersEqual(_a , _a ) _snake_case = parser.parse_args([] ) self.assertEqual( _a , Namespace(foo_int=[] , bar_int=[1, 2, 3] , foo_str=['''Hallo''', '''Bonjour''', '''Hello'''] , foo_float=[0.1, 0.2, 0.3] ) , ) _snake_case = parser.parse_args('''--foo_int 1 --bar_int 2 3 --foo_str a b c --foo_float 0.1 0.7'''.split() ) self.assertEqual(_a , Namespace(foo_int=[1] , bar_int=[2, 3] , foo_str=['''a''', '''b''', '''c'''] , foo_float=[0.1, 0.7] ) ) def lowercase ( self : str ): _snake_case = argparse.ArgumentParser() expected.add_argument('''--foo''' , default=_a , type=_a ) expected.add_argument('''--bar''' , default=_a , type=_a , help='''help message''' ) expected.add_argument('''--baz''' , default=_a , type=_a ) expected.add_argument('''--ces''' , nargs='''+''' , default=[] , type=_a ) expected.add_argument('''--des''' , nargs='''+''' , default=[] , type=_a ) _snake_case = [OptionalExample] if is_python_no_less_than_3_10: dataclass_types.append(_a ) for dataclass_type in dataclass_types: _snake_case = HfArgumentParser(_a ) self.argparsersEqual(_a , _a ) _snake_case = parser.parse_args([] ) self.assertEqual(_a , Namespace(foo=_a , bar=_a , baz=_a , ces=[] , des=[] ) ) _snake_case = parser.parse_args('''--foo 12 --bar 3.14 --baz 42 --ces a b c --des 1 2 3'''.split() ) self.assertEqual(_a , Namespace(foo=12 , bar=3.1_4 , baz='''42''' , ces=['''a''', '''b''', '''c'''] , des=[1, 2, 3] ) ) def lowercase ( self : Any ): _snake_case = HfArgumentParser(_a ) _snake_case = argparse.ArgumentParser() expected.add_argument('''--required_list''' , nargs='''+''' , type=_a , required=_a ) expected.add_argument('''--required_str''' , type=_a , required=_a ) expected.add_argument( '''--required_enum''' , type=make_choice_type_function(['''titi''', '''toto'''] ) , choices=['''titi''', '''toto'''] , required=_a , ) self.argparsersEqual(_a , _a ) def lowercase ( self : Optional[Any] ): _snake_case = HfArgumentParser(_a ) _snake_case = argparse.ArgumentParser() expected.add_argument('''--foo''' , type=_a , required=_a ) expected.add_argument( '''--required_enum''' , type=make_choice_type_function(['''titi''', '''toto'''] ) , choices=['''titi''', '''toto'''] , required=_a , ) expected.add_argument('''--opt''' , type=_a , default=_a ) expected.add_argument('''--baz''' , default='''toto''' , type=_a , help='''help message''' ) expected.add_argument('''--foo_str''' , nargs='''+''' , default=['''Hallo''', '''Bonjour''', '''Hello'''] , type=_a ) self.argparsersEqual(_a , _a ) def lowercase ( self : Optional[Any] ): _snake_case = HfArgumentParser(_a ) _snake_case = { '''foo''': 12, '''bar''': 3.1_4, '''baz''': '''42''', '''flag''': True, } _snake_case = parser.parse_dict(_a )[0] _snake_case = BasicExample(**_a ) self.assertEqual(_a , _a ) def lowercase ( self : Optional[int] ): _snake_case = HfArgumentParser(_a ) _snake_case = { '''foo''': 12, '''bar''': 3.1_4, '''baz''': '''42''', '''flag''': True, '''extra''': 42, } self.assertRaises(_a , parser.parse_dict , _a , allow_extra_keys=_a ) def lowercase ( self : Dict ): _snake_case = HfArgumentParser(_a ) _snake_case = { '''foo''': 12, '''bar''': 3.1_4, '''baz''': '''42''', '''flag''': True, } with tempfile.TemporaryDirectory() as tmp_dir: _snake_case = os.path.join(_a , '''temp_json''' ) os.mkdir(_a ) with open(temp_local_path + '''.json''' , '''w+''' ) as f: json.dump(_a , _a ) _snake_case = parser.parse_yaml_file(Path(temp_local_path + '''.json''' ) )[0] _snake_case = BasicExample(**_a ) self.assertEqual(_a , _a ) def lowercase ( self : List[Any] ): _snake_case = HfArgumentParser(_a ) _snake_case = { '''foo''': 12, '''bar''': 3.1_4, '''baz''': '''42''', '''flag''': True, } with tempfile.TemporaryDirectory() as tmp_dir: _snake_case = os.path.join(_a , '''temp_yaml''' ) os.mkdir(_a ) with open(temp_local_path + '''.yaml''' , '''w+''' ) as f: yaml.dump(_a , _a ) _snake_case = parser.parse_yaml_file(Path(temp_local_path + '''.yaml''' ) )[0] _snake_case = BasicExample(**_a ) self.assertEqual(_a , _a ) def lowercase ( self : List[str] ): _snake_case = HfArgumentParser(_a ) self.assertIsNotNone(_a )
288
"""simple docstring""" from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import pyarrow as pa if TYPE_CHECKING: from .features import FeatureType @dataclass class __lowerCAmelCase : '''simple docstring''' __UpperCAmelCase : List[str] __UpperCAmelCase : Optional[str] = None # Automatically constructed __UpperCAmelCase : ClassVar[str] = "dict" __UpperCAmelCase : ClassVar[Any] = None __UpperCAmelCase : str = field(default='Translation' , init=__SCREAMING_SNAKE_CASE , repr=__SCREAMING_SNAKE_CASE ) def __call__( self ): return pa.struct({lang: pa.string() for lang in sorted(self.languages )} ) def __UpperCAmelCase ( self ): from .features import Value return {k: Value('''string''' ) for k in sorted(self.languages )} @dataclass class __lowerCAmelCase : '''simple docstring''' __UpperCAmelCase : Optional[List] = None __UpperCAmelCase : Optional[int] = None __UpperCAmelCase : Optional[str] = None # Automatically constructed __UpperCAmelCase : ClassVar[str] = "dict" __UpperCAmelCase : ClassVar[Any] = None __UpperCAmelCase : str = field(default='TranslationVariableLanguages' , init=__SCREAMING_SNAKE_CASE , repr=__SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self ): __a = sorted(set(self.languages ) ) if self.languages else None __a = len(self.languages ) if self.languages else None def __call__( self ): return pa.struct({'''language''': pa.list_(pa.string() ), '''translation''': pa.list_(pa.string() )} ) def __UpperCAmelCase ( self , _a ): __a = set(self.languages ) if self.languages and set(_a ) - lang_set: raise ValueError( f'''Some languages in example ({', '.join(sorted(set(_a ) - lang_set ) )}) are not in valid set ({', '.join(_a )}).''' ) # Convert dictionary into tuples, splitting out cases where there are # multiple translations for a single language. __a = [] for lang, text in translation_dict.items(): if isinstance(_a , _a ): translation_tuples.append((lang, text) ) else: translation_tuples.extend([(lang, el) for el in text] ) # Ensure translations are in ascending order by language code. __a , __a = zip(*sorted(_a ) ) return {"language": languages, "translation": translations} def __UpperCAmelCase ( self ): from .features import Sequence, Value return { "language": Sequence(Value('''string''' ) ), "translation": Sequence(Value('''string''' ) ), }
45
0
from importlib import import_module from .logging import get_logger lowerCAmelCase__ = get_logger(__name__) class a__ : """simple docstring""" def __init__( self , lowercase , lowercase=None ) -> List[str]: '''simple docstring''' 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 a__ : """simple docstring""" __lowerCamelCase = [] def __init__( self , lowercase , lowercase , lowercase , lowercase=None ) -> Any: '''simple docstring''' A__ = obj A__ = target A__ = new A__ = target.split("." )[0] A__ = {} A__ = attrs or [] def __enter__( self ) -> Union[str, Any]: '''simple docstring''' *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 , *lowercase ) -> List[Any]: '''simple docstring''' for attr in list(self.original ): setattr(self.obj , _a , self.original.pop(_a ) ) def UpperCamelCase ( self ) -> List[Any]: '''simple docstring''' self.__enter__() self._active_patches.append(self ) def UpperCamelCase ( self ) -> Optional[int]: '''simple docstring''' try: self._active_patches.remove(self ) except ValueError: # If the patch hasn't been started this will fail return None return self.__exit__()
68
"""simple docstring""" def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list ) -> List[Any]: _enforce_args(lowerCAmelCase__ , lowerCAmelCase__ ) if n == 0: return 0 __a = float('''-inf''' ) for i in range(1 , n + 1 ): __a = max( lowerCAmelCase__ , prices[i - 1] + naive_cut_rod_recursive(n - i , lowerCAmelCase__ ) ) return max_revue def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list ) -> List[str]: _enforce_args(lowerCAmelCase__ , lowerCAmelCase__ ) __a = [float('''-inf''' ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list , lowerCAmelCase__ : list ) -> Union[str, Any]: if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: __a = float('''-inf''' ) for i in range(1 , n + 1 ): __a = max( lowerCAmelCase__ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , lowerCAmelCase__ , lowerCAmelCase__ ) , ) __a = max_revenue return max_rev[n] def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list ) -> Dict: _enforce_args(lowerCAmelCase__ , lowerCAmelCase__ ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. __a = [float('''-inf''' ) for _ in range(n + 1 )] __a = 0 for i in range(1 , n + 1 ): __a = max_rev[i] for j in range(1 , i + 1 ): __a = max(lowerCAmelCase__ , prices[j - 1] + max_rev[i - j] ) __a = max_revenue_i return max_rev[n] def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list ) -> str: if n < 0: __a = f'''n must be greater than or equal to 0. Got n = {n}''' raise ValueError(lowerCAmelCase__ ) if n > len(lowerCAmelCase__ ): __a = ( '''Each integral piece of rod must have a corresponding price. ''' f'''Got n = {n} but length of prices = {len(lowerCAmelCase__ )}''' ) raise ValueError(lowerCAmelCase__ ) def lowercase ( ) -> int: __a = [6, 10, 12, 15, 20, 23] __a = len(lowerCAmelCase__ ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. __a = 36 __a = top_down_cut_rod(lowerCAmelCase__ , lowerCAmelCase__ ) __a = bottom_up_cut_rod(lowerCAmelCase__ , lowerCAmelCase__ ) __a = naive_cut_rod_recursive(lowerCAmelCase__ , lowerCAmelCase__ ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
45
0
import argparse from argparse import Namespace import torch from torch import nn from transformers import XGLMConfig, XGLMForCausalLM def lowerCAmelCase__ ( a__: str ) -> int: '''simple docstring''' _UpperCAmelCase = [ 'decoder.version', 'decoder.output_projection.weight', '_float_tensor', 'decoder.embed_positions._float_tensor', ] for k in ignore_keys: state_dict.pop(lowerCAmelCase__ , lowerCAmelCase__ ) def lowerCAmelCase__ ( a__: Optional[int] ) -> str: '''simple docstring''' _UpperCAmelCase , _UpperCAmelCase = emb.weight.shape _UpperCAmelCase = nn.Linear(lowerCAmelCase__ , lowerCAmelCase__ , bias=lowerCAmelCase__ ) _UpperCAmelCase = emb.weight.data return lin_layer def lowerCAmelCase__ ( a__: Optional[int] ) -> Tuple: '''simple docstring''' _UpperCAmelCase = torch.load(lowerCAmelCase__ , map_location='cpu' ) _UpperCAmelCase = Namespace(**checkpoint['cfg']['model'] ) _UpperCAmelCase = checkpoint['model'] remove_ignore_keys_(lowerCAmelCase__ ) _UpperCAmelCase = state_dict['decoder.embed_tokens.weight'].shape[0] _UpperCAmelCase = {key.replace('decoder' , 'model' ): val for key, val in state_dict.items()} _UpperCAmelCase = XGLMConfig( vocab_size=lowerCAmelCase__ , max_position_embeddings=args.max_target_positions , num_layers=args.decoder_layers , attention_heads=args.decoder_attention_heads , ffn_dim=args.decoder_ffn_embed_dim , d_model=args.decoder_embed_dim , layerdrop=args.decoder_layerdrop , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function='gelu' , scale_embedding=not args.no_scale_embedding , tie_word_embeddings=args.share_decoder_input_output_embed , ) _UpperCAmelCase = XGLMForCausalLM(lowerCAmelCase__ ) _UpperCAmelCase = model.load_state_dict(lowerCAmelCase__ , strict=lowerCAmelCase__ ) print(lowerCAmelCase__ ) _UpperCAmelCase = make_linear_from_emb(model.model.embed_tokens ) return model if __name__ == "__main__": lowerCAmelCase__ :int = argparse.ArgumentParser() # Required parameters parser.add_argument('''fairseq_path''', type=str, help='''path to a model.pt on local filesystem.''') parser.add_argument('''pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') lowerCAmelCase__ :List[Any] = parser.parse_args() lowerCAmelCase__ :Tuple = convert_fairseq_xglm_checkpoint_from_disk(args.fairseq_path) model.save_pretrained(args.pytorch_dump_folder_path)
329
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) lowercase_ = {"configuration_unispeech": ["UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP", "UniSpeechConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST", "UniSpeechForCTC", "UniSpeechForPreTraining", "UniSpeechForSequenceClassification", "UniSpeechModel", "UniSpeechPreTrainedModel", ] if TYPE_CHECKING: from .configuration_unispeech import UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_unispeech import ( UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST, UniSpeechForCTC, UniSpeechForPreTraining, UniSpeechForSequenceClassification, UniSpeechModel, UniSpeechPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
45
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available, ) __a = { 'configuration_perceiver': ['PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'PerceiverConfig', 'PerceiverOnnxConfig'], 'tokenization_perceiver': ['PerceiverTokenizer'], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __a = ['PerceiverFeatureExtractor'] __a = ['PerceiverImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __a = [ 'PERCEIVER_PRETRAINED_MODEL_ARCHIVE_LIST', 'PerceiverForImageClassificationConvProcessing', 'PerceiverForImageClassificationFourier', 'PerceiverForImageClassificationLearned', 'PerceiverForMaskedLM', 'PerceiverForMultimodalAutoencoding', 'PerceiverForOpticalFlow', 'PerceiverForSequenceClassification', 'PerceiverLayer', 'PerceiverModel', 'PerceiverPreTrainedModel', ] if TYPE_CHECKING: from .configuration_perceiver import PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP, PerceiverConfig, PerceiverOnnxConfig from .tokenization_perceiver import PerceiverTokenizer try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_perceiver import PerceiverFeatureExtractor from .image_processing_perceiver import PerceiverImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_perceiver import ( PERCEIVER_PRETRAINED_MODEL_ARCHIVE_LIST, PerceiverForImageClassificationConvProcessing, PerceiverForImageClassificationFourier, PerceiverForImageClassificationLearned, PerceiverForMaskedLM, PerceiverForMultimodalAutoencoding, PerceiverForOpticalFlow, PerceiverForSequenceClassification, PerceiverLayer, PerceiverModel, PerceiverPreTrainedModel, ) else: import sys __a = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
145
"""simple docstring""" import unittest import torch from torch import nn from diffusers.models.activations import get_activation class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = get_activation('''swish''' ) self.assertIsInstance(_a , nn.SiLU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def __UpperCAmelCase ( self ): __a = get_activation('''silu''' ) self.assertIsInstance(_a , nn.SiLU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def __UpperCAmelCase ( self ): __a = get_activation('''mish''' ) self.assertIsInstance(_a , nn.Mish ) self.assertEqual(act(torch.tensor(-200 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def __UpperCAmelCase ( self ): __a = get_activation('''gelu''' ) self.assertIsInstance(_a , nn.GELU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 )
45
0
import logging import os from dataclasses import dataclass, field from functools import partial from pathlib import Path from tempfile import TemporaryDirectory from typing import List, Optional import faiss import torch from datasets import Features, Sequence, Value, load_dataset from transformers import DPRContextEncoder, DPRContextEncoderTokenizerFast, HfArgumentParser __a :Optional[Any] = logging.getLogger(__name__) torch.set_grad_enabled(False) __a :List[str] = 'cuda' if torch.cuda.is_available() else 'cpu' def __snake_case ( __UpperCamelCase : str ,__UpperCamelCase : List[Any]=100 ,__UpperCamelCase : Optional[int]=" " ): """simple docstring""" A_ = text.split(lowerCAmelCase__ ) return [character.join(text[i : i + n] ).strip() for i in range(0 ,len(lowerCAmelCase__ ) ,lowerCAmelCase__ )] def __snake_case ( __UpperCamelCase : dict ): """simple docstring""" A_ , A_ = [], [] for title, text in zip(documents["title"] ,documents["text"] ): if text is not None: for passage in split_text(lowerCAmelCase__ ): titles.append(title if title is not None else "" ) texts.append(lowerCAmelCase__ ) return {"title": titles, "text": texts} def __snake_case ( __UpperCamelCase : dict ,__UpperCamelCase : DPRContextEncoder ,__UpperCamelCase : DPRContextEncoderTokenizerFast ): """simple docstring""" A_ = ctx_tokenizer( documents["title"] ,documents["text"] ,truncation=lowerCAmelCase__ ,padding="longest" ,return_tensors="pt" )["input_ids"] A_ = ctx_encoder(input_ids.to(device=lowerCAmelCase__ ) ,return_dict=lowerCAmelCase__ ).pooler_output return {"embeddings": embeddings.detach().cpu().numpy()} def __snake_case ( __UpperCamelCase : "RagExampleArguments" ,__UpperCamelCase : "ProcessingArguments" ,__UpperCamelCase : "IndexHnswArguments" ,): """simple docstring""" logger.info("Step 1 - Create the dataset" ) ###################################### # The dataset needed for RAG must have three columns: # - title (string): title of the document # - text (string): text of a passage of the document # - embeddings (array of dimension d): DPR representation of the passage # Let's say you have documents in tab-separated csv files with columns "title" and "text" assert os.path.isfile(rag_example_args.csv_path ), "Please provide a valid path to a csv file" # You can load a Dataset object this way A_ = load_dataset( "csv" ,data_files=[rag_example_args.csv_path] ,split="train" ,delimiter="\t" ,column_names=["title", "text"] ) # More info about loading csv files in the documentation: https://huggingface.co/docs/datasets/loading_datasets.html?highlight=csv#csv-files # Then split the documents into passages of 100 words A_ = dataset.map(lowerCAmelCase__ ,batched=lowerCAmelCase__ ,num_proc=processing_args.num_proc ) # And compute the embeddings A_ = DPRContextEncoder.from_pretrained(rag_example_args.dpr_ctx_encoder_model_name ).to(device=lowerCAmelCase__ ) A_ = DPRContextEncoderTokenizerFast.from_pretrained(rag_example_args.dpr_ctx_encoder_model_name ) A_ = Features( {"text": Value("string" ), "title": Value("string" ), "embeddings": Sequence(Value("float32" ) )} ) # optional, save as float32 instead of float64 to save space A_ = dataset.map( partial(lowerCAmelCase__ ,ctx_encoder=lowerCAmelCase__ ,ctx_tokenizer=lowerCAmelCase__ ) ,batched=lowerCAmelCase__ ,batch_size=processing_args.batch_size ,features=lowerCAmelCase__ ,) # And finally save your dataset A_ = os.path.join(rag_example_args.output_dir ,"my_knowledge_dataset" ) dataset.save_to_disk(lowerCAmelCase__ ) # from datasets import load_from_disk # dataset = load_from_disk(passages_path) # to reload the dataset ###################################### logger.info("Step 2 - Index the dataset" ) ###################################### # Let's use the Faiss implementation of HNSW for fast approximate nearest neighbor search A_ = faiss.IndexHNSWFlat(index_hnsw_args.d ,index_hnsw_args.m ,faiss.METRIC_INNER_PRODUCT ) dataset.add_faiss_index("embeddings" ,custom_index=lowerCAmelCase__ ) # And save the index A_ = os.path.join(rag_example_args.output_dir ,"my_knowledge_dataset_hnsw_index.faiss" ) dataset.get_index("embeddings" ).save(lowerCAmelCase__ ) # dataset.load_faiss_index("embeddings", index_path) # to reload the index @dataclass class _a : """simple docstring""" _lowerCamelCase : str = field( default=str(Path(__SCREAMING_SNAKE_CASE ).parent / 'test_run' / 'dummy-kb' / 'my_knowledge_dataset.csv' ) , metadata={'help': 'Path to a tab-separated csv file with columns \'title\' and \'text\''} , ) _lowerCamelCase : Optional[str] = field( default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Question that is passed as input to RAG. Default is \'What does Moses\' rod turn into ?\'.'} , ) _lowerCamelCase : str = field( default='facebook/rag-sequence-nq' , metadata={'help': 'The RAG model to use. Either \'facebook/rag-sequence-nq\' or \'facebook/rag-token-nq\''} , ) _lowerCamelCase : str = field( default='facebook/dpr-ctx_encoder-multiset-base' , metadata={ 'help': ( 'The DPR context encoder model to use. Either \'facebook/dpr-ctx_encoder-single-nq-base\' or' ' \'facebook/dpr-ctx_encoder-multiset-base\'' ) } , ) _lowerCamelCase : Optional[str] = field( default=str(Path(__SCREAMING_SNAKE_CASE ).parent / 'test_run' / 'dummy-kb' ) , metadata={'help': 'Path to a directory where the dataset passages and the index will be saved'} , ) @dataclass class _a : """simple docstring""" _lowerCamelCase : Optional[int] = field( default=__SCREAMING_SNAKE_CASE , metadata={ 'help': 'The number of processes to use to split the documents into passages. Default is single process.' } , ) _lowerCamelCase : int = field( default=1_6 , metadata={ 'help': 'The batch size to use when computing the passages embeddings using the DPR context encoder.' } , ) @dataclass class _a : """simple docstring""" _lowerCamelCase : int = field( default=7_6_8 , metadata={'help': 'The dimension of the embeddings to pass to the HNSW Faiss index.'} , ) _lowerCamelCase : int = field( default=1_2_8 , metadata={ 'help': ( 'The number of bi-directional links created for every new element during the HNSW index construction.' ) } , ) if __name__ == "__main__": logging.basicConfig(level=logging.WARNING) logger.setLevel(logging.INFO) __a :Optional[Any] = HfArgumentParser((RagExampleArguments, ProcessingArguments, IndexHnswArguments)) __a , __a , __a :str = parser.parse_args_into_dataclasses() with TemporaryDirectory() as tmp_dir: __a :str = rag_example_args.output_dir or tmp_dir main(rag_example_args, processing_args, index_hnsw_args)
312
"""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 : '''simple docstring''' def __init__( self , _a , ): __a = parent __a = 13 __a = 7 __a = True __a = True __a = True __a = 99 __a = 32 __a = 2 __a = 4 __a = 37 __a = '''gelu''' __a = 0.1 __a = 0.1 __a = 512 __a = 16 __a = 2 __a = 0.02 __a = 3 __a = 4 __a = None def __UpperCAmelCase ( self ): __a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a = None if self.use_input_mask: __a = random_attention_mask([self.batch_size, self.seq_length] ) __a = None __a = None __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __a = ids_tensor([self.batch_size] , self.num_choices ) __a = 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 __UpperCAmelCase ( self ): ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = self.prepare_config_and_inputs() __a = True __a = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __a = 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 __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a ): __a = TFEsmModel(config=_a ) __a = {'''input_ids''': input_ids, '''attention_mask''': input_mask} __a = model(_a ) __a = [input_ids, input_mask] __a = model(_a ) __a = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a , _a , ): __a = True __a = TFEsmModel(config=_a ) __a = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''encoder_hidden_states''': encoder_hidden_states, '''encoder_attention_mask''': encoder_attention_mask, } __a = model(_a ) __a = [input_ids, input_mask] __a = model(_a , encoder_hidden_states=_a ) # Also check the case where encoder outputs are not passed __a = model(_a , attention_mask=_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a ): __a = TFEsmForMaskedLM(config=_a ) __a = model([input_ids, input_mask] ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a ): __a = self.num_labels __a = TFEsmForTokenClassification(config=_a ) __a = {'''input_ids''': input_ids, '''attention_mask''': input_mask} __a = model(_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCAmelCase ( self ): __a = self.prepare_config_and_inputs() ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = config_and_inputs __a = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_tf class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : int = ( ( TFEsmModel, TFEsmForMaskedLM, TFEsmForSequenceClassification, TFEsmForTokenClassification, ) if is_tf_available() else () ) __UpperCAmelCase : Tuple = ( { 'feature-extraction': TFEsmModel, 'fill-mask': TFEsmForMaskedLM, 'text-classification': TFEsmForSequenceClassification, 'token-classification': TFEsmForTokenClassification, 'zero-shot': TFEsmForSequenceClassification, } if is_tf_available() else {} ) __UpperCAmelCase : Tuple = False __UpperCAmelCase : Union[str, Any] = False def __UpperCAmelCase ( self ): __a = TFEsmModelTester(self ) __a = ConfigTester(self , config_class=_a , hidden_size=37 ) def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_a ) @slow def __UpperCAmelCase ( self ): for model_name in TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = TFEsmModel.from_pretrained(_a ) self.assertIsNotNone(_a ) @unittest.skip('''Protein models do not support embedding resizing.''' ) def __UpperCAmelCase ( self ): pass @unittest.skip('''Protein models do not support embedding resizing.''' ) 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(_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 __a = model.get_bias() assert isinstance(_a , _a ) for k, v in name.items(): assert isinstance(_a , tf.Variable ) else: __a = model.get_output_embeddings() assert x is None __a = model.get_bias() assert name is None @require_tf class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @slow def __UpperCAmelCase ( self ): __a = TFEsmForMaskedLM.from_pretrained('''facebook/esm2_t6_8M_UR50D''' ) __a = tf.constant([[0, 1, 2, 3, 4, 5]] ) __a = model(_a )[0] __a = [1, 6, 33] self.assertEqual(list(output.numpy().shape ) , _a ) # compare the actual values for a slice. __a = tf.constant( [ [ [8.92_1518, -10.58_9814, -6.467_1307], [-6.396_7156, -13.91_1377, -1.121_1915], [-7.78_1247, -13.95_1557, -3.74_0592], ] ] ) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-2 ) ) @slow def __UpperCAmelCase ( self ): __a = TFEsmModel.from_pretrained('''facebook/esm2_t6_8M_UR50D''' ) __a = tf.constant([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] ) __a = model(_a )[0] # compare the actual values for a slice. __a = tf.constant( [ [ [0.1444_3092, 0.5412_5327, 0.324_7739], [0.3034_0484, 0.0052_6676, 0.3107_7722], [0.3227_8043, -0.2498_7096, 0.341_4628], ] ] ) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4 ) )
45
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCamelCase : Optional[Any] = logging.get_logger(__name__) lowerCamelCase : Tuple = { "roberta-base": "https://huggingface.co/roberta-base/resolve/main/config.json", "roberta-large": "https://huggingface.co/roberta-large/resolve/main/config.json", "roberta-large-mnli": "https://huggingface.co/roberta-large-mnli/resolve/main/config.json", "distilroberta-base": "https://huggingface.co/distilroberta-base/resolve/main/config.json", "roberta-base-openai-detector": "https://huggingface.co/roberta-base-openai-detector/resolve/main/config.json", "roberta-large-openai-detector": "https://huggingface.co/roberta-large-openai-detector/resolve/main/config.json", } class A( __SCREAMING_SNAKE_CASE ): '''simple docstring''' UpperCamelCase = 'roberta' def __init__( self : int , A_ : Tuple=50265 , A_ : Optional[int]=768 , A_ : Tuple=12 , A_ : Dict=12 , A_ : Any=3072 , A_ : Optional[int]="gelu" , A_ : List[Any]=0.1 , A_ : str=0.1 , A_ : Union[str, Any]=512 , A_ : Dict=2 , A_ : Dict=0.02 , A_ : Dict=1E-12 , A_ : int=1 , A_ : Union[str, Any]=0 , A_ : Tuple=2 , A_ : Union[str, Any]="absolute" , A_ : Any=True , A_ : Optional[Any]=None , **A_ : Optional[Any] , ) -> List[Any]: """simple docstring""" super().__init__(pad_token_id=_a , bos_token_id=_a , eos_token_id=_a , **_a ) lowerCamelCase_ = vocab_size lowerCamelCase_ = hidden_size lowerCamelCase_ = num_hidden_layers lowerCamelCase_ = num_attention_heads lowerCamelCase_ = hidden_act lowerCamelCase_ = intermediate_size lowerCamelCase_ = hidden_dropout_prob lowerCamelCase_ = attention_probs_dropout_prob lowerCamelCase_ = max_position_embeddings lowerCamelCase_ = type_vocab_size lowerCamelCase_ = initializer_range lowerCamelCase_ = layer_norm_eps lowerCamelCase_ = position_embedding_type lowerCamelCase_ = use_cache lowerCamelCase_ = classifier_dropout class A( __SCREAMING_SNAKE_CASE ): '''simple docstring''' @property def a__ ( self : Optional[int] ) -> str: """simple docstring""" if self.task == "multiple-choice": lowerCamelCase_ = {0: 'batch', 1: 'choice', 2: 'sequence'} else: lowerCamelCase_ = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
204
"""simple docstring""" def lowercase ( lowerCAmelCase__ : int ) -> str: if number > 0: raise ValueError('''input must be a negative integer''' ) __a = len(bin(lowerCAmelCase__ )[3:] ) __a = bin(abs(lowerCAmelCase__ ) - (1 << binary_number_length) )[3:] __a = ( ( '''1''' + '''0''' * (binary_number_length - len(lowerCAmelCase__ )) + twos_complement_number ) if number < 0 else '''0''' ) return "0b" + twos_complement_number if __name__ == "__main__": import doctest doctest.testmod()
45
0
import doctest from collections import deque import numpy as np class __magic_name__ : """simple docstring""" def __init__( self :List[str] ): '''simple docstring''' A_ : str = [2, 1, 2, -1] A_ : Tuple = [1, 2, 3, 4] def SCREAMING_SNAKE_CASE ( self :Optional[Any] ): '''simple docstring''' A_ : Optional[Any] = len(self.first_signal ) A_ : List[Any] = len(self.second_signal ) A_ : Union[str, Any] = max(_a , _a ) # create a zero matrix of max_length x max_length A_ : int = [[0] * max_length for i in range(_a )] # fills the smaller signal with zeros to make both signals of same length if length_first_signal < length_second_signal: self.first_signal += [0] * (max_length - length_first_signal) elif length_first_signal > length_second_signal: self.second_signal += [0] * (max_length - length_second_signal) for i in range(_a ): A_ : Union[str, Any] = deque(self.second_signal ) rotated_signal.rotate(_a ) for j, item in enumerate(_a ): matrix[i][j] += item # multiply the matrix with the first signal A_ : Tuple = np.matmul(np.transpose(_a ) , np.transpose(self.first_signal ) ) # rounding-off to two decimal places return [round(_a , 2 ) for i in final_signal] if __name__ == "__main__": doctest.testmod()
300
"""simple docstring""" def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : list[str] ) -> str: __a = '''''' for word_or_phrase in separated: if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise Exception('''join() accepts only strings to be joined''' ) joined += word_or_phrase + separator return joined.strip(lowerCAmelCase__ ) if __name__ == "__main__": from doctest import testmod testmod()
45
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, ) _UpperCAmelCase : Tuple = { """configuration_roformer""": ["""ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """RoFormerConfig""", """RoFormerOnnxConfig"""], """tokenization_roformer""": ["""RoFormerTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase : int = ["""RoFormerTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase : Any = [ """ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """RoFormerForCausalLM""", """RoFormerForMaskedLM""", """RoFormerForMultipleChoice""", """RoFormerForQuestionAnswering""", """RoFormerForSequenceClassification""", """RoFormerForTokenClassification""", """RoFormerLayer""", """RoFormerModel""", """RoFormerPreTrainedModel""", """load_tf_weights_in_roformer""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase : int = [ """TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFRoFormerForCausalLM""", """TFRoFormerForMaskedLM""", """TFRoFormerForMultipleChoice""", """TFRoFormerForQuestionAnswering""", """TFRoFormerForSequenceClassification""", """TFRoFormerForTokenClassification""", """TFRoFormerLayer""", """TFRoFormerModel""", """TFRoFormerPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase : List[str] = [ """FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """FlaxRoFormerForMaskedLM""", """FlaxRoFormerForMultipleChoice""", """FlaxRoFormerForQuestionAnswering""", """FlaxRoFormerForSequenceClassification""", """FlaxRoFormerForTokenClassification""", """FlaxRoFormerModel""", """FlaxRoFormerPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_roformer import ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, RoFormerConfig, RoFormerOnnxConfig from .tokenization_roformer import RoFormerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roformer_fast import RoFormerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roformer import ( ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, RoFormerForCausalLM, RoFormerForMaskedLM, RoFormerForMultipleChoice, RoFormerForQuestionAnswering, RoFormerForSequenceClassification, RoFormerForTokenClassification, RoFormerLayer, RoFormerModel, RoFormerPreTrainedModel, load_tf_weights_in_roformer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roformer import ( TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerLayer, TFRoFormerModel, TFRoFormerPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roformer import ( FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, FlaxRoFormerPreTrainedModel, ) else: import sys _UpperCAmelCase : str = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
174
"""simple docstring""" lowercase_ = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" def lowercase ( lowerCAmelCase__ : bytes ) -> bytes: # Make sure the supplied data is a bytes-like object if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): __a = f'''a bytes-like object is required, not \'{data.__class__.__name__}\'''' raise TypeError(lowerCAmelCase__ ) __a = ''''''.join(bin(lowerCAmelCase__ )[2:].zfill(8 ) for byte in data ) __a = len(lowerCAmelCase__ ) % 6 != 0 if padding_needed: # The padding that will be added later __a = b'''=''' * ((6 - len(lowerCAmelCase__ ) % 6) // 2) # Append binary_stream with arbitrary binary digits (0's by default) to make its # length a multiple of 6. binary_stream += "0" * (6 - len(lowerCAmelCase__ ) % 6) else: __a = b'''''' # Encode every 6 binary digits to their corresponding Base64 character return ( "".join( B64_CHARSET[int(binary_stream[index : index + 6] , 2 )] for index in range(0 , len(lowerCAmelCase__ ) , 6 ) ).encode() + padding ) def lowercase ( lowerCAmelCase__ : str ) -> bytes: # Make sure encoded_data is either a string or a bytes-like object if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): __a = ( '''argument should be a bytes-like object or ASCII string, ''' f'''not \'{encoded_data.__class__.__name__}\'''' ) raise TypeError(lowerCAmelCase__ ) # In case encoded_data is a bytes-like object, make sure it contains only # ASCII characters so we convert it to a string object if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): try: __a = encoded_data.decode('''utf-8''' ) except UnicodeDecodeError: raise ValueError('''base64 encoded data should only contain ASCII characters''' ) __a = encoded_data.count('''=''' ) # Check if the encoded string contains non base64 characters if padding: assert all( char in B64_CHARSET for char in encoded_data[:-padding] ), "Invalid base64 character(s) found." else: assert all( char in B64_CHARSET for char in encoded_data ), "Invalid base64 character(s) found." # Check the padding assert len(lowerCAmelCase__ ) % 4 == 0 and padding < 3, "Incorrect padding" if padding: # Remove padding if there is one __a = encoded_data[:-padding] __a = ''''''.join( bin(B64_CHARSET.index(lowerCAmelCase__ ) )[2:].zfill(6 ) for char in encoded_data )[: -padding * 2] else: __a = ''''''.join( bin(B64_CHARSET.index(lowerCAmelCase__ ) )[2:].zfill(6 ) for char in encoded_data ) __a = [ int(binary_stream[index : index + 8] , 2 ) for index in range(0 , len(lowerCAmelCase__ ) , 8 ) ] return bytes(lowerCAmelCase__ ) if __name__ == "__main__": import doctest doctest.testmod()
45
0
import numpy as np def a__ ( snake_case , snake_case ): """simple docstring""" return np.where(vector > 0 , lowerCAmelCase__ , (alpha * (np.exp(lowerCAmelCase__ ) - 1)) ) if __name__ == "__main__": import doctest doctest.testmod()
303
"""simple docstring""" 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 __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = inspect.getfile(accelerate.test_utils ) __a = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_script.py'''] ) __a = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_distributed_data_loop.py'''] ) __a = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_ops.py'''] ) @require_multi_gpu def __UpperCAmelCase ( self ): print(f'''Found {torch.cuda.device_count()} devices.''' ) __a = ['''torchrun''', f'''--nproc_per_node={torch.cuda.device_count()}''', self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(_a , env=os.environ.copy() ) @require_multi_gpu def __UpperCAmelCase ( self ): print(f'''Found {torch.cuda.device_count()} devices.''' ) __a = ['''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(_a , env=os.environ.copy() ) @require_multi_gpu def __UpperCAmelCase ( self ): __a = ['''torchrun''', f'''--nproc_per_node={torch.cuda.device_count()}''', inspect.getfile(self.__class__ )] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(_a , env=os.environ.copy() ) @require_multi_gpu def __UpperCAmelCase ( self ): print(f'''Found {torch.cuda.device_count()} devices, using 2 devices only''' ) __a = ['''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(_a , env=os.environ.copy() ) if __name__ == "__main__": lowercase_ = Accelerator() lowercase_ = (accelerator.state.process_index + 2, 1_0) lowercase_ = torch.randint(0, 1_0, shape).to(accelerator.device) lowercase_ = "" lowercase_ = 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)." lowercase_ = 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." lowercase_ = 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)
45
0
"""simple docstring""" 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 UpperCAmelCase = logging.get_logger(__name__) class UpperCAmelCase_ ( __SCREAMING_SNAKE_CASE): def __init__( self : Union[str, Any] , __UpperCamelCase : Optional[int] ) -> int: super().__init__() _UpperCamelCase = nn.ModuleList(_a ) def _UpperCamelCase ( self : Tuple , __UpperCamelCase : Optional[int] , __UpperCamelCase : List[str] , __UpperCamelCase : Optional[int] , __UpperCamelCase : Optional[int] , __UpperCamelCase : Dict , __UpperCamelCase : List[Any] = None , __UpperCamelCase : int = None , __UpperCamelCase : int = None , __UpperCamelCase : Tuple = None , __UpperCamelCase : Any = False , __UpperCamelCase : str = True , ) -> List[str]: for i, (image, scale, controlnet) in enumerate(zip(_a , _a , self.nets ) ): _UpperCamelCase , _UpperCamelCase = controlnet( _a , _a , _a , _a , _a , _a , _a , _a , _a , _a , _a , ) # merge samples if i == 0: _UpperCamelCase , _UpperCamelCase = down_samples, mid_sample else: _UpperCamelCase = [ samples_prev + samples_curr for samples_prev, samples_curr in zip(_a , _a ) ] mid_block_res_sample += mid_sample return down_block_res_samples, mid_block_res_sample def _UpperCamelCase ( self : Tuple , __UpperCamelCase : Dict , __UpperCamelCase : Dict = True , __UpperCamelCase : Dict = None , __UpperCamelCase : int = False , __UpperCamelCase : Optional[Any] = None , ) -> Dict: _UpperCamelCase = 0 _UpperCamelCase = save_directory for controlnet in self.nets: controlnet.save_pretrained( _a , is_main_process=_a , save_function=_a , safe_serialization=_a , variant=_a , ) idx += 1 _UpperCamelCase = model_path_to_save + F'''_{idx}''' @classmethod def _UpperCamelCase ( cls : Optional[int] , __UpperCamelCase : str , **__UpperCamelCase : int ) -> str: _UpperCamelCase = 0 _UpperCamelCase = [] # 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`, ... _UpperCamelCase = pretrained_model_path while os.path.isdir(_a ): _UpperCamelCase = ControlNetModel.from_pretrained(_a , **_a ) controlnets.append(_a ) idx += 1 _UpperCamelCase = pretrained_model_path + F'''_{idx}''' logger.info(F'''{len(_a )} controlnets loaded from {pretrained_model_path}.''' ) if len(_a ) == 0: raise ValueError( F'''No ControlNets found under {os.path.dirname(_a )}. Expected at least {pretrained_model_path + "_0"}.''' ) return cls(_a )
256
"""simple docstring""" import numpy as np def lowercase ( lowerCAmelCase__ : np.ndarray , lowerCAmelCase__ : float ) -> np.ndarray: return np.where(vector > 0 , lowerCAmelCase__ , (alpha * (np.exp(lowerCAmelCase__ ) - 1)) ) if __name__ == "__main__": import doctest doctest.testmod()
45
0
"""simple docstring""" import unittest import numpy as np import timeout_decorator # noqa from transformers import BlenderbotConfig, is_flax_available from transformers.testing_utils import jax_device, require_flax, slow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html SCREAMING_SNAKE_CASE__:Union[str, Any] = """platform""" import jax import jax.numpy as jnp from transformers import BlenderbotTokenizer from transformers.models.blenderbot.modeling_flax_blenderbot import ( FlaxBlenderbotForConditionalGeneration, FlaxBlenderbotModel, shift_tokens_right, ) def _lowerCamelCase( a , a , a=None , a=None , a=None , a=None , a=None , a=None , ): if attention_mask is None: __a = np.where(input_ids != config.pad_token_id , 1 , 0 ) if decoder_attention_mask is None: __a = np.where(decoder_input_ids != config.pad_token_id , 1 , 0 ) if head_mask is None: __a = np.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: __a = np.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: __a = np.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": attention_mask, } class snake_case__ : def __init__( self , lowerCamelCase , lowerCamelCase=13 , lowerCamelCase=7 , lowerCamelCase=True , lowerCamelCase=False , lowerCamelCase=99 , lowerCamelCase=16 , lowerCamelCase=2 , lowerCamelCase=4 , lowerCamelCase=4 , lowerCamelCase="gelu" , lowerCamelCase=0.1 , lowerCamelCase=0.1 , lowerCamelCase=32 , lowerCamelCase=2 , lowerCamelCase=1 , lowerCamelCase=0 , lowerCamelCase=0.02 , ): __a = parent __a = batch_size __a = seq_length __a = is_training __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 = eos_token_id __a = pad_token_id __a = bos_token_id __a = initializer_range def a__ ( self ): __a = np.clip(ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) , 3 , self.vocab_size ) __a = np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1) , dtype=np.intaa )) , -1 ) __a = shift_tokens_right(_a , 1 , 2 ) __a = BlenderbotConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , initializer_range=self.initializer_range , use_cache=_a , ) __a = prepare_blenderbot_inputs_dict(_a , _a , _a ) return config, inputs_dict def a__ ( self ): __a , __a = self.prepare_config_and_inputs() return config, inputs_dict def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase ): __a = 20 __a = model_class_name(_a ) __a = model.encode(inputs_dict["input_ids"] ) __a , __a = ( inputs_dict["decoder_input_ids"], inputs_dict["decoder_attention_mask"], ) __a = model.init_cache(decoder_input_ids.shape[0] , _a , _a ) __a = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype="i4" ) __a = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __a = model.decode( decoder_input_ids[:, :-1] , _a , decoder_attention_mask=_a , past_key_values=_a , decoder_position_ids=_a , ) __a = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="i4" ) __a = model.decode( decoder_input_ids[:, -1:] , _a , decoder_attention_mask=_a , past_key_values=outputs_cache.past_key_values , decoder_position_ids=_a , ) __a = model.decode(_a , _a ) __a = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=F"Max diff is {diff}" ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase ): __a = 20 __a = model_class_name(_a ) __a = model.encode(inputs_dict["input_ids"] ) __a , __a = ( inputs_dict["decoder_input_ids"], inputs_dict["decoder_attention_mask"], ) __a = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) __a = model.init_cache(decoder_input_ids.shape[0] , _a , _a ) __a = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __a = model.decode( decoder_input_ids[:, :-1] , _a , decoder_attention_mask=_a , past_key_values=_a , decoder_position_ids=_a , ) __a = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="i4" ) __a = model.decode( decoder_input_ids[:, -1:] , _a , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=_a , decoder_position_ids=_a , ) __a = model.decode(_a , _a , decoder_attention_mask=_a ) __a = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=F"Max diff is {diff}" ) @require_flax class snake_case__ ( unittest.TestCase ): _snake_case : str = 99 def a__ ( self ): __a = np.array( [ [71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 82, 2], [5, 97, 17, 39, 94, 40, 2], [76, 83, 94, 25, 70, 78, 2], [87, 59, 41, 35, 48, 66, 2], [55, 13, 16, 58, 5, 2, 1], # note padding [64, 27, 31, 51, 12, 75, 2], [52, 64, 86, 17, 83, 39, 2], [48, 61, 9, 24, 71, 82, 2], [26, 1, 60, 48, 22, 13, 2], [21, 5, 62, 28, 14, 76, 2], [45, 98, 37, 86, 59, 48, 2], [70, 70, 50, 9, 28, 0, 2], ] , dtype=np.intaa , ) __a = input_ids.shape[0] __a = BlenderbotConfig( vocab_size=self.vocab_size , d_model=24 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=32 , decoder_ffn_dim=32 , max_position_embeddings=48 , eos_token_id=2 , pad_token_id=1 , bos_token_id=0 , ) return config, input_ids, batch_size def a__ ( self ): __a , __a , __a = self._get_config_and_data() __a = FlaxBlenderbotForConditionalGeneration(_a ) __a = lm_model(input_ids=_a ) __a = (batch_size, input_ids.shape[1], config.vocab_size) self.assertEqual(outputs["logits"].shape , _a ) def a__ ( self ): __a = BlenderbotConfig( vocab_size=self.vocab_size , d_model=14 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=8 , decoder_ffn_dim=8 , max_position_embeddings=48 , ) __a = FlaxBlenderbotForConditionalGeneration(_a ) __a = np.array([[71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 2, 1]] , dtype=np.intaa ) __a = np.array([[82, 71, 82, 18, 2], [58, 68, 2, 1, 1]] , dtype=np.intaa ) __a = lm_model(input_ids=_a , decoder_input_ids=_a ) __a = (*summary.shape, config.vocab_size) self.assertEqual(outputs["logits"].shape , _a ) def a__ ( self ): __a = np.array([[71, 82, 18, 33, 2, 1, 1], [68, 34, 26, 58, 30, 82, 2]] , dtype=np.intaa ) __a = shift_tokens_right(_a , 1 , 2 ) __a = np.equal(_a , 1 ).astype(np.floataa ).sum() __a = np.equal(_a , 1 ).astype(np.floataa ).sum() self.assertEqual(shifted.shape , input_ids.shape ) self.assertEqual(_a , n_pad_before - 1 ) self.assertTrue(np.equal(shifted[:, 0] , 2 ).all() ) @require_flax class snake_case__ ( __SCREAMING_SNAKE_CASE, unittest.TestCase, __SCREAMING_SNAKE_CASE ): _snake_case : Optional[int] = True _snake_case : Dict = ( ( FlaxBlenderbotModel, FlaxBlenderbotForConditionalGeneration, ) if is_flax_available() else () ) _snake_case : List[Any] = (FlaxBlenderbotForConditionalGeneration,) if is_flax_available() else () def a__ ( self ): __a = FlaxBlenderbotModelTester(self ) def a__ ( self ): __a , __a = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(_a , _a , _a ) def a__ ( self ): __a , __a = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(_a , _a , _a ) def a__ ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __a = self._prepare_for_class(_a , _a ) __a = model_class(_a ) @jax.jit def encode_jitted(lowerCamelCase , lowerCamelCase=None , **lowerCamelCase ): return model.encode(input_ids=_a , attention_mask=_a ) with self.subTest("JIT Enabled" ): __a = encode_jitted(**_a ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): __a = encode_jitted(**_a ).to_tuple() self.assertEqual(len(_a ) , len(_a ) ) for jitted_output, output in zip(_a , _a ): self.assertEqual(jitted_output.shape , output.shape ) def a__ ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __a = model_class(_a ) __a = model.encode(inputs_dict["input_ids"] , inputs_dict["attention_mask"] ) __a = { "decoder_input_ids": inputs_dict["decoder_input_ids"], "decoder_attention_mask": inputs_dict["decoder_attention_mask"], "encoder_outputs": encoder_outputs, } @jax.jit def decode_jitted(lowerCamelCase , lowerCamelCase , lowerCamelCase ): return model.decode( decoder_input_ids=_a , decoder_attention_mask=_a , encoder_outputs=_a , ) with self.subTest("JIT Enabled" ): __a = decode_jitted(**_a ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): __a = decode_jitted(**_a ).to_tuple() self.assertEqual(len(_a ) , len(_a ) ) for jitted_output, output in zip(_a , _a ): self.assertEqual(jitted_output.shape , output.shape ) @slow def a__ ( self ): for model_class_name in self.all_model_classes: __a = model_class_name.from_pretrained("facebook/blenderbot-400M-distill" ) # FlaxBlenderbotForSequenceClassification expects eos token in input_ids __a = np.ones((1, 1) ) * model.config.eos_token_id __a = model(_a ) self.assertIsNotNone(_a ) @unittest.skipUnless(jax_device != "cpu" , "3B test too slow on CPU." ) @slow def a__ ( self ): __a = {"num_beams": 1, "early_stopping": True, "min_length": 15, "max_length": 25} __a = {"skip_special_tokens": True, "clean_up_tokenization_spaces": True} __a = FlaxBlenderbotForConditionalGeneration.from_pretrained("facebook/blenderbot-3B" , from_pt=_a ) __a = BlenderbotTokenizer.from_pretrained("facebook/blenderbot-3B" ) __a = ["Sam"] __a = tokenizer(_a , return_tensors="jax" ) __a = model.generate(**_a , **_a ) __a = "Sam is a great name. It means \"sun\" in Gaelic." __a = tokenizer.batch_decode(_a , **_a ) assert generated_txt[0].strip() == tgt_text
261
"""simple docstring""" def lowercase ( lowerCAmelCase__ : str = "The quick brown fox jumps over the lazy dog" , ) -> bool: __a = set() # Replace all the whitespace in our sentence __a = input_str.replace(''' ''' , '''''' ) for alpha in input_str: if "a" <= alpha.lower() <= "z": frequency.add(alpha.lower() ) return len(lowerCAmelCase__ ) == 26 def lowercase ( lowerCAmelCase__ : str = "The quick brown fox jumps over the lazy dog" , ) -> bool: __a = [False] * 26 for char in input_str: if char.islower(): __a = True elif char.isupper(): __a = True return all(lowerCAmelCase__ ) def lowercase ( lowerCAmelCase__ : str = "The quick brown fox jumps over the lazy dog" , ) -> bool: return len({char for char in input_str.lower() if char.isalpha()} ) == 26 def lowercase ( ) -> None: from timeit import timeit __a = '''from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest''' print(timeit('''is_pangram()''' , setup=lowerCAmelCase__ ) ) print(timeit('''is_pangram_faster()''' , setup=lowerCAmelCase__ ) ) print(timeit('''is_pangram_fastest()''' , setup=lowerCAmelCase__ ) ) # 5.348480500048026, 2.6477354579837993, 1.8470395830227062 # 5.036091582966037, 2.644472333951853, 1.8869528750656173 if __name__ == "__main__": import doctest doctest.testmod() benchmark()
45
0
"""simple docstring""" import argparse import ast import logging import os import sys import pandas as pd import torch from tqdm import tqdm from transformers import BartForConditionalGeneration, RagRetriever, RagSequenceForGeneration, RagTokenForGeneration from transformers import logging as transformers_logging sys.path.append(os.path.join(os.getcwd())) # noqa: E402 # isort:skip from utils_rag import exact_match_score, fa_score # noqa: E402 # isort:skip UpperCAmelCase__ = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) transformers_logging.set_verbosity_info() def _UpperCAmelCase ( __lowerCamelCase : Optional[int] ) -> Optional[Any]: if "token" in model_name_or_path: return "rag_token" if "sequence" in model_name_or_path: return "rag_sequence" if "bart" in model_name_or_path: return "bart" return None def _UpperCAmelCase ( __lowerCamelCase : Optional[Any] , __lowerCamelCase : Tuple , __lowerCamelCase : str ) -> List[str]: return max(metric_fn(lowerCAmelCase__ , lowerCAmelCase__ ) for gt in ground_truths ) def _UpperCAmelCase ( __lowerCamelCase : Tuple , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Dict ) -> int: _snake_case = [line.strip() for line in open(lowerCAmelCase__ , '''r''' ).readlines()] _snake_case = [] if args.gold_data_mode == "qa": _snake_case = pd.read_csv(lowerCAmelCase__ , sep='''\t''' , header=lowerCAmelCase__ ) for answer_list in data[1]: _snake_case = ast.literal_eval(lowerCAmelCase__ ) answers.append(lowerCAmelCase__ ) else: _snake_case = [line.strip() for line in open(lowerCAmelCase__ , '''r''' ).readlines()] _snake_case = [[reference] for reference in references] _snake_case = _snake_case = _snake_case = 0 for prediction, ground_truths in zip(lowerCAmelCase__ , lowerCAmelCase__ ): total += 1 em += metric_max_over_ground_truths(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) fa += metric_max_over_ground_truths(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) _snake_case = 1_00.0 * em / total _snake_case = 1_00.0 * fa / total logger.info(f'''F1: {fa:.2f}''' ) logger.info(f'''EM: {em:.2f}''' ) def _UpperCAmelCase ( __lowerCamelCase : Dict , __lowerCamelCase : Tuple , __lowerCamelCase : Any ) -> Any: _snake_case = args.k _snake_case = [line.strip() for line in open(lowerCAmelCase__ , '''r''' ).readlines()] _snake_case = [line.strip() for line in open(lowerCAmelCase__ , '''r''' ).readlines()] _snake_case = _snake_case = 0 for hypo, reference in zip(lowerCAmelCase__ , lowerCAmelCase__ ): _snake_case = set(hypo.split('''\t''' )[:k] ) _snake_case = set(reference.split('''\t''' ) ) total += 1 em += len(hypo_provenance & ref_provenance ) / k _snake_case = 1_00.0 * em / total logger.info(f'''Precision@{k}: {em: .2f}''' ) def _UpperCAmelCase ( __lowerCamelCase : List[str] , __lowerCamelCase : str , __lowerCamelCase : str ) -> Dict: def strip_title(__lowerCamelCase : Tuple ): if title.startswith('''"''' ): _snake_case = title[1:] if title.endswith('''"''' ): _snake_case = title[:-1] return title _snake_case = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus( lowerCAmelCase__ , return_tensors='''pt''' , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__ , )['''input_ids'''].to(args.device ) _snake_case = rag_model.rag.question_encoder(lowerCAmelCase__ ) _snake_case = question_enc_outputs[0] _snake_case = rag_model.retriever( lowerCAmelCase__ , question_enc_pool_output.cpu().detach().to(torch.floataa ).numpy() , prefix=rag_model.rag.generator.config.prefix , n_docs=rag_model.config.n_docs , return_tensors='''pt''' , ) _snake_case = rag_model.retriever.index.get_doc_dicts(result.doc_ids ) _snake_case = [] for docs in all_docs: _snake_case = [strip_title(lowerCAmelCase__ ) for title in docs['''title''']] provenance_strings.append('''\t'''.join(lowerCAmelCase__ ) ) return provenance_strings def _UpperCAmelCase ( __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Dict , __lowerCamelCase : Any ) -> Any: with torch.no_grad(): _snake_case = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus( lowerCAmelCase__ , return_tensors='''pt''' , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__ ) _snake_case = inputs_dict.input_ids.to(args.device ) _snake_case = inputs_dict.attention_mask.to(args.device ) _snake_case = rag_model.generate( # rag_model overwrites generate lowerCAmelCase__ , attention_mask=lowerCAmelCase__ , num_beams=args.num_beams , min_length=args.min_length , max_length=args.max_length , early_stopping=lowerCAmelCase__ , num_return_sequences=1 , bad_words_ids=[[0, 0]] , ) _snake_case = rag_model.retriever.generator_tokenizer.batch_decode(lowerCAmelCase__ , skip_special_tokens=lowerCAmelCase__ ) if args.print_predictions: for q, a in zip(lowerCAmelCase__ , lowerCAmelCase__ ): logger.info('''Q: {} - A: {}'''.format(lowerCAmelCase__ , lowerCAmelCase__ ) ) return answers def _UpperCAmelCase ( ) -> Optional[Any]: _snake_case = argparse.ArgumentParser() parser.add_argument( '''--model_type''' , choices=['''rag_sequence''', '''rag_token''', '''bart'''] , type=lowerCAmelCase__ , help=( '''RAG model type: rag_sequence, rag_token or bart, if none specified, the type is inferred from the''' ''' model_name_or_path''' ) , ) parser.add_argument( '''--index_name''' , default=lowerCAmelCase__ , choices=['''exact''', '''compressed''', '''legacy'''] , type=lowerCAmelCase__ , help='''RAG model retriever type''' , ) parser.add_argument( '''--index_path''' , default=lowerCAmelCase__ , type=lowerCAmelCase__ , help='''Path to the retrieval index''' , ) parser.add_argument('''--n_docs''' , default=5 , type=lowerCAmelCase__ , help='''Number of retrieved docs''' ) parser.add_argument( '''--model_name_or_path''' , default=lowerCAmelCase__ , type=lowerCAmelCase__ , required=lowerCAmelCase__ , help='''Path to pretrained checkpoints or model identifier from huggingface.co/models''' , ) parser.add_argument( '''--eval_mode''' , choices=['''e2e''', '''retrieval'''] , default='''e2e''' , type=lowerCAmelCase__ , help=( '''Evaluation mode, e2e calculates exact match and F1 of the downstream task, retrieval calculates''' ''' precision@k.''' ) , ) parser.add_argument('''--k''' , default=1 , type=lowerCAmelCase__ , help='''k for the precision@k calculation''' ) parser.add_argument( '''--evaluation_set''' , default=lowerCAmelCase__ , type=lowerCAmelCase__ , required=lowerCAmelCase__ , help='''Path to a file containing evaluation samples''' , ) parser.add_argument( '''--gold_data_path''' , default=lowerCAmelCase__ , type=lowerCAmelCase__ , required=lowerCAmelCase__ , help='''Path to a tab-separated file with gold samples''' , ) parser.add_argument( '''--gold_data_mode''' , default='''qa''' , type=lowerCAmelCase__ , choices=['''qa''', '''ans'''] , help=( '''Format of the gold data file''' '''qa - a single line in the following format: question [tab] answer_list''' '''ans - a single line of the gold file contains the expected answer string''' ) , ) parser.add_argument( '''--predictions_path''' , type=lowerCAmelCase__ , default='''predictions.txt''' , help='''Name of the predictions file, to be stored in the checkpoints directory''' , ) parser.add_argument( '''--eval_all_checkpoints''' , action='''store_true''' , help='''Evaluate all checkpoints starting with the same prefix as model_name ending and ending with step number''' , ) parser.add_argument( '''--eval_batch_size''' , default=8 , type=lowerCAmelCase__ , help='''Batch size per GPU/CPU for evaluation.''' , ) parser.add_argument( '''--recalculate''' , help='''Recalculate predictions even if the prediction file exists''' , action='''store_true''' , ) parser.add_argument( '''--num_beams''' , default=4 , type=lowerCAmelCase__ , help='''Number of beams to be used when generating answers''' , ) parser.add_argument('''--min_length''' , default=1 , type=lowerCAmelCase__ , help='''Min length of the generated answers''' ) parser.add_argument('''--max_length''' , default=50 , type=lowerCAmelCase__ , help='''Max length of the generated answers''' ) parser.add_argument( '''--print_predictions''' , action='''store_true''' , help='''If True, prints predictions while evaluating.''' , ) parser.add_argument( '''--print_docs''' , action='''store_true''' , help='''If True, prints docs retried while generating.''' , ) _snake_case = parser.parse_args() _snake_case = torch.device('''cuda''' if torch.cuda.is_available() else '''cpu''' ) return args def _UpperCAmelCase ( __lowerCamelCase : Union[str, Any] ) -> str: _snake_case = {} if args.model_type is None: _snake_case = infer_model_type(args.model_name_or_path ) assert args.model_type is not None if args.model_type.startswith('''rag''' ): _snake_case = RagTokenForGeneration if args.model_type == '''rag_token''' else RagSequenceForGeneration _snake_case = args.n_docs if args.index_name is not None: _snake_case = args.index_name if args.index_path is not None: _snake_case = args.index_path else: _snake_case = BartForConditionalGeneration _snake_case = ( [f.path for f in os.scandir(args.model_name_or_path ) if f.is_dir()] if args.eval_all_checkpoints else [args.model_name_or_path] ) logger.info('''Evaluate the following checkpoints: %s''' , lowerCAmelCase__ ) _snake_case = get_scores if args.eval_mode == '''e2e''' else get_precision_at_k _snake_case = evaluate_batch_eae if args.eval_mode == '''e2e''' else evaluate_batch_retrieval for checkpoint in checkpoints: if os.path.exists(args.predictions_path ) and (not args.recalculate): logger.info('''Calculating metrics based on an existing predictions file: {}'''.format(args.predictions_path ) ) score_fn(lowerCAmelCase__ , args.predictions_path , args.gold_data_path ) continue logger.info('''***** Running evaluation for {} *****'''.format(lowerCAmelCase__ ) ) logger.info(''' Batch size = %d''' , args.eval_batch_size ) logger.info(''' Predictions will be stored under {}'''.format(args.predictions_path ) ) if args.model_type.startswith('''rag''' ): _snake_case = RagRetriever.from_pretrained(lowerCAmelCase__ , **lowerCAmelCase__ ) _snake_case = model_class.from_pretrained(lowerCAmelCase__ , retriever=lowerCAmelCase__ , **lowerCAmelCase__ ) model.retriever.init_retrieval() else: _snake_case = model_class.from_pretrained(lowerCAmelCase__ , **lowerCAmelCase__ ) model.to(args.device ) with open(args.evaluation_set , '''r''' ) as eval_file, open(args.predictions_path , '''w''' ) as preds_file: _snake_case = [] for line in tqdm(lowerCAmelCase__ ): questions.append(line.strip() ) if len(lowerCAmelCase__ ) == args.eval_batch_size: _snake_case = evaluate_batch_fn(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) preds_file.write('''\n'''.join(lowerCAmelCase__ ) + '''\n''' ) preds_file.flush() _snake_case = [] if len(lowerCAmelCase__ ) > 0: _snake_case = evaluate_batch_fn(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) preds_file.write('''\n'''.join(lowerCAmelCase__ ) ) preds_file.flush() score_fn(lowerCAmelCase__ , args.predictions_path , args.gold_data_path ) if __name__ == "__main__": UpperCAmelCase__ = get_args() main(args)
288
"""simple docstring""" import gc import unittest from transformers import CTRLConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, CTRLForSequenceClassification, CTRLLMHeadModel, CTRLModel, ) class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a=14 , _a=7 , _a=True , _a=True , _a=True , _a=True , _a=True , _a=99 , _a=32 , _a=5 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=16 , _a=2 , _a=0.02 , _a=3 , _a=4 , _a=None , ): __a = parent __a = batch_size __a = seq_length __a = is_training __a = use_token_type_ids __a = use_input_mask __a = use_labels __a = use_mc_token_ids __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = type_vocab_size __a = type_sequence_label_size __a = initializer_range __a = num_labels __a = num_choices __a = scope __a = self.vocab_size - 1 def __UpperCAmelCase ( self ): __a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a = None if self.use_input_mask: __a = random_attention_mask([self.batch_size, self.seq_length] ) __a = None if self.use_token_type_ids: __a = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __a = None if self.use_mc_token_ids: __a = ids_tensor([self.batch_size, self.num_choices] , self.seq_length ) __a = None __a = None __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __a = ids_tensor([self.batch_size] , self.num_choices ) __a = self.get_config() __a = ids_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 ) return ( config, input_ids, input_mask, head_mask, token_type_ids, mc_token_ids, sequence_labels, token_labels, choice_labels, ) def __UpperCAmelCase ( self ): return CTRLConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , pad_token_id=self.pad_token_id , ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , *_a ): __a = CTRLModel(config=_a ) model.to(_a ) model.eval() model(_a , token_type_ids=_a , head_mask=_a ) model(_a , token_type_ids=_a ) __a = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(len(result.past_key_values ) , config.n_layer ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , *_a ): __a = CTRLLMHeadModel(_a ) model.to(_a ) model.eval() __a = model(_a , token_type_ids=_a , labels=_a ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self ): __a = self.prepare_config_and_inputs() ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = config_and_inputs __a = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''head_mask''': head_mask} return config, inputs_dict def __UpperCAmelCase ( self , _a , _a , _a , _a , *_a ): __a = self.num_labels __a = CTRLForSequenceClassification(_a ) model.to(_a ) model.eval() __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = model(_a , token_type_ids=_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) @require_torch class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : str = (CTRLModel, CTRLLMHeadModel, CTRLForSequenceClassification) if is_torch_available() else () __UpperCAmelCase : Union[str, Any] = (CTRLLMHeadModel,) if is_torch_available() else () __UpperCAmelCase : Union[str, Any] = ( { 'feature-extraction': CTRLModel, 'text-classification': CTRLForSequenceClassification, 'text-generation': CTRLLMHeadModel, 'zero-shot': CTRLForSequenceClassification, } if is_torch_available() else {} ) __UpperCAmelCase : Optional[Any] = True __UpperCAmelCase : List[Any] = False __UpperCAmelCase : str = False def __UpperCAmelCase ( self , _a , _a , _a , _a , _a ): if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests": # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers. # `CTRLConfig` was never used in pipeline tests, either because of a missing checkpoint or because a tiny # config could not be created. return True return False def __UpperCAmelCase ( self ): __a = CTRLModelTester(self ) __a = ConfigTester(self , config_class=_a , n_embd=37 ) def __UpperCAmelCase ( self ): super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() torch.cuda.empty_cache() def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_ctrl_model(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*_a ) @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def __UpperCAmelCase ( self ): pass @slow def __UpperCAmelCase ( self ): for model_name in CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = CTRLModel.from_pretrained(_a ) self.assertIsNotNone(_a ) @unittest.skip('''The model doesn\'t support left padding''' ) # and it's not used enough to be worth fixing :) def __UpperCAmelCase ( self ): pass @require_torch class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() torch.cuda.empty_cache() @slow def __UpperCAmelCase ( self ): __a = CTRLLMHeadModel.from_pretrained('''ctrl''' ) model.to(_a ) __a = torch.tensor( [[11_859, 0, 1_611, 8]] , dtype=torch.long , device=_a ) # Legal the president is __a = [ 11_859, 0, 1_611, 8, 5, 150, 26_449, 2, 19, 348, 469, 3, 2_595, 48, 20_740, 246_533, 246_533, 19, 30, 5, ] # Legal the president is a good guy and I don't want to lose my job. \n \n I have a __a = model.generate(_a , do_sample=_a ) self.assertListEqual(output_ids[0].tolist() , _a )
45
0
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { """microsoft/beit-base-patch16-224-pt22k""": ( """https://huggingface.co/microsoft/beit-base-patch16-224-pt22k/resolve/main/config.json""" ), # See all BEiT models at https://huggingface.co/models?filter=beit } class a__ ( __SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCamelCase = 'beit' def __init__( self , lowercase=8192 , lowercase=768 , lowercase=12 , lowercase=12 , lowercase=3072 , lowercase="gelu" , lowercase=0.0 , lowercase=0.0 , lowercase=0.02 , lowercase=1e-12 , lowercase=224 , lowercase=16 , lowercase=3 , lowercase=False , lowercase=False , lowercase=False , lowercase=False , lowercase=0.1 , lowercase=0.1 , lowercase=True , lowercase=[3, 5, 7, 11] , lowercase=[1, 2, 3, 6] , lowercase=True , lowercase=0.4 , lowercase=256 , lowercase=1 , lowercase=False , lowercase=255 , **lowercase , ) -> List[Any]: '''simple docstring''' super().__init__(**_a ) 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__ = initializer_range A__ = layer_norm_eps A__ = image_size A__ = patch_size A__ = num_channels A__ = use_mask_token A__ = use_absolute_position_embeddings A__ = use_relative_position_bias A__ = use_shared_relative_position_bias A__ = layer_scale_init_value A__ = drop_path_rate A__ = use_mean_pooling # decode head attributes (semantic segmentation) A__ = out_indices A__ = pool_scales # auxiliary head attributes (semantic segmentation) A__ = use_auxiliary_head A__ = auxiliary_loss_weight A__ = auxiliary_channels A__ = auxiliary_num_convs A__ = auxiliary_concat_input A__ = semantic_loss_ignore_index class a__ ( __SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCamelCase = version.parse('1.11' ) @property def UpperCamelCase ( self ) -> int: '''simple docstring''' return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ] ) @property def UpperCamelCase ( self ) -> str: '''simple docstring''' return 1e-4
68
"""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, ) lowercase_ = {"configuration_xglm": ["XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP", "XGLMConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["XGLMTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["XGLMTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "XGLM_PRETRAINED_MODEL_ARCHIVE_LIST", "XGLMForCausalLM", "XGLMModel", "XGLMPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "FlaxXGLMForCausalLM", "FlaxXGLMModel", "FlaxXGLMPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST", "TFXGLMForCausalLM", "TFXGLMModel", "TFXGLMPreTrainedModel", ] if TYPE_CHECKING: from .configuration_xglm import XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XGLMConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm import XGLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm_fast import XGLMTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xglm import XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, XGLMForCausalLM, XGLMModel, XGLMPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_xglm import FlaxXGLMForCausalLM, FlaxXGLMModel, FlaxXGLMPreTrainedModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, TFXGLMPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure)
45
0
lowerCAmelCase__ :Optional[Any] = '''ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/''' def lowerCAmelCase__ ( a__: bytes ) -> bytes: '''simple docstring''' if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): _UpperCAmelCase = F'''a bytes-like object is required, not \'{data.__class__.__name__}\'''' raise TypeError(lowerCAmelCase__ ) _UpperCAmelCase = ''.join(bin(lowerCAmelCase__ )[2:].zfill(8 ) for byte in data ) _UpperCAmelCase = len(lowerCAmelCase__ ) % 6 != 0 if padding_needed: # The padding that will be added later _UpperCAmelCase = B'=' * ((6 - len(lowerCAmelCase__ ) % 6) // 2) # Append binary_stream with arbitrary binary digits (0's by default) to make its # length a multiple of 6. binary_stream += "0" * (6 - len(lowerCAmelCase__ ) % 6) else: _UpperCAmelCase = B'' # Encode every 6 binary digits to their corresponding Base64 character return ( "".join( B64_CHARSET[int(binary_stream[index : index + 6] , 2 )] for index in range(0 , len(lowerCAmelCase__ ) , 6 ) ).encode() + padding ) def lowerCAmelCase__ ( a__: str ) -> bytes: '''simple docstring''' if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): _UpperCAmelCase = ( 'argument should be a bytes-like object or ASCII string, ' F'''not \'{encoded_data.__class__.__name__}\'''' ) raise TypeError(lowerCAmelCase__ ) # In case encoded_data is a bytes-like object, make sure it contains only # ASCII characters so we convert it to a string object if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): try: _UpperCAmelCase = encoded_data.decode('utf-8' ) except UnicodeDecodeError: raise ValueError('base64 encoded data should only contain ASCII characters' ) _UpperCAmelCase = encoded_data.count('=' ) # Check if the encoded string contains non base64 characters if padding: assert all( char in B64_CHARSET for char in encoded_data[:-padding] ), "Invalid base64 character(s) found." else: assert all( char in B64_CHARSET for char in encoded_data ), "Invalid base64 character(s) found." # Check the padding assert len(lowerCAmelCase__ ) % 4 == 0 and padding < 3, "Incorrect padding" if padding: # Remove padding if there is one _UpperCAmelCase = encoded_data[:-padding] _UpperCAmelCase = ''.join( bin(B64_CHARSET.index(lowerCAmelCase__ ) )[2:].zfill(6 ) for char in encoded_data )[: -padding * 2] else: _UpperCAmelCase = ''.join( bin(B64_CHARSET.index(lowerCAmelCase__ ) )[2:].zfill(6 ) for char in encoded_data ) _UpperCAmelCase = [ int(binary_stream[index : index + 8] , 2 ) for index in range(0 , len(lowerCAmelCase__ ) , 8 ) ] return bytes(lowerCAmelCase__ ) if __name__ == "__main__": import doctest doctest.testmod()
329
"""simple docstring""" 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 lowercase_ = re.compile("[^A-Za-z_0-9]") # parameters used in DuplicationIndex lowercase_ = 1_0 lowercase_ = 2_5_6 def lowercase ( lowerCAmelCase__ : List[str] ) -> Optional[MinHash]: if len(lowerCAmelCase__ ) < MIN_NUM_TOKENS: return None __a = MinHash(num_perm=lowerCAmelCase__ ) for token in set(lowerCAmelCase__ ): min_hash.update(token.encode() ) return min_hash def lowercase ( lowerCAmelCase__ : str ) -> Set[str]: return {t for t in NON_ALPHA.split(lowerCAmelCase__ ) if len(t.strip() ) > 0} class __lowerCAmelCase : '''simple docstring''' def __init__( self , *, _a = 0.85 , ): __a = duplication_jaccard_threshold __a = NUM_PERM __a = MinHashLSH(threshold=self._duplication_jaccard_threshold , num_perm=self._num_perm ) __a = defaultdict(_a ) def __UpperCAmelCase ( self , _a , _a ): __a = 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 __UpperCAmelCase ( self ): __a = [] for base, duplicates in self._duplicate_clusters.items(): __a = [base] + list(_a ) # reformat the cluster to be a list of dict __a = [{'''base_index''': el[0], '''repo_name''': el[1], '''path''': el[2]} for el in cluster] duplicate_clusters.append(_a ) return duplicate_clusters def __UpperCAmelCase ( self , _a ): __a = self.get_duplicate_clusters() with open(_a , '''w''' ) as f: json.dump(_a , _a ) def lowercase ( lowerCAmelCase__ : List[str] ) -> int: __a , __a = element __a = 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 lowercase ( lowerCAmelCase__ : Type[Dataset] ) -> str: 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 lowercase ( lowerCAmelCase__ : Type[Dataset] , lowerCAmelCase__ : float ) -> Dict: __a = 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 lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : str ) -> float: __a = get_tokens(lowerCAmelCase__ ) __a = get_tokens(lowerCAmelCase__ ) return len(tokensa & tokensa ) / len(tokensa | tokensa ) lowercase_ = None def lowercase ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Union[str, Any] ) -> Any: __a = [] for elementa in cluster: __a = _shared_dataset[elementa['''base_index''']]['''content'''] for elementa in extremes: __a = _shared_dataset[elementa['''base_index''']]['''content'''] if jaccard_similarity(lowerCAmelCase__ , lowerCAmelCase__ ) >= jaccard_threshold: elementa["copies"] += 1 break else: __a = 1 extremes.append(lowerCAmelCase__ ) return extremes def lowercase ( lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Optional[int] ) -> Optional[int]: global _shared_dataset __a = dataset __a = [] __a = 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 lowercase ( lowerCAmelCase__ : Type[Dataset] , lowerCAmelCase__ : float = 0.85 ) -> Tuple[Type[Dataset], List[List[Dict]]]: __a = make_duplicate_clusters(lowerCAmelCase__ , lowerCAmelCase__ ) __a = {x['''base_index'''] for cluster in duplicate_clusters for x in cluster} __a = {} __a = find_extremes(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) for extremes in extremes_clusters: for element in extremes: __a = element __a = duplicate_indices - set(extreme_dict.keys() ) __a = 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: __a = element['''base_index'''] in extreme_dict if element["is_extreme"]: __a = 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
45
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) __a = {'configuration_unispeech': ['UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP', 'UniSpeechConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __a = [ 'UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST', 'UniSpeechForCTC', 'UniSpeechForPreTraining', 'UniSpeechForSequenceClassification', 'UniSpeechModel', 'UniSpeechPreTrainedModel', ] if TYPE_CHECKING: from .configuration_unispeech import UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_unispeech import ( UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST, UniSpeechForCTC, UniSpeechForPreTraining, UniSpeechForSequenceClassification, UniSpeechModel, UniSpeechPreTrainedModel, ) else: import sys __a = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
145
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowercase_ = { "configuration_roformer": ["ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "RoFormerConfig", "RoFormerOnnxConfig"], "tokenization_roformer": ["RoFormerTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["RoFormerTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "RoFormerForCausalLM", "RoFormerForMaskedLM", "RoFormerForMultipleChoice", "RoFormerForQuestionAnswering", "RoFormerForSequenceClassification", "RoFormerForTokenClassification", "RoFormerLayer", "RoFormerModel", "RoFormerPreTrainedModel", "load_tf_weights_in_roformer", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TFRoFormerForCausalLM", "TFRoFormerForMaskedLM", "TFRoFormerForMultipleChoice", "TFRoFormerForQuestionAnswering", "TFRoFormerForSequenceClassification", "TFRoFormerForTokenClassification", "TFRoFormerLayer", "TFRoFormerModel", "TFRoFormerPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "FlaxRoFormerForMaskedLM", "FlaxRoFormerForMultipleChoice", "FlaxRoFormerForQuestionAnswering", "FlaxRoFormerForSequenceClassification", "FlaxRoFormerForTokenClassification", "FlaxRoFormerModel", "FlaxRoFormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_roformer import ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, RoFormerConfig, RoFormerOnnxConfig from .tokenization_roformer import RoFormerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roformer_fast import RoFormerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roformer import ( ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, RoFormerForCausalLM, RoFormerForMaskedLM, RoFormerForMultipleChoice, RoFormerForQuestionAnswering, RoFormerForSequenceClassification, RoFormerForTokenClassification, RoFormerLayer, RoFormerModel, RoFormerPreTrainedModel, load_tf_weights_in_roformer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roformer import ( TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerLayer, TFRoFormerModel, TFRoFormerPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roformer import ( FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, FlaxRoFormerPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
45
0
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( UniSpeechConfig, UniSpeechForCTC, UniSpeechForPreTraining, WavaVecaFeatureExtractor, WavaVecaPhonemeCTCTokenizer, WavaVecaProcessor, logging, ) logging.set_verbosity_info() __a :Dict = logging.get_logger(__name__) __a :List[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', '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': 'ctc_proj', 'mask_emb': 'masked_spec_embed', } __a :Optional[Any] = [ 'ctc_proj', 'quantizer.weight_proj', 'quantizer.codevectors', 'project_q', 'project_hid', ] def __snake_case ( __UpperCamelCase : str ,__UpperCamelCase : List[str] ,__UpperCamelCase : Union[str, Any] ,__UpperCamelCase : str ,__UpperCamelCase : Any ,__UpperCamelCase : Any ): """simple docstring""" for attribute in key.split("." ): if is_finetuned: if attribute in ["quantizer", "project_q", "project_hid"]: # those layers are only relevant for pretraining and should be dropped return if attribute == "ctc_proj": # we should rename `ctc_proj` to `lm_head` for fine-tuned phoneme models A_ = "lm_head" A_ = getattr(lowerCAmelCase__ ,lowerCAmelCase__ ) if weight_type is not None: A_ = getattr(lowerCAmelCase__ ,lowerCAmelCase__ ).shape else: A_ = hf_pointer.shape assert hf_shape == value.shape, ( 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 __snake_case ( __UpperCamelCase : List[str] ,__UpperCamelCase : Any ,__UpperCamelCase : Tuple ): """simple docstring""" A_ = [] A_ = fairseq_model.state_dict() A_ = hf_model.unispeech.feature_extractor for name, value in fairseq_dict.items(): A_ = False if "conv_layers" in name: load_conv_layer( lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,hf_model.config.feat_extract_norm == "group" ,) A_ = True else: for key, mapped_key in MAPPING.items(): A_ = "unispeech." + 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]: A_ = True if "*" in mapped_key: A_ = name.split(lowerCAmelCase__ )[0].split("." )[-2] A_ = mapped_key.replace("*" ,lowerCAmelCase__ ) 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(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ) continue if not is_used: unused_weights.append(lowerCAmelCase__ ) logger.warning(f'''Unused weights: {unused_weights}''' ) def __snake_case ( __UpperCamelCase : Union[str, Any] ,__UpperCamelCase : int ,__UpperCamelCase : str ,__UpperCamelCase : List[Any] ,__UpperCamelCase : int ): """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: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( 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: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( 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: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( f'''{full_name} has size {value.shape}, but {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: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( 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(lowerCAmelCase__ ) @torch.no_grad() def __snake_case ( __UpperCamelCase : List[Any] ,__UpperCamelCase : Optional[Any] ,__UpperCamelCase : Optional[int]=None ,__UpperCamelCase : List[str]=None ,__UpperCamelCase : Dict=True ): """simple docstring""" if config_path is not None: A_ = UniSpeechConfig.from_pretrained(lowerCAmelCase__ ) else: A_ = UniSpeechConfig() if is_finetuned: if dict_path: A_ = Dictionary.load_from_json(lowerCAmelCase__ ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq A_ = target_dict.pad_index A_ = target_dict.bos_index A_ = target_dict.eos_index A_ = len(target_dict.symbols ) A_ = os.path.join(lowerCAmelCase__ ,"vocab.json" ) if not os.path.isdir(lowerCAmelCase__ ): logger.error("--pytorch_dump_folder_path ({}) should be a directory".format(lowerCAmelCase__ ) ) return os.makedirs(lowerCAmelCase__ ,exist_ok=lowerCAmelCase__ ) A_ = target_dict.indices # fairseq has the <pad> and <s> switched A_ = 42 A_ = 43 with open(lowerCAmelCase__ ,"w" ,encoding="utf-8" ) as vocab_handle: json.dump(lowerCAmelCase__ ,lowerCAmelCase__ ) A_ = WavaVecaPhonemeCTCTokenizer( lowerCAmelCase__ ,unk_token=target_dict.unk_word ,pad_token=target_dict.pad_word ,bos_token=target_dict.bos_word ,eos_token=target_dict.eos_word ,word_delimiter_token="|" ,do_lower_case=lowerCAmelCase__ ,) A_ = True if config.feat_extract_norm == "layer" else False A_ = WavaVecaFeatureExtractor( feature_size=1 ,sampling_rate=1_6000 ,padding_value=0 ,do_normalize=lowerCAmelCase__ ,return_attention_mask=lowerCAmelCase__ ,) A_ = WavaVecaProcessor(feature_extractor=lowerCAmelCase__ ,tokenizer=lowerCAmelCase__ ) processor.save_pretrained(lowerCAmelCase__ ) A_ = UniSpeechForCTC(lowerCAmelCase__ ) else: A_ = UniSpeechForPreTraining(lowerCAmelCase__ ) if is_finetuned: A_ , A_ , A_ = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] ,arg_overrides={"data": "/".join(dict_path.split("/" )[:-1] ), "w2v_path": checkpoint_path} ) else: A_ , A_ , A_ = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ) A_ = model[0].eval() recursively_load_weights(lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ) hf_unispeech.save_pretrained(lowerCAmelCase__ ) if __name__ == "__main__": __a :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' ) __a :Tuple = parser.parse_args() convert_unispeech_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
312
"""simple docstring""" import warnings from ..trainer import Trainer from ..utils import logging lowercase_ = logging.get_logger(__name__) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a=None , **_a ): warnings.warn( '''`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` ''' '''instead.''' , _a , ) super().__init__(args=_a , **_a )
45
0
def _SCREAMING_SNAKE_CASE ( lowercase : list[list[int]] , lowercase : int , lowercase : int , lowercase : set ): '''simple docstring''' lowerCamelCase_ , lowerCamelCase_ = len(lowerCAmelCase__ ), len(grid[0] ) if ( min(lowerCAmelCase__ , lowerCAmelCase__ ) < 0 or row == row_length or col == col_length or (row, col) in visit or grid[row][col] == 1 ): return 0 if row == row_length - 1 and col == col_length - 1: return 1 visit.add((row, col) ) lowerCamelCase_ = 0 count += depth_first_search(lowerCAmelCase__ , row + 1 , lowerCAmelCase__ , lowerCAmelCase__ ) count += depth_first_search(lowerCAmelCase__ , row - 1 , lowerCAmelCase__ , lowerCAmelCase__ ) count += depth_first_search(lowerCAmelCase__ , lowerCAmelCase__ , col + 1 , lowerCAmelCase__ ) count += depth_first_search(lowerCAmelCase__ , lowerCAmelCase__ , col - 1 , lowerCAmelCase__ ) visit.remove((row, col) ) return count if __name__ == "__main__": import doctest doctest.testmod()
204
"""simple docstring""" import math def lowercase ( lowerCAmelCase__ : list , lowerCAmelCase__ : int ) -> int: __a = len(lowerCAmelCase__ ) __a = int(math.floor(math.sqrt(lowerCAmelCase__ ) ) ) __a = 0 while arr[min(lowerCAmelCase__ , lowerCAmelCase__ ) - 1] < x: __a = step step += int(math.floor(math.sqrt(lowerCAmelCase__ ) ) ) if prev >= n: return -1 while arr[prev] < x: __a = prev + 1 if prev == min(lowerCAmelCase__ , lowerCAmelCase__ ): return -1 if arr[prev] == x: return prev return -1 if __name__ == "__main__": lowercase_ = input("Enter numbers separated by a comma:\n").strip() lowercase_ = [int(item) for item in user_input.split(",")] lowercase_ = int(input("Enter the number to be searched:\n")) lowercase_ = jump_search(arr, x) if res == -1: print("Number not found!") else: print(F'''Number {x} is at index {res}''')
45
0
import os import socket from contextlib import contextmanager import torch from ..commands.config.default import write_basic_config # noqa: F401 from ..state import PartialState from .dataclasses import DistributedType from .imports import is_deepspeed_available, is_tpu_available from .transformer_engine import convert_model from .versions import is_torch_version if is_deepspeed_available(): from deepspeed import DeepSpeedEngine if is_tpu_available(check_device=False): import torch_xla.core.xla_model as xm def __snake_case ( _lowerCAmelCase : Tuple ) -> str: if is_torch_version("<" , "2.0.0" ) or not hasattr(lowerCAmelCase__ , "_dynamo" ): return False return isinstance(lowerCAmelCase__ , torch._dynamo.eval_frame.OptimizedModule ) def __snake_case ( _lowerCAmelCase : List[Any] , _lowerCAmelCase : bool = True ) -> int: A_ : Optional[Any] = (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel) A_ : Union[str, Any] = is_compiled_module(lowerCAmelCase__ ) if is_compiled: A_ : str = model A_ : Tuple = model._orig_mod if is_deepspeed_available(): options += (DeepSpeedEngine,) while isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): A_ : Dict = model.module if not keep_fpaa_wrapper: A_ : Dict = getattr(lowerCAmelCase__ , "forward" ) A_ : Any = model.__dict__.pop("_original_forward" , lowerCAmelCase__ ) if original_forward is not None: while hasattr(lowerCAmelCase__ , "__wrapped__" ): A_ : Optional[Any] = forward.__wrapped__ if forward == original_forward: break A_ : Union[str, Any] = forward if getattr(lowerCAmelCase__ , "_converted_to_transformer_engine" , lowerCAmelCase__ ): convert_model(lowerCAmelCase__ , to_transformer_engine=lowerCAmelCase__ ) if is_compiled: A_ : List[Any] = model A_ : int = compiled_model return model def __snake_case ( ) -> Optional[int]: PartialState().wait_for_everyone() def __snake_case ( _lowerCAmelCase : Optional[int] , _lowerCAmelCase : Tuple ) -> int: if PartialState().distributed_type == DistributedType.TPU: xm.save(lowerCAmelCase__ , lowerCAmelCase__ ) elif PartialState().local_process_index == 0: torch.save(lowerCAmelCase__ , lowerCAmelCase__ ) @contextmanager def __snake_case ( **_lowerCAmelCase : List[str] ) -> List[str]: for key, value in kwargs.items(): A_ : int = str(lowerCAmelCase__ ) yield for key in kwargs: if key.upper() in os.environ: del os.environ[key.upper()] def __snake_case ( _lowerCAmelCase : Any ) -> Optional[int]: if not hasattr(lowerCAmelCase__ , "__qualname__" ) and not hasattr(lowerCAmelCase__ , "__name__" ): A_ : Union[str, Any] = getattr(lowerCAmelCase__ , "__class__" , lowerCAmelCase__ ) if hasattr(lowerCAmelCase__ , "__qualname__" ): return obj.__qualname__ if hasattr(lowerCAmelCase__ , "__name__" ): return obj.__name__ return str(lowerCAmelCase__ ) def __snake_case ( _lowerCAmelCase : Any , _lowerCAmelCase : Union[str, Any] ) -> str: for key, value in source.items(): if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): A_ : Union[str, Any] = destination.setdefault(lowerCAmelCase__ , {} ) merge_dicts(lowerCAmelCase__ , lowerCAmelCase__ ) else: A_ : List[str] = value return destination def __snake_case ( _lowerCAmelCase : int = None ) -> bool: if port is None: A_ : str = 29500 with socket.socket(socket.AF_INET , socket.SOCK_STREAM ) as s: return s.connect_ex(("localhost", port) ) == 0
300
"""simple docstring""" lowercase_ = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] lowercase_ = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] lowercase_ = { 0: "Sunday", 1: "Monday", 2: "Tuesday", 3: "Wednesday", 4: "Thursday", 5: "Friday", 6: "Saturday", } def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : int , lowerCAmelCase__ : int ) -> str: assert len(str(lowerCAmelCase__ ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 12, "month should be between 1 to 12" assert 1 <= day <= 31, "day should be between 1 to 31" # Doomsday algorithm: __a = year // 100 __a = (5 * (century % 4) + 2) % 7 __a = year % 100 __a = centurian % 12 __a = ( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 __a = ( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 400) == 0) else DOOMSDAY_LEAP[month - 1] ) __a = (dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
45
0
'''simple docstring''' from __future__ import annotations _UpperCAmelCase : Any = 1.6021E-19 # units = C def __magic_name__( lowerCamelCase, lowerCamelCase, lowerCamelCase, ): if (conductivity, electron_conc, mobility).count(0) != 1: raise ValueError('''You cannot supply more or less than 2 values''') elif conductivity < 0: raise ValueError('''Conductivity cannot be negative''') elif electron_conc < 0: raise ValueError('''Electron concentration cannot be negative''') elif mobility < 0: raise ValueError('''mobility cannot be negative''') elif conductivity == 0: return ( "conductivity", mobility * electron_conc * ELECTRON_CHARGE, ) elif electron_conc == 0: return ( "electron_conc", conductivity / (mobility * ELECTRON_CHARGE), ) else: return ( "mobility", conductivity / (electron_conc * ELECTRON_CHARGE), ) if __name__ == "__main__": import doctest doctest.testmod()
174
"""simple docstring""" def lowercase ( lowerCAmelCase__ : list ) -> bool: if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise ValueError('''Input series is not valid, valid series - [2, 4, 6]''' ) if len(lowerCAmelCase__ ) == 0: raise ValueError('''Input list must be a non empty list''' ) if len(lowerCAmelCase__ ) == 1: return True __a = series[1] - series[0] for index in range(len(lowerCAmelCase__ ) - 1 ): if series[index + 1] - series[index] != common_diff: return False return True def lowercase ( lowerCAmelCase__ : list ) -> float: if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise ValueError('''Input series is not valid, valid series - [2, 4, 6]''' ) if len(lowerCAmelCase__ ) == 0: raise ValueError('''Input list must be a non empty list''' ) __a = 0 for val in series: answer += val return answer / len(lowerCAmelCase__ ) if __name__ == "__main__": import doctest doctest.testmod()
45
0
def a__ ( snake_case , snake_case , snake_case ): """simple docstring""" def update_area_of_max_square(snake_case , snake_case ) -> int: # BASE CASE if row >= rows or col >= cols: return 0 __SCREAMING_SNAKE_CASE : List[Any] = update_area_of_max_square(lowerCAmelCase__ , col + 1 ) __SCREAMING_SNAKE_CASE : Optional[int] = update_area_of_max_square(row + 1 , col + 1 ) __SCREAMING_SNAKE_CASE : Dict = update_area_of_max_square(row + 1 , lowerCAmelCase__ ) if mat[row][col]: __SCREAMING_SNAKE_CASE : Any = 1 + min([right, diagonal, down] ) __SCREAMING_SNAKE_CASE : List[Any] = max(largest_square_area[0] , lowerCAmelCase__ ) return sub_problem_sol else: return 0 __SCREAMING_SNAKE_CASE : str = [0] update_area_of_max_square(0 , 0 ) return largest_square_area[0] def a__ ( snake_case , snake_case , snake_case ): """simple docstring""" def update_area_of_max_square_using_dp_array( snake_case , snake_case , snake_case ) -> int: if row >= rows or col >= cols: return 0 if dp_array[row][col] != -1: return dp_array[row][col] __SCREAMING_SNAKE_CASE : Optional[Any] = update_area_of_max_square_using_dp_array(lowerCAmelCase__ , col + 1 , lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : Any = update_area_of_max_square_using_dp_array(row + 1 , col + 1 , lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : Any = update_area_of_max_square_using_dp_array(row + 1 , lowerCAmelCase__ , lowerCAmelCase__ ) if mat[row][col]: __SCREAMING_SNAKE_CASE : int = 1 + min([right, diagonal, down] ) __SCREAMING_SNAKE_CASE : Optional[int] = max(largest_square_area[0] , lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : Optional[int] = sub_problem_sol return sub_problem_sol else: return 0 __SCREAMING_SNAKE_CASE : Any = [0] __SCREAMING_SNAKE_CASE : Optional[Any] = [[-1] * cols for _ in range(lowerCAmelCase__ )] update_area_of_max_square_using_dp_array(0 , 0 , lowerCAmelCase__ ) return largest_square_area[0] def a__ ( snake_case , snake_case , snake_case ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = [[0] * (cols + 1) for _ in range(rows + 1 )] __SCREAMING_SNAKE_CASE : str = 0 for row in range(rows - 1 , -1 , -1 ): for col in range(cols - 1 , -1 , -1 ): __SCREAMING_SNAKE_CASE : Any = dp_array[row][col + 1] __SCREAMING_SNAKE_CASE : List[str] = dp_array[row + 1][col + 1] __SCREAMING_SNAKE_CASE : List[str] = dp_array[row + 1][col] if mat[row][col] == 1: __SCREAMING_SNAKE_CASE : Dict = 1 + min(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : int = max(dp_array[row][col] , lowerCAmelCase__ ) else: __SCREAMING_SNAKE_CASE : List[Any] = 0 return largest_square_area def a__ ( snake_case , snake_case , snake_case ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = [0] * (cols + 1) __SCREAMING_SNAKE_CASE : Tuple = [0] * (cols + 1) __SCREAMING_SNAKE_CASE : Optional[int] = 0 for row in range(rows - 1 , -1 , -1 ): for col in range(cols - 1 , -1 , -1 ): __SCREAMING_SNAKE_CASE : Optional[Any] = current_row[col + 1] __SCREAMING_SNAKE_CASE : Optional[int] = next_row[col + 1] __SCREAMING_SNAKE_CASE : List[str] = next_row[col] if mat[row][col] == 1: __SCREAMING_SNAKE_CASE : Union[str, Any] = 1 + min(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : List[str] = max(current_row[col] , lowerCAmelCase__ ) else: __SCREAMING_SNAKE_CASE : Any = 0 __SCREAMING_SNAKE_CASE : str = current_row return largest_square_area if __name__ == "__main__": import doctest doctest.testmod() print(largest_square_area_in_matrix_bottom_up(2, 2, [[1, 1], [1, 1]]))
303
"""simple docstring""" from argparse import ArgumentParser, Namespace from ..utils import logging from . import BaseTransformersCLICommand def lowercase ( lowerCAmelCase__ : Namespace ) -> Tuple: return ConvertCommand( args.model_type , args.tf_checkpoint , args.pytorch_dump_output , args.config , args.finetuning_task_name ) lowercase_ = "\ntransformers can only be used from the commandline to convert TensorFlow models in PyTorch, In that case, it requires\nTensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installation instructions.\n" class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' @staticmethod def __UpperCAmelCase ( _a ): __a = parser.add_parser( '''convert''' , help='''CLI tool to run convert model from original author checkpoints to Transformers PyTorch checkpoints.''' , ) train_parser.add_argument('''--model_type''' , type=_a , required=_a , help='''Model\'s type.''' ) train_parser.add_argument( '''--tf_checkpoint''' , type=_a , required=_a , help='''TensorFlow checkpoint path or folder.''' ) train_parser.add_argument( '''--pytorch_dump_output''' , type=_a , required=_a , help='''Path to the PyTorch saved model output.''' ) train_parser.add_argument('''--config''' , type=_a , default='''''' , help='''Configuration file path or folder.''' ) train_parser.add_argument( '''--finetuning_task_name''' , type=_a , default=_a , help='''Optional fine-tuning task name if the TF model was a finetuned model.''' , ) train_parser.set_defaults(func=_a ) def __init__( self , _a , _a , _a , _a , _a , *_a , ): __a = logging.get_logger('''transformers-cli/converting''' ) self._logger.info(f'''Loading model {model_type}''' ) __a = model_type __a = tf_checkpoint __a = pytorch_dump_output __a = config __a = finetuning_task_name def __UpperCAmelCase ( self ): if self._model_type == "albert": try: from ..models.albert.convert_albert_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "bert": try: from ..models.bert.convert_bert_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "funnel": try: from ..models.funnel.convert_funnel_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "t5": try: from ..models.ta.convert_ta_original_tf_checkpoint_to_pytorch import convert_tf_checkpoint_to_pytorch except ImportError: raise ImportError(_a ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "gpt": from ..models.openai.convert_openai_original_tf_checkpoint_to_pytorch import ( convert_openai_checkpoint_to_pytorch, ) convert_openai_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "transfo_xl": try: from ..models.transfo_xl.convert_transfo_xl_original_tf_checkpoint_to_pytorch import ( convert_transfo_xl_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) if "ckpt" in self._tf_checkpoint.lower(): __a = self._tf_checkpoint __a = '''''' else: __a = self._tf_checkpoint __a = '''''' convert_transfo_xl_checkpoint_to_pytorch( _a , self._config , self._pytorch_dump_output , _a ) elif self._model_type == "gpt2": try: from ..models.gpta.convert_gpta_original_tf_checkpoint_to_pytorch import ( convert_gpta_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_gpta_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "xlnet": try: from ..models.xlnet.convert_xlnet_original_tf_checkpoint_to_pytorch import ( convert_xlnet_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_xlnet_checkpoint_to_pytorch( self._tf_checkpoint , self._config , self._pytorch_dump_output , self._finetuning_task_name ) elif self._model_type == "xlm": from ..models.xlm.convert_xlm_original_pytorch_checkpoint_to_pytorch import ( convert_xlm_checkpoint_to_pytorch, ) convert_xlm_checkpoint_to_pytorch(self._tf_checkpoint , self._pytorch_dump_output ) elif self._model_type == "lxmert": from ..models.lxmert.convert_lxmert_original_tf_checkpoint_to_pytorch import ( convert_lxmert_checkpoint_to_pytorch, ) convert_lxmert_checkpoint_to_pytorch(self._tf_checkpoint , self._pytorch_dump_output ) elif self._model_type == "rembert": from ..models.rembert.convert_rembert_tf_checkpoint_to_pytorch import ( convert_rembert_tf_checkpoint_to_pytorch, ) convert_rembert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) else: raise ValueError( '''--model_type should be selected in the list [bert, gpt, gpt2, t5, transfo_xl, xlnet, xlm, lxmert]''' )
45
0
"""simple docstring""" import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import List import timm import torch import torch.nn as nn from huggingface_hub import hf_hub_download from torch import Tensor from transformers import AutoImageProcessor, ResNetConfig, ResNetForImageClassification from transformers.utils import logging logging.set_verbosity_info() UpperCAmelCase = logging.get_logger() @dataclass class UpperCAmelCase_ : snake_case__ = 42 snake_case__ = field(default_factory=__SCREAMING_SNAKE_CASE) snake_case__ = field(default_factory=__SCREAMING_SNAKE_CASE) def _UpperCamelCase ( self : Union[str, Any] , __UpperCamelCase : List[Any] , __UpperCamelCase : Optional[Any] , __UpperCamelCase : List[Any] ) -> int: _UpperCamelCase = len(list(m.modules() ) ) == 1 or isinstance(_a , nn.Convad ) or isinstance(_a , nn.BatchNormad ) if has_not_submodules: self.traced.append(_a ) def __call__( self : int , __UpperCamelCase : str ) -> int: for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(_a ) [x.remove() for x in self.handles] return self @property def _UpperCamelCase ( self : Tuple ) -> Dict: # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda __UpperCamelCase : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) ) @dataclass class UpperCAmelCase_ : snake_case__ = 42 snake_case__ = 42 snake_case__ = 0 snake_case__ = field(default_factory=__SCREAMING_SNAKE_CASE) snake_case__ = field(default_factory=__SCREAMING_SNAKE_CASE) def __call__( self : List[Any] , __UpperCamelCase : Union[str, Any] ) -> List[str]: _UpperCamelCase = Tracker(self.dest )(_a ).parametrized _UpperCamelCase = Tracker(self.src )(_a ).parametrized _UpperCamelCase = list(filter(lambda __UpperCamelCase : type(_a ) not in self.src_skip , _a ) ) _UpperCamelCase = list(filter(lambda __UpperCamelCase : type(_a ) not in self.dest_skip , _a ) ) if len(_a ) != len(_a ): raise Exception( F'''Numbers of operations are different. Source module has {len(_a )} operations while''' F''' destination module has {len(_a )}.''' ) for dest_m, src_m in zip(_a , _a ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(F'''Transfered from={src_m} to={dest_m}''' ) def lowercase ( a__ : str , a__ : ResNetConfig , a__ : Path , a__ : bool = True ) -> Tuple: print(F'''Converting {name}...''' ) with torch.no_grad(): _UpperCamelCase = timm.create_model(lowerCAmelCase__ , pretrained=lowerCAmelCase__ ).eval() _UpperCamelCase = ResNetForImageClassification(lowerCAmelCase__ ).eval() _UpperCamelCase = ModuleTransfer(src=lowerCAmelCase__ , dest=lowerCAmelCase__ ) _UpperCamelCase = torch.randn((1, 3, 224, 224) ) module_transfer(lowerCAmelCase__ ) assert torch.allclose(from_model(lowerCAmelCase__ ) , our_model(lowerCAmelCase__ ).logits ), "The model logits don't match the original one." _UpperCamelCase = F'''resnet{"-".join(name.split("resnet" ) )}''' print(lowerCAmelCase__ ) if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / checkpoint_name , commit_message='''Add model''' , use_temp_dir=lowerCAmelCase__ , ) # we can use the convnext one _UpperCamelCase = AutoImageProcessor.from_pretrained('''facebook/convnext-base-224-22k-1k''' ) image_processor.push_to_hub( repo_path_or_name=save_directory / checkpoint_name , commit_message='''Add image processor''' , use_temp_dir=lowerCAmelCase__ , ) print(F'''Pushed {checkpoint_name}''' ) def lowercase ( a__ : Path , a__ : str = None , a__ : bool = True ) -> Optional[Any]: _UpperCamelCase = '''imagenet-1k-id2label.json''' _UpperCamelCase = 1000 _UpperCamelCase = (1, num_labels) _UpperCamelCase = '''huggingface/label-files''' _UpperCamelCase = num_labels _UpperCamelCase = json.load(open(hf_hub_download(lowerCAmelCase__ , lowerCAmelCase__ , repo_type='''dataset''' ) , '''r''' ) ) _UpperCamelCase = {int(lowerCAmelCase__ ): v for k, v in idalabel.items()} _UpperCamelCase = idalabel _UpperCamelCase = {v: k for k, v in idalabel.items()} _UpperCamelCase = partial(lowerCAmelCase__ , num_labels=lowerCAmelCase__ , idalabel=lowerCAmelCase__ , labelaid=lowerCAmelCase__ ) _UpperCamelCase = { '''resnet18''': ImageNetPreTrainedConfig( depths=[2, 2, 2, 2] , hidden_sizes=[64, 128, 256, 512] , layer_type='''basic''' ), '''resnet26''': ImageNetPreTrainedConfig( depths=[2, 2, 2, 2] , hidden_sizes=[256, 512, 1024, 2048] , layer_type='''bottleneck''' ), '''resnet34''': ImageNetPreTrainedConfig( depths=[3, 4, 6, 3] , hidden_sizes=[64, 128, 256, 512] , layer_type='''basic''' ), '''resnet50''': ImageNetPreTrainedConfig( depths=[3, 4, 6, 3] , hidden_sizes=[256, 512, 1024, 2048] , layer_type='''bottleneck''' ), '''resnet101''': ImageNetPreTrainedConfig( depths=[3, 4, 23, 3] , hidden_sizes=[256, 512, 1024, 2048] , layer_type='''bottleneck''' ), '''resnet152''': ImageNetPreTrainedConfig( depths=[3, 8, 36, 3] , hidden_sizes=[256, 512, 1024, 2048] , layer_type='''bottleneck''' ), } if model_name: convert_weight_and_push(lowerCAmelCase__ , names_to_config[model_name] , lowerCAmelCase__ , lowerCAmelCase__ ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) return config, expected_shape if __name__ == "__main__": UpperCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default=None, type=str, help=( """The name of the model you wish to convert, it must be one of the supported resnet* architecture,""" """ currently: resnet18,26,34,50,101,152. If `None`, all of them will the converted.""" ), ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=Path, required=True, help="""Path to the output PyTorch model directory.""", ) parser.add_argument( """--push_to_hub""", default=True, type=bool, required=False, help="""If True, push model and image processor to the hub.""", ) UpperCAmelCase = parser.parse_args() UpperCAmelCase = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
256
"""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 lowercase_ = logging.get_logger(__name__) lowercase_ = { "microsoft/beit-base-patch16-224-pt22k": ( "https://huggingface.co/microsoft/beit-base-patch16-224-pt22k/resolve/main/config.json" ), # See all BEiT models at https://huggingface.co/models?filter=beit } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : List[str] = 'beit' def __init__( self , _a=8_192 , _a=768 , _a=12 , _a=12 , _a=3_072 , _a="gelu" , _a=0.0 , _a=0.0 , _a=0.02 , _a=1E-12 , _a=224 , _a=16 , _a=3 , _a=False , _a=False , _a=False , _a=False , _a=0.1 , _a=0.1 , _a=True , _a=[3, 5, 7, 11] , _a=[1, 2, 3, 6] , _a=True , _a=0.4 , _a=256 , _a=1 , _a=False , _a=255 , **_a , ): super().__init__(**_a ) __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 = initializer_range __a = layer_norm_eps __a = image_size __a = patch_size __a = num_channels __a = use_mask_token __a = use_absolute_position_embeddings __a = use_relative_position_bias __a = use_shared_relative_position_bias __a = layer_scale_init_value __a = drop_path_rate __a = use_mean_pooling # decode head attributes (semantic segmentation) __a = out_indices __a = pool_scales # auxiliary head attributes (semantic segmentation) __a = use_auxiliary_head __a = auxiliary_loss_weight __a = auxiliary_channels __a = auxiliary_num_convs __a = auxiliary_concat_input __a = semantic_loss_ignore_index class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : List[Any] = version.parse('1.11' ) @property def __UpperCAmelCase ( self ): return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def __UpperCAmelCase ( self ): return 1E-4
45
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available, ) SCREAMING_SNAKE_CASE__:Any = { """configuration_layoutlmv2""": ["""LAYOUTLMV2_PRETRAINED_CONFIG_ARCHIVE_MAP""", """LayoutLMv2Config"""], """processing_layoutlmv2""": ["""LayoutLMv2Processor"""], """tokenization_layoutlmv2""": ["""LayoutLMv2Tokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__:Tuple = ["""LayoutLMv2TokenizerFast"""] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__:List[Any] = ["""LayoutLMv2FeatureExtractor"""] SCREAMING_SNAKE_CASE__:Dict = ["""LayoutLMv2ImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__:Tuple = [ """LAYOUTLMV2_PRETRAINED_MODEL_ARCHIVE_LIST""", """LayoutLMv2ForQuestionAnswering""", """LayoutLMv2ForSequenceClassification""", """LayoutLMv2ForTokenClassification""", """LayoutLMv2Layer""", """LayoutLMv2Model""", """LayoutLMv2PreTrainedModel""", ] if TYPE_CHECKING: from .configuration_layoutlmva import LAYOUTLMV2_PRETRAINED_CONFIG_ARCHIVE_MAP, LayoutLMvaConfig from .processing_layoutlmva import LayoutLMvaProcessor from .tokenization_layoutlmva import LayoutLMvaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutlmva_fast import LayoutLMvaTokenizerFast try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_layoutlmva import LayoutLMvaFeatureExtractor, LayoutLMvaImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_layoutlmva import ( LAYOUTLMV2_PRETRAINED_MODEL_ARCHIVE_LIST, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaLayer, LayoutLMvaModel, LayoutLMvaPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__:Tuple = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
261
"""simple docstring""" def lowercase ( lowerCAmelCase__ : str ) -> list: if n_term == "": return [] __a = [] for temp in range(int(lowerCAmelCase__ ) ): series.append(f'''1/{temp + 1}''' if series else '''1''' ) return series if __name__ == "__main__": lowercase_ = input("Enter the last number (nth term) of the Harmonic Series") print("Formula of Harmonic Series => 1+1/2+1/3 ..... 1/n") print(harmonic_series(nth_term))
45
0
"""simple docstring""" import argparse import re from pathlib import Path import requests import torch from PIL import Image from torchvision.transforms import CenterCrop, Compose, Normalize, Resize, ToTensor from transformers import ( EfficientFormerConfig, EfficientFormerForImageClassificationWithTeacher, EfficientFormerImageProcessor, ) from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling def _UpperCAmelCase ( __lowerCamelCase : Any , __lowerCamelCase : Any ) -> str: _snake_case = old_name if "patch_embed" in old_name: _snake_case , _snake_case , _snake_case = old_name.split('''.''' ) if layer == "0": _snake_case = old_name.replace('''0''' , '''convolution1''' ) elif layer == "1": _snake_case = old_name.replace('''1''' , '''batchnorm_before''' ) elif layer == "3": _snake_case = old_name.replace('''3''' , '''convolution2''' ) else: _snake_case = old_name.replace('''4''' , '''batchnorm_after''' ) if "network" in old_name and re.search(R'''\d\.\d''' , lowerCAmelCase__ ): _snake_case = R'''\b\d{2}\b''' if bool(re.search(lowerCAmelCase__ , lowerCAmelCase__ ) ): _snake_case = re.search(R'''\d\.\d\d.''' , lowerCAmelCase__ ).group() else: _snake_case = re.search(R'''\d\.\d.''' , lowerCAmelCase__ ).group() if int(match[0] ) < 6: _snake_case = old_name.replace(lowerCAmelCase__ , '''''' ) _snake_case = trimmed_name.replace('''network''' , match[0] + '''.meta4D_layers.blocks.''' + match[2:-1] ) _snake_case = '''intermediate_stages.''' + trimmed_name else: _snake_case = old_name.replace(lowerCAmelCase__ , '''''' ) if int(match[2] ) < num_meta4D_last_stage: _snake_case = trimmed_name.replace('''network''' , '''meta4D_layers.blocks.''' + match[2] ) else: _snake_case = str(int(match[2] ) - num_meta4D_last_stage ) _snake_case = trimmed_name.replace('''network''' , '''meta3D_layers.blocks.''' + layer_index ) if "norm1" in old_name: _snake_case = trimmed_name.replace('''norm1''' , '''layernorm1''' ) elif "norm2" in old_name: _snake_case = trimmed_name.replace('''norm2''' , '''layernorm2''' ) elif "fc1" in old_name: _snake_case = trimmed_name.replace('''fc1''' , '''linear_in''' ) elif "fc2" in old_name: _snake_case = trimmed_name.replace('''fc2''' , '''linear_out''' ) _snake_case = '''last_stage.''' + trimmed_name elif "network" in old_name and re.search(R'''.\d.''' , lowerCAmelCase__ ): _snake_case = old_name.replace('''network''' , '''intermediate_stages''' ) if "fc" in new_name: _snake_case = new_name.replace('''fc''' , '''convolution''' ) elif ("norm1" in new_name) and ("layernorm1" not in new_name): _snake_case = new_name.replace('''norm1''' , '''batchnorm_before''' ) elif ("norm2" in new_name) and ("layernorm2" not in new_name): _snake_case = new_name.replace('''norm2''' , '''batchnorm_after''' ) if "proj" in new_name: _snake_case = new_name.replace('''proj''' , '''projection''' ) if "dist_head" in new_name: _snake_case = new_name.replace('''dist_head''' , '''distillation_classifier''' ) elif "head" in new_name: _snake_case = new_name.replace('''head''' , '''classifier''' ) elif "patch_embed" in new_name: _snake_case = '''efficientformer.''' + new_name elif new_name == "norm.weight" or new_name == "norm.bias": _snake_case = new_name.replace('''norm''' , '''layernorm''' ) _snake_case = '''efficientformer.''' + new_name else: _snake_case = '''efficientformer.encoder.''' + new_name return new_name def _UpperCAmelCase ( __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Tuple ) -> Tuple: for key in checkpoint.copy().keys(): _snake_case = checkpoint.pop(lowerCAmelCase__ ) _snake_case = val return checkpoint def _UpperCAmelCase ( ) -> Any: _snake_case = '''http://images.cocodataset.org/val2017/000000039769.jpg''' _snake_case = Image.open(requests.get(lowerCAmelCase__ , stream=lowerCAmelCase__ ).raw ) return image def _UpperCAmelCase ( __lowerCamelCase : Path , __lowerCamelCase : Path , __lowerCamelCase : Path , __lowerCamelCase : bool ) -> Any: _snake_case = torch.load(lowerCAmelCase__ , map_location='''cpu''' )['''model'''] _snake_case = EfficientFormerConfig.from_json_file(lowerCAmelCase__ ) _snake_case = EfficientFormerForImageClassificationWithTeacher(lowerCAmelCase__ ) _snake_case = '''_'''.join(checkpoint_path.split('''/''' )[-1].split('''.''' )[0].split('''_''' )[:-1] ) _snake_case = config.depths[-1] - config.num_metaad_blocks + 1 _snake_case = convert_torch_checkpoint(lowerCAmelCase__ , lowerCAmelCase__ ) model.load_state_dict(lowerCAmelCase__ ) model.eval() _snake_case = { '''bilinear''': PILImageResampling.BILINEAR, '''bicubic''': PILImageResampling.BICUBIC, '''nearest''': PILImageResampling.NEAREST, } # prepare image _snake_case = prepare_img() _snake_case = 2_56 _snake_case = 2_24 _snake_case = EfficientFormerImageProcessor( size={'''shortest_edge''': image_size} , crop_size={'''height''': crop_size, '''width''': crop_size} , resample=pillow_resamplings['''bicubic'''] , ) _snake_case = processor(images=lowerCAmelCase__ , return_tensors='''pt''' ).pixel_values # original processing pipeline _snake_case = Compose( [ Resize(lowerCAmelCase__ , interpolation=pillow_resamplings['''bicubic'''] ), CenterCrop(lowerCAmelCase__ ), ToTensor(), Normalize(lowerCAmelCase__ , lowerCAmelCase__ ), ] ) _snake_case = image_transforms(lowerCAmelCase__ ).unsqueeze(0 ) assert torch.allclose(lowerCAmelCase__ , lowerCAmelCase__ ) _snake_case = model(lowerCAmelCase__ ) _snake_case = outputs.logits _snake_case = (1, 10_00) if "l1" in model_name: _snake_case = torch.Tensor( [-0.1_312, 0.4_353, -1.0_499, -0.5_124, 0.4_183, -0.6_793, -1.3_777, -0.0_893, -0.7_358, -2.4_328] ) assert torch.allclose(logits[0, :10] , lowerCAmelCase__ , atol=1E-3 ) assert logits.shape == expected_shape elif "l3" in model_name: _snake_case = torch.Tensor( [-1.3_150, -1.5_456, -1.2_556, -0.8_496, -0.7_127, -0.7_897, -0.9_728, -0.3_052, 0.3_751, -0.3_127] ) assert torch.allclose(logits[0, :10] , lowerCAmelCase__ , atol=1E-3 ) assert logits.shape == expected_shape elif "l7" in model_name: _snake_case = torch.Tensor( [-1.0_283, -1.4_131, -0.5_644, -1.3_115, -0.5_785, -1.2_049, -0.7_528, 0.1_992, -0.3_822, -0.0_878] ) assert logits.shape == expected_shape else: raise ValueError( f'''Unknown model checkpoint: {checkpoint_path}. Supported version of efficientformer are l1, l3 and l7''' ) # Save Checkpoints Path(lowerCAmelCase__ ).mkdir(exist_ok=lowerCAmelCase__ ) model.save_pretrained(lowerCAmelCase__ ) print(f'''Checkpoint successfuly converted. Model saved at {pytorch_dump_path}''' ) processor.save_pretrained(lowerCAmelCase__ ) print(f'''Processor successfuly saved at {pytorch_dump_path}''' ) if push_to_hub: print('''Pushing model to the hub...''' ) model.push_to_hub( repo_id=f'''Bearnardd/{pytorch_dump_path}''' , commit_message='''Add model''' , use_temp_dir=lowerCAmelCase__ , ) processor.push_to_hub( repo_id=f'''Bearnardd/{pytorch_dump_path}''' , commit_message='''Add image processor''' , use_temp_dir=lowerCAmelCase__ , ) if __name__ == "__main__": UpperCAmelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--pytorch_model_path', default=None, type=str, required=True, help='Path to EfficientFormer pytorch checkpoint.', ) parser.add_argument( '--config_file', default=None, type=str, required=True, help='The json file for EfficientFormer model config.', ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) parser.add_argument('--push_to_hub', action='store_true', help='Push model and image processor to the hub') parser.add_argument( '--no-push_to_hub', dest='push_to_hub', action='store_false', help='Do not push model and image processor to the hub', ) parser.set_defaults(push_to_hub=True) UpperCAmelCase__ = parser.parse_args() convert_efficientformer_checkpoint( checkpoint_path=args.pytorch_model_path, efficientformer_config_file=args.config_file, pytorch_dump_path=args.pytorch_dump_path, push_to_hub=args.push_to_hub, )
288
"""simple docstring""" from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import pyarrow as pa if TYPE_CHECKING: from .features import FeatureType @dataclass class __lowerCAmelCase : '''simple docstring''' __UpperCAmelCase : List[str] __UpperCAmelCase : Optional[str] = None # Automatically constructed __UpperCAmelCase : ClassVar[str] = "dict" __UpperCAmelCase : ClassVar[Any] = None __UpperCAmelCase : str = field(default='Translation' , init=__SCREAMING_SNAKE_CASE , repr=__SCREAMING_SNAKE_CASE ) def __call__( self ): return pa.struct({lang: pa.string() for lang in sorted(self.languages )} ) def __UpperCAmelCase ( self ): from .features import Value return {k: Value('''string''' ) for k in sorted(self.languages )} @dataclass class __lowerCAmelCase : '''simple docstring''' __UpperCAmelCase : Optional[List] = None __UpperCAmelCase : Optional[int] = None __UpperCAmelCase : Optional[str] = None # Automatically constructed __UpperCAmelCase : ClassVar[str] = "dict" __UpperCAmelCase : ClassVar[Any] = None __UpperCAmelCase : str = field(default='TranslationVariableLanguages' , init=__SCREAMING_SNAKE_CASE , repr=__SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self ): __a = sorted(set(self.languages ) ) if self.languages else None __a = len(self.languages ) if self.languages else None def __call__( self ): return pa.struct({'''language''': pa.list_(pa.string() ), '''translation''': pa.list_(pa.string() )} ) def __UpperCAmelCase ( self , _a ): __a = set(self.languages ) if self.languages and set(_a ) - lang_set: raise ValueError( f'''Some languages in example ({', '.join(sorted(set(_a ) - lang_set ) )}) are not in valid set ({', '.join(_a )}).''' ) # Convert dictionary into tuples, splitting out cases where there are # multiple translations for a single language. __a = [] for lang, text in translation_dict.items(): if isinstance(_a , _a ): translation_tuples.append((lang, text) ) else: translation_tuples.extend([(lang, el) for el in text] ) # Ensure translations are in ascending order by language code. __a , __a = zip(*sorted(_a ) ) return {"language": languages, "translation": translations} def __UpperCAmelCase ( self ): from .features import Sequence, Value return { "language": Sequence(Value('''string''' ) ), "translation": Sequence(Value('''string''' ) ), }
45
0
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: str ) -> bool: '''simple docstring''' A__ = [int(lowerCAmelCase__ ) for i in ip_va_address.split("." ) if i.isdigit()] return len(lowerCAmelCase__ ) == 4 and all(0 <= int(lowerCAmelCase__ ) <= 2_5_4 for octet in octets ) if __name__ == "__main__": lowerCAmelCase__ = input().strip() lowerCAmelCase__ = """valid""" if is_ip_va_address_valid(ip) else """invalid""" print(f"""{ip} is a {valid_or_invalid} IP v4 address.""")
68
"""simple docstring""" def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list ) -> List[Any]: _enforce_args(lowerCAmelCase__ , lowerCAmelCase__ ) if n == 0: return 0 __a = float('''-inf''' ) for i in range(1 , n + 1 ): __a = max( lowerCAmelCase__ , prices[i - 1] + naive_cut_rod_recursive(n - i , lowerCAmelCase__ ) ) return max_revue def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list ) -> List[str]: _enforce_args(lowerCAmelCase__ , lowerCAmelCase__ ) __a = [float('''-inf''' ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list , lowerCAmelCase__ : list ) -> Union[str, Any]: if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: __a = float('''-inf''' ) for i in range(1 , n + 1 ): __a = max( lowerCAmelCase__ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , lowerCAmelCase__ , lowerCAmelCase__ ) , ) __a = max_revenue return max_rev[n] def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list ) -> Dict: _enforce_args(lowerCAmelCase__ , lowerCAmelCase__ ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. __a = [float('''-inf''' ) for _ in range(n + 1 )] __a = 0 for i in range(1 , n + 1 ): __a = max_rev[i] for j in range(1 , i + 1 ): __a = max(lowerCAmelCase__ , prices[j - 1] + max_rev[i - j] ) __a = max_revenue_i return max_rev[n] def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list ) -> str: if n < 0: __a = f'''n must be greater than or equal to 0. Got n = {n}''' raise ValueError(lowerCAmelCase__ ) if n > len(lowerCAmelCase__ ): __a = ( '''Each integral piece of rod must have a corresponding price. ''' f'''Got n = {n} but length of prices = {len(lowerCAmelCase__ )}''' ) raise ValueError(lowerCAmelCase__ ) def lowercase ( ) -> int: __a = [6, 10, 12, 15, 20, 23] __a = len(lowerCAmelCase__ ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. __a = 36 __a = top_down_cut_rod(lowerCAmelCase__ , lowerCAmelCase__ ) __a = bottom_up_cut_rod(lowerCAmelCase__ , lowerCAmelCase__ ) __a = naive_cut_rod_recursive(lowerCAmelCase__ , lowerCAmelCase__ ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
45
0
import json import os from typing import Optional, Tuple import regex as re from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging lowerCAmelCase__ :List[str] = logging.get_logger(__name__) lowerCAmelCase__ :List[str] = { '''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', } lowerCAmelCase__ :List[Any] = { '''vocab_file''': {'''ctrl''': '''https://raw.githubusercontent.com/salesforce/ctrl/master/ctrl-vocab.json'''}, '''merges_file''': {'''ctrl''': '''https://raw.githubusercontent.com/salesforce/ctrl/master/ctrl-merges.txt'''}, } lowerCAmelCase__ :Tuple = { '''ctrl''': 2_5_6, } lowerCAmelCase__ :int = { '''Pregnancy''': 1_6_8_6_2_9, '''Christianity''': 7_6_7_5, '''Explain''': 1_0_6_4_2_3, '''Fitness''': 6_3_4_4_0, '''Saving''': 6_3_1_6_3, '''Ask''': 2_7_1_7_1, '''Ass''': 9_5_9_8_5, '''Joke''': 1_6_3_5_0_9, '''Questions''': 4_5_6_2_2, '''Thoughts''': 4_9_6_0_5, '''Retail''': 5_2_3_4_2, '''Feminism''': 1_6_4_3_3_8, '''Writing''': 1_1_9_9_2, '''Atheism''': 1_9_2_2_6_3, '''Netflix''': 4_8_6_1_6, '''Computing''': 3_9_6_3_9, '''Opinion''': 4_3_2_1_3, '''Alone''': 4_4_9_6_7, '''Funny''': 5_8_9_1_7, '''Gaming''': 4_0_3_5_8, '''Human''': 4_0_8_8, '''India''': 1_3_3_1, '''Joker''': 7_7_1_3_8, '''Diet''': 3_6_2_0_6, '''Legal''': 1_1_8_5_9, '''Norman''': 4_9_3_9, '''Tip''': 7_2_6_8_9, '''Weight''': 5_2_3_4_3, '''Movies''': 4_6_2_7_3, '''Running''': 2_3_4_2_5, '''Science''': 2_0_9_0, '''Horror''': 3_7_7_9_3, '''Confession''': 6_0_5_7_2, '''Finance''': 1_2_2_5_0, '''Politics''': 1_6_3_6_0, '''Scary''': 1_9_1_9_8_5, '''Support''': 1_2_6_5_4, '''Technologies''': 3_2_5_1_6, '''Teenage''': 6_6_1_6_0, '''Event''': 3_2_7_6_9, '''Learned''': 6_7_4_6_0, '''Notion''': 1_8_2_7_7_0, '''Wikipedia''': 3_7_5_8_3, '''Books''': 6_6_6_5, '''Extract''': 7_6_0_5_0, '''Confessions''': 1_0_2_7_0_1, '''Conspiracy''': 7_5_9_3_2, '''Links''': 6_3_6_7_4, '''Narcissus''': 1_5_0_4_2_5, '''Relationship''': 5_4_7_6_6, '''Relationships''': 1_3_4_7_9_6, '''Reviews''': 4_1_6_7_1, '''News''': 4_2_5_6, '''Translation''': 2_6_8_2_0, '''multilingual''': 1_2_8_4_0_6, } def lowerCAmelCase__ ( a__: List[str] ) -> str: '''simple docstring''' _UpperCAmelCase = set() _UpperCAmelCase = word[0] for char in word[1:]: pairs.add((prev_char, char) ) _UpperCAmelCase = char _UpperCAmelCase = set(lowerCAmelCase__ ) return pairs class __a ( __SCREAMING_SNAKE_CASE ): _a : Dict = VOCAB_FILES_NAMES _a : Dict = PRETRAINED_VOCAB_FILES_MAP _a : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _a : int = CONTROL_CODES def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE="<unk>" , **_SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" super().__init__(unk_token=_a , **_a ) with open(_a , encoding='utf-8' ) as vocab_handle: _UpperCAmelCase = json.load(_a ) _UpperCAmelCase = {v: k for k, v in self.encoder.items()} with open(_a , encoding='utf-8' ) as merges_handle: _UpperCAmelCase = merges_handle.read().split('\n' )[1:-1] _UpperCAmelCase = [tuple(merge.split() ) for merge in merges] _UpperCAmelCase = dict(zip(_a , range(len(_a ) ) ) ) _UpperCAmelCase = {} @property def UpperCAmelCase__ ( self ) -> int: """simple docstring""" return len(self.encoder ) def UpperCAmelCase__ ( self ) -> int: """simple docstring""" return dict(self.encoder , **self.added_tokens_encoder ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" if token in self.cache: return self.cache[token] _UpperCAmelCase = tuple(_a ) _UpperCAmelCase = tuple(list(word[:-1] ) + [word[-1] + '</w>'] ) _UpperCAmelCase = get_pairs(_a ) if not pairs: return token while True: _UpperCAmelCase = min(_a , key=lambda _SCREAMING_SNAKE_CASE : self.bpe_ranks.get(_a , float('inf' ) ) ) if bigram not in self.bpe_ranks: break _UpperCAmelCase , _UpperCAmelCase = bigram _UpperCAmelCase = [] _UpperCAmelCase = 0 while i < len(_a ): try: _UpperCAmelCase = word.index(_a , _a ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) _UpperCAmelCase = j if word[i] == first and i < len(_a ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 _UpperCAmelCase = tuple(_a ) _UpperCAmelCase = new_word if len(_a ) == 1: break else: _UpperCAmelCase = get_pairs(_a ) _UpperCAmelCase = '@@ '.join(_a ) _UpperCAmelCase = word[:-4] _UpperCAmelCase = word return word def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" _UpperCAmelCase = [] _UpperCAmelCase = re.findall(R'\S+\n?' , _a ) for token in words: split_tokens.extend(list(self.bpe(_a ).split(' ' ) ) ) return split_tokens def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" return self.encoder.get(_a , self.encoder.get(self.unk_token ) ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" return self.decoder.get(_a , self.unk_token ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase = ' '.join(_a ).replace('@@ ' , '' ).strip() return out_string def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None ) -> Tuple: """simple docstring""" 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'] ) _UpperCAmelCase = os.path.join( _a , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['merges_file'] ) with open(_a , 'w' , encoding='utf-8' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=_a , ensure_ascii=_a ) + '\n' ) _UpperCAmelCase = 0 with open(_a , '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 _SCREAMING_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!' ) _UpperCAmelCase = token_index writer.write(' '.join(_a ) + '\n' ) index += 1 return vocab_file, merge_file # def decode(self, token_ids, skip_special_tokens=False, clean_up_tokenization_spaces=True): # filtered_tokens = ' '.join(self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens)) # tokens_generated_so_far = re.sub('(@@ )', '', string=filtered_tokens) # tokens_generated_so_far = re.sub('(@@ ?$)', '', string=tokens_generated_so_far) # return ''.join(tokens_generated_so_far)
329
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) lowercase_ = {"configuration_unispeech": ["UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP", "UniSpeechConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST", "UniSpeechForCTC", "UniSpeechForPreTraining", "UniSpeechForSequenceClassification", "UniSpeechModel", "UniSpeechPreTrainedModel", ] if TYPE_CHECKING: from .configuration_unispeech import UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_unispeech import ( UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST, UniSpeechForCTC, UniSpeechForPreTraining, UniSpeechForSequenceClassification, UniSpeechModel, UniSpeechPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
45
0
'''simple docstring''' import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation __a = logging.get_logger(__name__) __a = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'} __a = { 'tokenizer_file': { 'EleutherAI/gpt-neox-20b': 'https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/tokenizer.json', }, } __a = { 'gpt-neox-20b': 2_048, } class A__ ( __SCREAMING_SNAKE_CASE ): """simple docstring""" UpperCamelCase_ : Any = VOCAB_FILES_NAMES UpperCamelCase_ : int = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase_ : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase_ : Dict = ['input_ids', 'attention_mask'] def __init__( self : List[Any] , lowerCAmelCase__ : Any=None , lowerCAmelCase__ : Any=None , lowerCAmelCase__ : List[str]=None , lowerCAmelCase__ : Optional[int]="<|endoftext|>" , lowerCAmelCase__ : Dict="<|endoftext|>" , lowerCAmelCase__ : List[Any]="<|endoftext|>" , lowerCAmelCase__ : Tuple=False , **lowerCAmelCase__ : int , ) -> List[str]: """simple docstring""" super().__init__( _a , _a , tokenizer_file=_a , unk_token=_a , bos_token=_a , eos_token=_a , add_prefix_space=_a , **_a , ) _UpperCAmelCase : Any = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("add_prefix_space" , _a ) != add_prefix_space: _UpperCAmelCase : Optional[Any] = getattr(_a , pre_tok_state.pop("type" ) ) _UpperCAmelCase : Optional[int] = add_prefix_space _UpperCAmelCase : int = pre_tok_class(**_a ) _UpperCAmelCase : List[Any] = add_prefix_space def _lowerCAmelCase ( self : List[Any] , lowerCAmelCase__ : Dict , lowerCAmelCase__ : Tuple = None ) -> Any: """simple docstring""" _UpperCAmelCase : List[Any] = self._tokenizer.model.save(_a , name=_a ) return tuple(_a ) def _lowerCAmelCase ( self : Dict , lowerCAmelCase__ : Tuple ) -> List[str]: """simple docstring""" _UpperCAmelCase : Optional[int] = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(_a , add_special_tokens=_a ) + [self.eos_token_id] ) if len(_a ) > self.model_max_length: _UpperCAmelCase : List[str] = input_ids[-self.model_max_length :] return input_ids
145
"""simple docstring""" import unittest import torch from torch import nn from diffusers.models.activations import get_activation class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = get_activation('''swish''' ) self.assertIsInstance(_a , nn.SiLU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def __UpperCAmelCase ( self ): __a = get_activation('''silu''' ) self.assertIsInstance(_a , nn.SiLU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def __UpperCAmelCase ( self ): __a = get_activation('''mish''' ) self.assertIsInstance(_a , nn.Mish ) self.assertEqual(act(torch.tensor(-200 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def __UpperCAmelCase ( self ): __a = get_activation('''gelu''' ) self.assertIsInstance(_a , nn.GELU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 )
45
0
import json import os import unittest from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES, BioGptTokenizer from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class _a ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): """simple docstring""" _lowerCamelCase : str = BioGptTokenizer _lowerCamelCase : List[Any] = False def __A ( self : Tuple ): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt A_ = [ "l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "w</w>", "r</w>", "t</w>", "lo", "low", "er</w>", "low</w>", "lowest</w>", "newer</w>", "wider</w>", "<unk>", ] A_ = dict(zip(_a , range(len(_a ) ) ) ) A_ = ["l o 123", "lo w 1456", "e r</w> 1789", ""] A_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) A_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" ) as fp: fp.write(json.dumps(_a ) ) with open(self.merges_file , "w" ) as fp: fp.write("\n".join(_a ) ) def __A ( self : List[Any] , UpperCAmelCase : Dict ): A_ = "lower newer" A_ = "lower newer" return input_text, output_text def __A ( self : Optional[int] ): A_ = BioGptTokenizer(self.vocab_file , self.merges_file ) A_ = "lower" A_ = ["low", "er</w>"] A_ = tokenizer.tokenize(_a ) self.assertListEqual(_a , _a ) A_ = tokens + ["<unk>"] A_ = [14, 15, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(_a ) , _a ) @slow def __A ( self : str ): A_ = BioGptTokenizer.from_pretrained("microsoft/biogpt" ) A_ = tokenizer.encode("sequence builders" , add_special_tokens=_a ) A_ = tokenizer.encode("multi-sequence build" , add_special_tokens=_a ) A_ = tokenizer.build_inputs_with_special_tokens(_a ) A_ = tokenizer.build_inputs_with_special_tokens(_a , _a ) self.assertTrue(encoded_sentence == [2] + text ) self.assertTrue(encoded_pair == [2] + text + [2] + text_a )
312
"""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 : '''simple docstring''' def __init__( self , _a , ): __a = parent __a = 13 __a = 7 __a = True __a = True __a = True __a = 99 __a = 32 __a = 2 __a = 4 __a = 37 __a = '''gelu''' __a = 0.1 __a = 0.1 __a = 512 __a = 16 __a = 2 __a = 0.02 __a = 3 __a = 4 __a = None def __UpperCAmelCase ( self ): __a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a = None if self.use_input_mask: __a = random_attention_mask([self.batch_size, self.seq_length] ) __a = None __a = None __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __a = ids_tensor([self.batch_size] , self.num_choices ) __a = 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 __UpperCAmelCase ( self ): ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = self.prepare_config_and_inputs() __a = True __a = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __a = 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 __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a ): __a = TFEsmModel(config=_a ) __a = {'''input_ids''': input_ids, '''attention_mask''': input_mask} __a = model(_a ) __a = [input_ids, input_mask] __a = model(_a ) __a = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a , _a , ): __a = True __a = TFEsmModel(config=_a ) __a = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''encoder_hidden_states''': encoder_hidden_states, '''encoder_attention_mask''': encoder_attention_mask, } __a = model(_a ) __a = [input_ids, input_mask] __a = model(_a , encoder_hidden_states=_a ) # Also check the case where encoder outputs are not passed __a = model(_a , attention_mask=_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a ): __a = TFEsmForMaskedLM(config=_a ) __a = model([input_ids, input_mask] ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a ): __a = self.num_labels __a = TFEsmForTokenClassification(config=_a ) __a = {'''input_ids''': input_ids, '''attention_mask''': input_mask} __a = model(_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCAmelCase ( self ): __a = self.prepare_config_and_inputs() ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = config_and_inputs __a = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_tf class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : int = ( ( TFEsmModel, TFEsmForMaskedLM, TFEsmForSequenceClassification, TFEsmForTokenClassification, ) if is_tf_available() else () ) __UpperCAmelCase : Tuple = ( { 'feature-extraction': TFEsmModel, 'fill-mask': TFEsmForMaskedLM, 'text-classification': TFEsmForSequenceClassification, 'token-classification': TFEsmForTokenClassification, 'zero-shot': TFEsmForSequenceClassification, } if is_tf_available() else {} ) __UpperCAmelCase : Tuple = False __UpperCAmelCase : Union[str, Any] = False def __UpperCAmelCase ( self ): __a = TFEsmModelTester(self ) __a = ConfigTester(self , config_class=_a , hidden_size=37 ) def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_a ) @slow def __UpperCAmelCase ( self ): for model_name in TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = TFEsmModel.from_pretrained(_a ) self.assertIsNotNone(_a ) @unittest.skip('''Protein models do not support embedding resizing.''' ) def __UpperCAmelCase ( self ): pass @unittest.skip('''Protein models do not support embedding resizing.''' ) 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(_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 __a = model.get_bias() assert isinstance(_a , _a ) for k, v in name.items(): assert isinstance(_a , tf.Variable ) else: __a = model.get_output_embeddings() assert x is None __a = model.get_bias() assert name is None @require_tf class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @slow def __UpperCAmelCase ( self ): __a = TFEsmForMaskedLM.from_pretrained('''facebook/esm2_t6_8M_UR50D''' ) __a = tf.constant([[0, 1, 2, 3, 4, 5]] ) __a = model(_a )[0] __a = [1, 6, 33] self.assertEqual(list(output.numpy().shape ) , _a ) # compare the actual values for a slice. __a = tf.constant( [ [ [8.92_1518, -10.58_9814, -6.467_1307], [-6.396_7156, -13.91_1377, -1.121_1915], [-7.78_1247, -13.95_1557, -3.74_0592], ] ] ) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-2 ) ) @slow def __UpperCAmelCase ( self ): __a = TFEsmModel.from_pretrained('''facebook/esm2_t6_8M_UR50D''' ) __a = tf.constant([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] ) __a = model(_a )[0] # compare the actual values for a slice. __a = tf.constant( [ [ [0.1444_3092, 0.5412_5327, 0.324_7739], [0.3034_0484, 0.0052_6676, 0.3107_7722], [0.3227_8043, -0.2498_7096, 0.341_4628], ] ] ) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4 ) )
45
0
from typing import List, Union import numpy as np from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_DEPTH_ESTIMATION_MAPPING lowerCamelCase : Optional[Any] = logging.get_logger(__name__) @add_end_docstrings(__SCREAMING_SNAKE_CASE ) class A( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self : Optional[int] , *A_ : int , **A_ : Optional[Any] ) -> str: """simple docstring""" super().__init__(*_a , **_a ) requires_backends(self , 'vision' ) self.check_model_type(_a ) def __call__( self : Optional[Any] , A_ : Optional[Any] , **A_ : Tuple ) -> Tuple: """simple docstring""" return super().__call__(_a , **_a ) def a__ ( self : Optional[int] , **A_ : Optional[Any] ) -> Dict: """simple docstring""" return {}, {}, {} def a__ ( self : Optional[Any] , A_ : str ) -> Optional[Any]: """simple docstring""" lowerCamelCase_ = load_image(_a ) lowerCamelCase_ = image.size lowerCamelCase_ = self.image_processor(images=_a , return_tensors=self.framework ) return model_inputs def a__ ( self : List[Any] , A_ : Union[str, Any] ) -> Optional[int]: """simple docstring""" lowerCamelCase_ = self.model(**_a ) return model_outputs def a__ ( self : Dict , A_ : Any ) -> Optional[int]: """simple docstring""" lowerCamelCase_ = model_outputs.predicted_depth lowerCamelCase_ = torch.nn.functional.interpolate( predicted_depth.unsqueeze(1 ) , size=self.image_size[::-1] , mode='bicubic' , align_corners=_a ) lowerCamelCase_ = prediction.squeeze().cpu().numpy() lowerCamelCase_ = (output * 255 / np.max(_a )).astype('uint8' ) lowerCamelCase_ = Image.fromarray(_a ) lowerCamelCase_ = {} lowerCamelCase_ = predicted_depth lowerCamelCase_ = depth return output_dict
204
"""simple docstring""" def lowercase ( lowerCAmelCase__ : int ) -> str: if number > 0: raise ValueError('''input must be a negative integer''' ) __a = len(bin(lowerCAmelCase__ )[3:] ) __a = bin(abs(lowerCAmelCase__ ) - (1 << binary_number_length) )[3:] __a = ( ( '''1''' + '''0''' * (binary_number_length - len(lowerCAmelCase__ )) + twos_complement_number ) if number < 0 else '''0''' ) return "0b" + twos_complement_number if __name__ == "__main__": import doctest doctest.testmod()
45
0
import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ASTConfig from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_torchaudio_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 ASTForAudioClassification, ASTModel from transformers.models.audio_spectrogram_transformer.modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) if is_torchaudio_available(): import torchaudio from transformers import ASTFeatureExtractor class __magic_name__ : """simple docstring""" def __init__( self :int , snake_case :Dict , snake_case :Optional[Any]=13 , snake_case :Any=2 , snake_case :int=24 , snake_case :Optional[int]=16 , snake_case :Tuple=True , snake_case :int=True , snake_case :str=32 , snake_case :Any=5 , snake_case :Tuple=4 , snake_case :int=37 , snake_case :List[str]="gelu" , snake_case :Union[str, Any]=0.1 , snake_case :Optional[int]=0.1 , snake_case :List[str]=10 , snake_case :Optional[int]=0.02 , snake_case :Optional[int]=None , snake_case :str=2 , snake_case :str=2 , ): '''simple docstring''' A_ : Dict = parent A_ : Optional[Any] = batch_size A_ : Any = patch_size A_ : int = max_length A_ : List[str] = num_mel_bins A_ : Tuple = is_training A_ : Tuple = use_labels A_ : Optional[Any] = hidden_size A_ : Optional[int] = num_hidden_layers A_ : Any = num_attention_heads A_ : List[str] = intermediate_size A_ : Dict = hidden_act A_ : str = hidden_dropout_prob A_ : Union[str, Any] = attention_probs_dropout_prob A_ : Tuple = type_sequence_label_size A_ : List[str] = initializer_range A_ : Any = scope A_ : Dict = frequency_stride A_ : str = time_stride # in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) A_ : Dict = (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1 A_ : Optional[int] = (self.max_length - self.patch_size) // self.time_stride + 1 A_ : List[Any] = frequency_out_dimension * time_out_dimension A_ : str = num_patches + 2 def SCREAMING_SNAKE_CASE ( self :Optional[Any] ): '''simple docstring''' A_ : Optional[Any] = floats_tensor([self.batch_size, self.max_length, self.num_mel_bins] ) A_ : Optional[Any] = None if self.use_labels: A_ : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A_ : Optional[int] = self.get_config() return config, input_values, labels def SCREAMING_SNAKE_CASE ( self :int ): '''simple docstring''' return ASTConfig( patch_size=self.patch_size , max_length=self.max_length , num_mel_bins=self.num_mel_bins , 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 , frequency_stride=self.frequency_stride , time_stride=self.time_stride , ) def SCREAMING_SNAKE_CASE ( self :Dict , snake_case :Optional[int] , snake_case :List[str] , snake_case :Any ): '''simple docstring''' A_ : Union[str, Any] = ASTModel(config=_a ) model.to(_a ) model.eval() A_ : Optional[int] = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE ( self :Optional[int] ): '''simple docstring''' A_ : List[Any] = self.prepare_config_and_inputs() ( ( A_ ) , ( A_ ) , ( A_ ) , ) : int = config_and_inputs A_ : Any = {"input_values": input_values} return config, inputs_dict @require_torch class __magic_name__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): """simple docstring""" __UpperCamelCase = ( ( ASTModel, ASTForAudioClassification, ) if is_torch_available() else () ) __UpperCamelCase = ( {'audio-classification': ASTForAudioClassification, 'feature-extraction': ASTModel} if is_torch_available() else {} ) __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False def SCREAMING_SNAKE_CASE ( self :Any , snake_case :str , snake_case :List[Any] , snake_case :Optional[int] , snake_case :Tuple , snake_case :Optional[int] ): '''simple docstring''' if pipeline_test_casse_name == "AudioClassificationPipelineTests": return True return False def SCREAMING_SNAKE_CASE ( self :str ): '''simple docstring''' A_ : Any = ASTModelTester(self ) A_ : Any = ConfigTester(self , config_class=_a , has_text_modality=_a , hidden_size=37 ) def SCREAMING_SNAKE_CASE ( self :str ): '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason="AST does not use inputs_embeds" ) def SCREAMING_SNAKE_CASE ( self :List[Any] ): '''simple docstring''' pass def SCREAMING_SNAKE_CASE ( self :str ): '''simple docstring''' A_ , A_ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A_ : List[str] = model_class(_a ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) A_ : str = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_a , nn.Linear ) ) def SCREAMING_SNAKE_CASE ( self :Dict ): '''simple docstring''' A_ , A_ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A_ : List[Any] = model_class(_a ) A_ : Union[str, Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic A_ : Union[str, Any] = [*signature.parameters.keys()] A_ : Any = ["input_values"] self.assertListEqual(arg_names[:1] , _a ) def SCREAMING_SNAKE_CASE ( self :int ): '''simple docstring''' A_ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) @slow def SCREAMING_SNAKE_CASE ( self :List[Any] ): '''simple docstring''' for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A_ : Optional[Any] = ASTModel.from_pretrained(_a ) self.assertIsNotNone(_a ) def __snake_case ( ) -> int: A_ : str = hf_hub_download( repo_id="nielsr/audio-spectogram-transformer-checkpoint" , filename="sample_audio.flac" , repo_type="dataset" ) A_ , A_ : str = torchaudio.load(lowerCAmelCase__ ) return audio, sampling_rate @require_torch @require_torchaudio class __magic_name__ ( unittest.TestCase ): """simple docstring""" @cached_property def SCREAMING_SNAKE_CASE ( self :int ): '''simple docstring''' return ( ASTFeatureExtractor.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593" ) if is_torchaudio_available() else None ) @slow def SCREAMING_SNAKE_CASE ( self :str ): '''simple docstring''' A_ : Union[str, Any] = self.default_feature_extractor A_ : List[Any] = ASTForAudioClassification.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593" ).to(_a ) A_ : List[str] = self.default_feature_extractor A_ , A_ : Any = prepare_audio() A_ : int = audio.squeeze().numpy() A_ : Dict = feature_extractor(_a , sampling_rate=_a , return_tensors="pt" ).to(_a ) # forward pass with torch.no_grad(): A_ : Tuple = model(**_a ) # verify the logits A_ : int = torch.Size((1, 527) ) self.assertEqual(outputs.logits.shape , _a ) A_ : int = torch.tensor([-0.8760, -7.0042, -8.6602] ).to(_a ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _a , atol=1e-4 ) )
300
"""simple docstring""" def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : list[str] ) -> str: __a = '''''' for word_or_phrase in separated: if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise Exception('''join() accepts only strings to be joined''' ) joined += word_or_phrase + separator return joined.strip(lowerCAmelCase__ ) if __name__ == "__main__": from doctest import testmod testmod()
45
0
'''simple docstring''' import argparse from tax import checkpoints from transformers import AutoConfig, FlaxAutoModelForSeqaSeqLM def __magic_name__( lowerCamelCase, lowerCamelCase, lowerCamelCase): __lowerCAmelCase = AutoConfig.from_pretrained(lowerCAmelCase__) __lowerCAmelCase = FlaxAutoModelForSeqaSeqLM.from_config(config=lowerCAmelCase__) __lowerCAmelCase = checkpoints.load_tax_checkpoint(lowerCAmelCase__) __lowerCAmelCase = '''wi_0''' in tax_model['''target''']['''encoder''']['''layers_0''']['''mlp'''] if config.model_type == "t5": __lowerCAmelCase = '''SelfAttention''' if config.model_type == "longt5" and config.encoder_attention_type == "local": __lowerCAmelCase = '''LocalSelfAttention''' elif config.model_type == "longt5" and config.encoder_attention_type == "transient-global": __lowerCAmelCase = '''TransientGlobalSelfAttention''' else: raise ValueError( '''Given config is expected to have `model_type=\'t5\'`, or `model_type=\'longt5` with `encoder_attention_type`''' ''' attribute with a value from [\'local\', \'transient-global].''') # Encoder for layer_index in range(config.num_layers): __lowerCAmelCase = F"""layers_{str(lowerCAmelCase__)}""" # Self-Attention __lowerCAmelCase = tax_model['''target''']['''encoder'''][layer_name]['''attention''']['''key''']['''kernel'''] __lowerCAmelCase = tax_model['''target''']['''encoder'''][layer_name]['''attention''']['''out''']['''kernel'''] __lowerCAmelCase = tax_model['''target''']['''encoder'''][layer_name]['''attention''']['''query''']['''kernel'''] __lowerCAmelCase = tax_model['''target''']['''encoder'''][layer_name]['''attention''']['''value''']['''kernel'''] # Global input layer norm if config.model_type == "longt5" and config.encoder_attention_type == "transient-global": __lowerCAmelCase = tax_model['''target''']['''encoder'''][layer_name]['''attention''']['''T5LayerNorm_0''']['''scale'''] # Layer Normalization __lowerCAmelCase = tax_model['''target''']['''encoder'''][layer_name]['''pre_attention_layer_norm''']['''scale'''] if split_mlp_wi: __lowerCAmelCase = tax_model['''target''']['''encoder'''][layer_name]['''mlp''']['''wi_0''']['''kernel'''] __lowerCAmelCase = tax_model['''target''']['''encoder'''][layer_name]['''mlp''']['''wi_1''']['''kernel'''] else: __lowerCAmelCase = tax_model['''target''']['''encoder'''][layer_name]['''mlp''']['''wi''']['''kernel'''] __lowerCAmelCase = tax_model['''target''']['''encoder'''][layer_name]['''mlp''']['''wo''']['''kernel'''] # Layer Normalization __lowerCAmelCase = tax_model['''target''']['''encoder'''][layer_name]['''pre_mlp_layer_norm''']['''scale'''] # Assigning __lowerCAmelCase = flax_model.params['''encoder''']['''block'''][str(lowerCAmelCase__)]['''layer'''] __lowerCAmelCase = tax_attention_key __lowerCAmelCase = tax_attention_out __lowerCAmelCase = tax_attention_query __lowerCAmelCase = tax_attention_value __lowerCAmelCase = tax_attention_layer_norm # Global input layer norm if config.model_type == "longt5" and config.encoder_attention_type == "transient-global": __lowerCAmelCase = tax_global_layer_norm if split_mlp_wi: __lowerCAmelCase = tax_mlp_wi_a __lowerCAmelCase = tax_mlp_wi_a else: __lowerCAmelCase = tax_mlp_wi __lowerCAmelCase = tax_mlp_wo __lowerCAmelCase = tax_mlp_layer_norm __lowerCAmelCase = flax_model_encoder_layer_block # Only for layer 0: __lowerCAmelCase = tax_model['''target''']['''encoder''']['''relpos_bias''']['''rel_embedding'''].T __lowerCAmelCase = tax_encoder_rel_embedding # Side/global relative position_bias + layer norm if config.model_type == "longt5" and config.encoder_attention_type == "transient-global": __lowerCAmelCase = tax_model['''target''']['''encoder''']['''side_relpos_bias''']['''rel_embedding'''].T __lowerCAmelCase = tax_encoder_global_rel_embedding # Assigning __lowerCAmelCase = tax_model['''target''']['''encoder''']['''encoder_norm''']['''scale'''] __lowerCAmelCase = tax_encoder_norm # Decoder for layer_index in range(config.num_layers): __lowerCAmelCase = F"""layers_{str(lowerCAmelCase__)}""" # Self-Attention __lowerCAmelCase = tax_model['''target''']['''decoder'''][layer_name]['''self_attention''']['''key''']['''kernel'''] __lowerCAmelCase = tax_model['''target''']['''decoder'''][layer_name]['''self_attention''']['''out''']['''kernel'''] __lowerCAmelCase = tax_model['''target''']['''decoder'''][layer_name]['''self_attention''']['''query''']['''kernel'''] __lowerCAmelCase = tax_model['''target''']['''decoder'''][layer_name]['''self_attention''']['''value''']['''kernel'''] # Layer Normalization __lowerCAmelCase = tax_model['''target''']['''decoder'''][layer_name]['''pre_self_attention_layer_norm'''][ '''scale''' ] # Encoder-Decoder-Attention __lowerCAmelCase = tax_model['''target''']['''decoder'''][layer_name]['''encoder_decoder_attention'''] __lowerCAmelCase = tax_enc_dec_attention_module['''key''']['''kernel'''] __lowerCAmelCase = tax_enc_dec_attention_module['''out''']['''kernel'''] __lowerCAmelCase = tax_enc_dec_attention_module['''query''']['''kernel'''] __lowerCAmelCase = tax_enc_dec_attention_module['''value''']['''kernel'''] # Layer Normalization __lowerCAmelCase = tax_model['''target''']['''decoder'''][layer_name]['''pre_cross_attention_layer_norm''']['''scale'''] # MLP if split_mlp_wi: __lowerCAmelCase = tax_model['''target''']['''decoder'''][layer_name]['''mlp''']['''wi_0''']['''kernel'''] __lowerCAmelCase = tax_model['''target''']['''decoder'''][layer_name]['''mlp''']['''wi_1''']['''kernel'''] else: __lowerCAmelCase = tax_model['''target''']['''decoder'''][layer_name]['''mlp''']['''wi''']['''kernel'''] __lowerCAmelCase = tax_model['''target''']['''decoder'''][layer_name]['''mlp''']['''wo''']['''kernel'''] # Layer Normalization __lowerCAmelCase = tax_model['''target''']['''decoder'''][layer_name]['''pre_mlp_layer_norm''']['''scale'''] # Assigning __lowerCAmelCase = flax_model.params['''decoder''']['''block'''][str(lowerCAmelCase__)]['''layer'''] __lowerCAmelCase = tax_attention_key __lowerCAmelCase = tax_attention_out __lowerCAmelCase = tax_attention_query __lowerCAmelCase = tax_attention_value __lowerCAmelCase = tax_pre_attention_layer_norm __lowerCAmelCase = tax_enc_dec_attention_key __lowerCAmelCase = tax_enc_dec_attention_out __lowerCAmelCase = tax_enc_dec_attention_query __lowerCAmelCase = tax_enc_dec_attention_value __lowerCAmelCase = tax_cross_layer_norm if split_mlp_wi: __lowerCAmelCase = tax_mlp_wi_a __lowerCAmelCase = tax_mlp_wi_a else: __lowerCAmelCase = tax_mlp_wi __lowerCAmelCase = tax_mlp_wo __lowerCAmelCase = txa_mlp_layer_norm __lowerCAmelCase = flax_model_decoder_layer_block # Decoder Normalization __lowerCAmelCase = tax_model['''target''']['''decoder''']['''decoder_norm''']['''scale'''] __lowerCAmelCase = txa_decoder_norm # Only for layer 0: __lowerCAmelCase = tax_model['''target''']['''decoder''']['''relpos_bias''']['''rel_embedding'''].T __lowerCAmelCase = tax_decoder_rel_embedding # Token Embeddings __lowerCAmelCase = tax_model['''target''']['''token_embedder''']['''embedding'''] __lowerCAmelCase = txa_token_embeddings # LM Head (only in v1.1 and LongT5 checkpoints) if "logits_dense" in tax_model["target"]["decoder"]: __lowerCAmelCase = tax_model['''target''']['''decoder''']['''logits_dense''']['''kernel'''] flax_model.save_pretrained(lowerCAmelCase__) print('''T5X Model was sucessfully converted!''') if __name__ == "__main__": _UpperCAmelCase : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--t5x_checkpoint_path""", default=None, type=str, required=True, help="""Path the T5X checkpoint.""" ) parser.add_argument("""--config_name""", default=None, type=str, required=True, help="""Config name of LongT5/T5 model.""") parser.add_argument( """--flax_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output FLAX model.""" ) _UpperCAmelCase : int = parser.parse_args() convert_tax_checkpoint_to_flax(args.tax_checkpoint_path, args.config_name, args.flax_dump_folder_path)
174
"""simple docstring""" lowercase_ = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" def lowercase ( lowerCAmelCase__ : bytes ) -> bytes: # Make sure the supplied data is a bytes-like object if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): __a = f'''a bytes-like object is required, not \'{data.__class__.__name__}\'''' raise TypeError(lowerCAmelCase__ ) __a = ''''''.join(bin(lowerCAmelCase__ )[2:].zfill(8 ) for byte in data ) __a = len(lowerCAmelCase__ ) % 6 != 0 if padding_needed: # The padding that will be added later __a = b'''=''' * ((6 - len(lowerCAmelCase__ ) % 6) // 2) # Append binary_stream with arbitrary binary digits (0's by default) to make its # length a multiple of 6. binary_stream += "0" * (6 - len(lowerCAmelCase__ ) % 6) else: __a = b'''''' # Encode every 6 binary digits to their corresponding Base64 character return ( "".join( B64_CHARSET[int(binary_stream[index : index + 6] , 2 )] for index in range(0 , len(lowerCAmelCase__ ) , 6 ) ).encode() + padding ) def lowercase ( lowerCAmelCase__ : str ) -> bytes: # Make sure encoded_data is either a string or a bytes-like object if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): __a = ( '''argument should be a bytes-like object or ASCII string, ''' f'''not \'{encoded_data.__class__.__name__}\'''' ) raise TypeError(lowerCAmelCase__ ) # In case encoded_data is a bytes-like object, make sure it contains only # ASCII characters so we convert it to a string object if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): try: __a = encoded_data.decode('''utf-8''' ) except UnicodeDecodeError: raise ValueError('''base64 encoded data should only contain ASCII characters''' ) __a = encoded_data.count('''=''' ) # Check if the encoded string contains non base64 characters if padding: assert all( char in B64_CHARSET for char in encoded_data[:-padding] ), "Invalid base64 character(s) found." else: assert all( char in B64_CHARSET for char in encoded_data ), "Invalid base64 character(s) found." # Check the padding assert len(lowerCAmelCase__ ) % 4 == 0 and padding < 3, "Incorrect padding" if padding: # Remove padding if there is one __a = encoded_data[:-padding] __a = ''''''.join( bin(B64_CHARSET.index(lowerCAmelCase__ ) )[2:].zfill(6 ) for char in encoded_data )[: -padding * 2] else: __a = ''''''.join( bin(B64_CHARSET.index(lowerCAmelCase__ ) )[2:].zfill(6 ) for char in encoded_data ) __a = [ int(binary_stream[index : index + 8] , 2 ) for index in range(0 , len(lowerCAmelCase__ ) , 8 ) ] return bytes(lowerCAmelCase__ ) if __name__ == "__main__": import doctest doctest.testmod()
45
0
from math import factorial, pi def a__ ( snake_case , snake_case = 30 ): """simple docstring""" if not isinstance(lowerCAmelCase__ , (int, float) ): raise ValueError('''maclaurin_sin() requires either an int or float for theta''' ) if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) or accuracy <= 0: raise ValueError('''maclaurin_sin() requires a positive int for accuracy''' ) __SCREAMING_SNAKE_CASE : Dict = float(lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : Dict = theta // (2 * pi) theta -= 2 * div * pi return sum( (-1) ** r * theta ** (2 * r + 1) / factorial(2 * r + 1 ) for r in range(lowerCAmelCase__ ) ) def a__ ( snake_case , snake_case = 30 ): """simple docstring""" if not isinstance(lowerCAmelCase__ , (int, float) ): raise ValueError('''maclaurin_cos() requires either an int or float for theta''' ) if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) or accuracy <= 0: raise ValueError('''maclaurin_cos() requires a positive int for accuracy''' ) __SCREAMING_SNAKE_CASE : int = float(lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : Tuple = theta // (2 * pi) theta -= 2 * div * pi return sum((-1) ** r * theta ** (2 * r) / factorial(2 * r ) for r in range(lowerCAmelCase__ ) ) if __name__ == "__main__": import doctest doctest.testmod() print(maclaurin_sin(10)) print(maclaurin_sin(-10)) print(maclaurin_sin(10, 15)) print(maclaurin_sin(-10, 15)) print(maclaurin_cos(5)) print(maclaurin_cos(-5)) print(maclaurin_cos(10, 15)) print(maclaurin_cos(-10, 15))
303
"""simple docstring""" 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 __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = inspect.getfile(accelerate.test_utils ) __a = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_script.py'''] ) __a = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_distributed_data_loop.py'''] ) __a = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_ops.py'''] ) @require_multi_gpu def __UpperCAmelCase ( self ): print(f'''Found {torch.cuda.device_count()} devices.''' ) __a = ['''torchrun''', f'''--nproc_per_node={torch.cuda.device_count()}''', self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(_a , env=os.environ.copy() ) @require_multi_gpu def __UpperCAmelCase ( self ): print(f'''Found {torch.cuda.device_count()} devices.''' ) __a = ['''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(_a , env=os.environ.copy() ) @require_multi_gpu def __UpperCAmelCase ( self ): __a = ['''torchrun''', f'''--nproc_per_node={torch.cuda.device_count()}''', inspect.getfile(self.__class__ )] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(_a , env=os.environ.copy() ) @require_multi_gpu def __UpperCAmelCase ( self ): print(f'''Found {torch.cuda.device_count()} devices, using 2 devices only''' ) __a = ['''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(_a , env=os.environ.copy() ) if __name__ == "__main__": lowercase_ = Accelerator() lowercase_ = (accelerator.state.process_index + 2, 1_0) lowercase_ = torch.randint(0, 1_0, shape).to(accelerator.device) lowercase_ = "" lowercase_ = 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)." lowercase_ = 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." lowercase_ = 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)
45
0
"""simple docstring""" from maths.prime_factors import prime_factors def lowercase ( a__ : int ) -> int: if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): _UpperCamelCase = F'''Input value of [number={number}] must be an integer''' raise TypeError(lowerCAmelCase__ ) if number < 1: raise ValueError('''Input must be a positive integer''' ) return -1 if len(prime_factors(lowerCAmelCase__ ) ) % 2 else 1 if __name__ == "__main__": import doctest doctest.testmod()
256
"""simple docstring""" import numpy as np def lowercase ( lowerCAmelCase__ : np.ndarray , lowerCAmelCase__ : float ) -> np.ndarray: return np.where(vector > 0 , lowerCAmelCase__ , (alpha * (np.exp(lowerCAmelCase__ ) - 1)) ) if __name__ == "__main__": import doctest doctest.testmod()
45
0
"""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 SCREAMING_SNAKE_CASE__:int = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__:Optional[int] = { """google/mobilenet_v1_1.0_224""": """https://huggingface.co/google/mobilenet_v1_1.0_224/resolve/main/config.json""", """google/mobilenet_v1_0.75_192""": """https://huggingface.co/google/mobilenet_v1_0.75_192/resolve/main/config.json""", # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1 } class snake_case__ ( __SCREAMING_SNAKE_CASE ): _snake_case : Optional[int] = 'mobilenet_v1' def __init__( self , lowerCamelCase=3 , lowerCamelCase=224 , lowerCamelCase=1.0 , lowerCamelCase=8 , lowerCamelCase="relu6" , lowerCamelCase=True , lowerCamelCase=0.999 , lowerCamelCase=0.02 , lowerCamelCase=0.001 , **lowerCamelCase , ): super().__init__(**_a ) if depth_multiplier <= 0: raise ValueError("depth_multiplier must be greater than zero." ) __a = num_channels __a = image_size __a = depth_multiplier __a = min_depth __a = hidden_act __a = tf_padding __a = classifier_dropout_prob __a = initializer_range __a = layer_norm_eps class snake_case__ ( __SCREAMING_SNAKE_CASE ): _snake_case : Tuple = version.parse("""1.11""" ) @property def a__ ( self ): return OrderedDict([("pixel_values", {0: "batch"})] ) @property def a__ ( self ): if self.task == "image-classification": return OrderedDict([("logits", {0: "batch"})] ) else: return OrderedDict([("last_hidden_state", {0: "batch"}), ("pooler_output", {0: "batch"})] ) @property def a__ ( self ): return 1E-4
261
"""simple docstring""" def lowercase ( lowerCAmelCase__ : str = "The quick brown fox jumps over the lazy dog" , ) -> bool: __a = set() # Replace all the whitespace in our sentence __a = input_str.replace(''' ''' , '''''' ) for alpha in input_str: if "a" <= alpha.lower() <= "z": frequency.add(alpha.lower() ) return len(lowerCAmelCase__ ) == 26 def lowercase ( lowerCAmelCase__ : str = "The quick brown fox jumps over the lazy dog" , ) -> bool: __a = [False] * 26 for char in input_str: if char.islower(): __a = True elif char.isupper(): __a = True return all(lowerCAmelCase__ ) def lowercase ( lowerCAmelCase__ : str = "The quick brown fox jumps over the lazy dog" , ) -> bool: return len({char for char in input_str.lower() if char.isalpha()} ) == 26 def lowercase ( ) -> None: from timeit import timeit __a = '''from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest''' print(timeit('''is_pangram()''' , setup=lowerCAmelCase__ ) ) print(timeit('''is_pangram_faster()''' , setup=lowerCAmelCase__ ) ) print(timeit('''is_pangram_fastest()''' , setup=lowerCAmelCase__ ) ) # 5.348480500048026, 2.6477354579837993, 1.8470395830227062 # 5.036091582966037, 2.644472333951853, 1.8869528750656173 if __name__ == "__main__": import doctest doctest.testmod() benchmark()
45
0
"""simple docstring""" import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler UpperCAmelCase__ = 16 UpperCAmelCase__ = 32 def _UpperCAmelCase ( __lowerCamelCase : Accelerator , __lowerCamelCase : int = 16 , __lowerCamelCase : str = "bert-base-cased" ) -> List[str]: _snake_case = AutoTokenizer.from_pretrained(lowerCAmelCase__ ) _snake_case = load_dataset('''glue''' , '''mrpc''' ) def tokenize_function(__lowerCamelCase : Any ): # max_length=None => use the model max length (it's actually the default) _snake_case = 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 _snake_case = datasets.map( lowerCAmelCase__ , batched=lowerCAmelCase__ , remove_columns=['''idx''', '''sentence1''', '''sentence2'''] , load_from_cache_file=lowerCAmelCase__ ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library _snake_case = tokenized_datasets.rename_column('''label''' , '''labels''' ) def collate_fn(__lowerCamelCase : Any ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(lowerCAmelCase__ , padding='''max_length''' , max_length=1_28 , return_tensors='''pt''' ) return tokenizer.pad(lowerCAmelCase__ , padding='''longest''' , return_tensors='''pt''' ) # Instantiate dataloaders. _snake_case = DataLoader( tokenized_datasets['''train'''] , shuffle=lowerCAmelCase__ , collate_fn=lowerCAmelCase__ , batch_size=lowerCAmelCase__ ) _snake_case = DataLoader( tokenized_datasets['''validation'''] , shuffle=lowerCAmelCase__ , collate_fn=lowerCAmelCase__ , batch_size=lowerCAmelCase__ ) return train_dataloader, eval_dataloader def _UpperCAmelCase ( __lowerCamelCase : List[Any] , __lowerCamelCase : Any ) -> List[str]: # Initialize accelerator _snake_case = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs _snake_case = config['''lr'''] _snake_case = int(config['''num_epochs'''] ) _snake_case = int(config['''seed'''] ) _snake_case = int(config['''batch_size'''] ) _snake_case = args.model_name_or_path set_seed(lowerCAmelCase__ ) _snake_case , _snake_case = get_dataloaders(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) _snake_case = AutoModelForSequenceClassification.from_pretrained(lowerCAmelCase__ , return_dict=lowerCAmelCase__ ) # Instantiate optimizer _snake_case = ( AdamW if accelerator.state.deepspeed_plugin is None or '''optimizer''' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) _snake_case = optimizer_cls(params=model.parameters() , lr=lowerCAmelCase__ ) if accelerator.state.deepspeed_plugin is not None: _snake_case = accelerator.state.deepspeed_plugin.deepspeed_config[ '''gradient_accumulation_steps''' ] else: _snake_case = 1 _snake_case = (len(lowerCAmelCase__ ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): _snake_case = get_linear_schedule_with_warmup( optimizer=lowerCAmelCase__ , num_warmup_steps=0 , num_training_steps=lowerCAmelCase__ , ) else: _snake_case = DummyScheduler(lowerCAmelCase__ , total_num_steps=lowerCAmelCase__ , warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. _snake_case , _snake_case , _snake_case , _snake_case , _snake_case = accelerator.prepare( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # We need to keep track of how many total steps we have iterated over _snake_case = 0 # We also need to keep track of the stating epoch so files are named properly _snake_case = 0 # Now we train the model _snake_case = evaluate.load('''glue''' , '''mrpc''' ) _snake_case = 0 _snake_case = {} for epoch in range(lowerCAmelCase__ , lowerCAmelCase__ ): model.train() for step, batch in enumerate(lowerCAmelCase__ ): _snake_case = model(**lowerCAmelCase__ ) _snake_case = outputs.loss _snake_case = loss / gradient_accumulation_steps accelerator.backward(lowerCAmelCase__ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 model.eval() _snake_case = 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 ) with torch.no_grad(): _snake_case = model(**lowerCAmelCase__ ) _snake_case = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times _snake_case , _snake_case = accelerator.gather( (predictions, batch['''labels''']) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(lowerCAmelCase__ ) - 1: _snake_case = predictions[: len(eval_dataloader.dataset ) - samples_seen] _snake_case = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=lowerCAmelCase__ , references=lowerCAmelCase__ , ) _snake_case = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f'''epoch {epoch}:''' , lowerCAmelCase__ ) _snake_case = eval_metric['''accuracy'''] if best_performance < eval_metric["accuracy"]: _snake_case = eval_metric['''accuracy'''] if args.performance_lower_bound is not None: assert ( args.performance_lower_bound <= best_performance ), f'''Best performance metric {best_performance} is lower than the lower bound {args.performance_lower_bound}''' accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , '''all_results.json''' ) , '''w''' ) as f: json.dump(lowerCAmelCase__ , lowerCAmelCase__ ) def _UpperCAmelCase ( ) -> int: _snake_case = argparse.ArgumentParser(description='''Simple example of training script tracking peak GPU memory usage.''' ) parser.add_argument( '''--model_name_or_path''' , type=lowerCAmelCase__ , default='''bert-base-cased''' , help='''Path to pretrained model or model identifier from huggingface.co/models.''' , required=lowerCAmelCase__ , ) parser.add_argument( '''--output_dir''' , type=lowerCAmelCase__ , default='''.''' , help='''Optional save directory where all checkpoint folders will be stored. Default is the current working directory.''' , ) parser.add_argument( '''--performance_lower_bound''' , type=lowerCAmelCase__ , default=lowerCAmelCase__ , help='''Optional lower bound for the performance metric. If set, the training will throw error when the performance metric drops below this value.''' , ) parser.add_argument( '''--num_epochs''' , type=lowerCAmelCase__ , default=3 , help='''Number of train epochs.''' , ) _snake_case = parser.parse_args() _snake_case = {'''lr''': 2E-5, '''num_epochs''': args.num_epochs, '''seed''': 42, '''batch_size''': 16} training_function(lowerCAmelCase__ , lowerCAmelCase__ ) if __name__ == "__main__": main()
288
"""simple docstring""" import gc import unittest from transformers import CTRLConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, CTRLForSequenceClassification, CTRLLMHeadModel, CTRLModel, ) class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a=14 , _a=7 , _a=True , _a=True , _a=True , _a=True , _a=True , _a=99 , _a=32 , _a=5 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=16 , _a=2 , _a=0.02 , _a=3 , _a=4 , _a=None , ): __a = parent __a = batch_size __a = seq_length __a = is_training __a = use_token_type_ids __a = use_input_mask __a = use_labels __a = use_mc_token_ids __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = type_vocab_size __a = type_sequence_label_size __a = initializer_range __a = num_labels __a = num_choices __a = scope __a = self.vocab_size - 1 def __UpperCAmelCase ( self ): __a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a = None if self.use_input_mask: __a = random_attention_mask([self.batch_size, self.seq_length] ) __a = None if self.use_token_type_ids: __a = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __a = None if self.use_mc_token_ids: __a = ids_tensor([self.batch_size, self.num_choices] , self.seq_length ) __a = None __a = None __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __a = ids_tensor([self.batch_size] , self.num_choices ) __a = self.get_config() __a = ids_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 ) return ( config, input_ids, input_mask, head_mask, token_type_ids, mc_token_ids, sequence_labels, token_labels, choice_labels, ) def __UpperCAmelCase ( self ): return CTRLConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , pad_token_id=self.pad_token_id , ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , *_a ): __a = CTRLModel(config=_a ) model.to(_a ) model.eval() model(_a , token_type_ids=_a , head_mask=_a ) model(_a , token_type_ids=_a ) __a = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(len(result.past_key_values ) , config.n_layer ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , *_a ): __a = CTRLLMHeadModel(_a ) model.to(_a ) model.eval() __a = model(_a , token_type_ids=_a , labels=_a ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self ): __a = self.prepare_config_and_inputs() ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = config_and_inputs __a = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''head_mask''': head_mask} return config, inputs_dict def __UpperCAmelCase ( self , _a , _a , _a , _a , *_a ): __a = self.num_labels __a = CTRLForSequenceClassification(_a ) model.to(_a ) model.eval() __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = model(_a , token_type_ids=_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) @require_torch class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : str = (CTRLModel, CTRLLMHeadModel, CTRLForSequenceClassification) if is_torch_available() else () __UpperCAmelCase : Union[str, Any] = (CTRLLMHeadModel,) if is_torch_available() else () __UpperCAmelCase : Union[str, Any] = ( { 'feature-extraction': CTRLModel, 'text-classification': CTRLForSequenceClassification, 'text-generation': CTRLLMHeadModel, 'zero-shot': CTRLForSequenceClassification, } if is_torch_available() else {} ) __UpperCAmelCase : Optional[Any] = True __UpperCAmelCase : List[Any] = False __UpperCAmelCase : str = False def __UpperCAmelCase ( self , _a , _a , _a , _a , _a ): if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests": # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers. # `CTRLConfig` was never used in pipeline tests, either because of a missing checkpoint or because a tiny # config could not be created. return True return False def __UpperCAmelCase ( self ): __a = CTRLModelTester(self ) __a = ConfigTester(self , config_class=_a , n_embd=37 ) def __UpperCAmelCase ( self ): super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() torch.cuda.empty_cache() def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_ctrl_model(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*_a ) @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def __UpperCAmelCase ( self ): pass @slow def __UpperCAmelCase ( self ): for model_name in CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = CTRLModel.from_pretrained(_a ) self.assertIsNotNone(_a ) @unittest.skip('''The model doesn\'t support left padding''' ) # and it's not used enough to be worth fixing :) def __UpperCAmelCase ( self ): pass @require_torch class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() torch.cuda.empty_cache() @slow def __UpperCAmelCase ( self ): __a = CTRLLMHeadModel.from_pretrained('''ctrl''' ) model.to(_a ) __a = torch.tensor( [[11_859, 0, 1_611, 8]] , dtype=torch.long , device=_a ) # Legal the president is __a = [ 11_859, 0, 1_611, 8, 5, 150, 26_449, 2, 19, 348, 469, 3, 2_595, 48, 20_740, 246_533, 246_533, 19, 30, 5, ] # Legal the president is a good guy and I don't want to lose my job. \n \n I have a __a = model.generate(_a , do_sample=_a ) self.assertListEqual(output_ids[0].tolist() , _a )
45
0
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: float ) -> float: '''simple docstring''' return 1_0 - x * x def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: float , SCREAMING_SNAKE_CASE_: float ) -> float: '''simple docstring''' if equation(lowerCAmelCase__ ) * equation(lowerCAmelCase__ ) >= 0: raise ValueError("Wrong space!" ) A__ = a while (b - a) >= 0.01: # Find middle point A__ = (a + b) / 2 # Check if middle point is root if equation(lowerCAmelCase__ ) == 0.0: break # Decide the side to repeat the steps if equation(lowerCAmelCase__ ) * equation(lowerCAmelCase__ ) < 0: A__ = c else: A__ = c return c if __name__ == "__main__": import doctest doctest.testmod() print(bisection(-2, 5)) print(bisection(0, 6))
68
"""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, ) lowercase_ = {"configuration_xglm": ["XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP", "XGLMConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["XGLMTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["XGLMTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "XGLM_PRETRAINED_MODEL_ARCHIVE_LIST", "XGLMForCausalLM", "XGLMModel", "XGLMPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "FlaxXGLMForCausalLM", "FlaxXGLMModel", "FlaxXGLMPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST", "TFXGLMForCausalLM", "TFXGLMModel", "TFXGLMPreTrainedModel", ] if TYPE_CHECKING: from .configuration_xglm import XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XGLMConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm import XGLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm_fast import XGLMTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xglm import XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, XGLMForCausalLM, XGLMModel, XGLMPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_xglm import FlaxXGLMForCausalLM, FlaxXGLMModel, FlaxXGLMPreTrainedModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, TFXGLMPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure)
45
0
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 ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): _a : Union[str, Any] = KandinskyVaaImgaImgPipeline _a : Optional[Any] = ['image_embeds', 'negative_image_embeds', 'image'] _a : List[Any] = [ 'image_embeds', 'negative_image_embeds', 'image', ] _a : Optional[Any] = [ 'generator', 'height', 'width', 'strength', 'guidance_scale', 'num_inference_steps', 'return_dict', 'guidance_scale', 'num_images_per_prompt', 'output_type', 'return_dict', ] _a : Any = False @property def UpperCAmelCase__ ( self ) -> List[str]: """simple docstring""" return 32 @property def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" return 32 @property def UpperCAmelCase__ ( self ) -> List[Any]: """simple docstring""" return self.time_input_dim @property def UpperCAmelCase__ ( self ) -> Dict: """simple docstring""" return self.time_input_dim * 4 @property def UpperCAmelCase__ ( self ) -> int: """simple docstring""" return 100 @property def UpperCAmelCase__ ( self ) -> List[Any]: """simple docstring""" torch.manual_seed(0 ) _UpperCAmelCase = { '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, } _UpperCAmelCase = UNetaDConditionModel(**_a ) return model @property def UpperCAmelCase__ ( self ) -> Dict: """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 UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" torch.manual_seed(0 ) _UpperCAmelCase = VQModel(**self.dummy_movq_kwargs ) return model def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" _UpperCAmelCase = self.dummy_unet _UpperCAmelCase = self.dummy_movq _UpperCAmelCase = { 'num_train_timesteps': 1000, 'beta_schedule': 'linear', 'beta_start': 0.00085, 'beta_end': 0.012, 'clip_sample': False, 'set_alpha_to_one': False, 'steps_offset': 0, 'prediction_type': 'epsilon', 'thresholding': False, } _UpperCAmelCase = DDIMScheduler(**_a ) _UpperCAmelCase = { 'unet': unet, 'scheduler': scheduler, 'movq': movq, } return components def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=0 ) -> str: """simple docstring""" _UpperCAmelCase = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(_a ) ).to(_a ) _UpperCAmelCase = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( _a ) # create init_image _UpperCAmelCase = floats_tensor((1, 3, 64, 64) , rng=random.Random(_a ) ).to(_a ) _UpperCAmelCase = image.cpu().permute(0 , 2 , 3 , 1 )[0] _UpperCAmelCase = Image.fromarray(np.uinta(_a ) ).convert('RGB' ).resize((256, 256) ) if str(_a ).startswith('mps' ): _UpperCAmelCase = torch.manual_seed(_a ) else: _UpperCAmelCase = torch.Generator(device=_a ).manual_seed(_a ) _UpperCAmelCase = { '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 UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase = 'cpu' _UpperCAmelCase = self.get_dummy_components() _UpperCAmelCase = self.pipeline_class(**_a ) _UpperCAmelCase = pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) _UpperCAmelCase = pipe(**self.get_dummy_inputs(_a ) ) _UpperCAmelCase = output.images _UpperCAmelCase = pipe( **self.get_dummy_inputs(_a ) , return_dict=_a , )[0] _UpperCAmelCase = image[0, -3:, -3:, -1] _UpperCAmelCase = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _UpperCAmelCase = np.array( [0.6199778, 0.63984406, 0.46145785, 0.62944984, 0.5622215, 0.47306132, 0.47441456, 0.4607606, 0.48719263] ) 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 ): def UpperCAmelCase__ ( self ) -> List[str]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase__ ( self ) -> List[Any]: """simple docstring""" _UpperCAmelCase = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinskyv22/kandinskyv22_img2img_frog.npy' ) _UpperCAmelCase = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinsky/cat.png' ) _UpperCAmelCase = 'A red cartoon frog, 4k' _UpperCAmelCase = KandinskyVaaPriorPipeline.from_pretrained( 'kandinsky-community/kandinsky-2-2-prior' , torch_dtype=torch.floataa ) pipe_prior.to(_a ) _UpperCAmelCase = KandinskyVaaImgaImgPipeline.from_pretrained( 'kandinsky-community/kandinsky-2-2-decoder' , torch_dtype=torch.floataa ) _UpperCAmelCase = pipeline.to(_a ) pipeline.set_progress_bar_config(disable=_a ) _UpperCAmelCase = torch.Generator(device='cpu' ).manual_seed(0 ) _UpperCAmelCase , _UpperCAmelCase = pipe_prior( _a , generator=_a , num_inference_steps=5 , negative_prompt='' , ).to_tuple() _UpperCAmelCase = 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' , ) _UpperCAmelCase = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(_a , _a )
329
"""simple docstring""" 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 lowercase_ = re.compile("[^A-Za-z_0-9]") # parameters used in DuplicationIndex lowercase_ = 1_0 lowercase_ = 2_5_6 def lowercase ( lowerCAmelCase__ : List[str] ) -> Optional[MinHash]: if len(lowerCAmelCase__ ) < MIN_NUM_TOKENS: return None __a = MinHash(num_perm=lowerCAmelCase__ ) for token in set(lowerCAmelCase__ ): min_hash.update(token.encode() ) return min_hash def lowercase ( lowerCAmelCase__ : str ) -> Set[str]: return {t for t in NON_ALPHA.split(lowerCAmelCase__ ) if len(t.strip() ) > 0} class __lowerCAmelCase : '''simple docstring''' def __init__( self , *, _a = 0.85 , ): __a = duplication_jaccard_threshold __a = NUM_PERM __a = MinHashLSH(threshold=self._duplication_jaccard_threshold , num_perm=self._num_perm ) __a = defaultdict(_a ) def __UpperCAmelCase ( self , _a , _a ): __a = 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 __UpperCAmelCase ( self ): __a = [] for base, duplicates in self._duplicate_clusters.items(): __a = [base] + list(_a ) # reformat the cluster to be a list of dict __a = [{'''base_index''': el[0], '''repo_name''': el[1], '''path''': el[2]} for el in cluster] duplicate_clusters.append(_a ) return duplicate_clusters def __UpperCAmelCase ( self , _a ): __a = self.get_duplicate_clusters() with open(_a , '''w''' ) as f: json.dump(_a , _a ) def lowercase ( lowerCAmelCase__ : List[str] ) -> int: __a , __a = element __a = 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 lowercase ( lowerCAmelCase__ : Type[Dataset] ) -> str: 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 lowercase ( lowerCAmelCase__ : Type[Dataset] , lowerCAmelCase__ : float ) -> Dict: __a = 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 lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : str ) -> float: __a = get_tokens(lowerCAmelCase__ ) __a = get_tokens(lowerCAmelCase__ ) return len(tokensa & tokensa ) / len(tokensa | tokensa ) lowercase_ = None def lowercase ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Union[str, Any] ) -> Any: __a = [] for elementa in cluster: __a = _shared_dataset[elementa['''base_index''']]['''content'''] for elementa in extremes: __a = _shared_dataset[elementa['''base_index''']]['''content'''] if jaccard_similarity(lowerCAmelCase__ , lowerCAmelCase__ ) >= jaccard_threshold: elementa["copies"] += 1 break else: __a = 1 extremes.append(lowerCAmelCase__ ) return extremes def lowercase ( lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Optional[int] ) -> Optional[int]: global _shared_dataset __a = dataset __a = [] __a = 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 lowercase ( lowerCAmelCase__ : Type[Dataset] , lowerCAmelCase__ : float = 0.85 ) -> Tuple[Type[Dataset], List[List[Dict]]]: __a = make_duplicate_clusters(lowerCAmelCase__ , lowerCAmelCase__ ) __a = {x['''base_index'''] for cluster in duplicate_clusters for x in cluster} __a = {} __a = find_extremes(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) for extremes in extremes_clusters: for element in extremes: __a = element __a = duplicate_indices - set(extreme_dict.keys() ) __a = 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: __a = element['''base_index'''] in extreme_dict if element["is_extreme"]: __a = 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
45
0
'''simple docstring''' class A__ : # Public class to implement a graph """simple docstring""" def __init__( self : Union[str, Any] , lowerCAmelCase__ : int , lowerCAmelCase__ : Any , lowerCAmelCase__ : Dict ) -> List[str]: """simple docstring""" _UpperCAmelCase : Optional[int] = row _UpperCAmelCase : int = col _UpperCAmelCase : Optional[int] = graph def _lowerCAmelCase ( self : Any , lowerCAmelCase__ : str , lowerCAmelCase__ : str , lowerCAmelCase__ : int ) -> Dict: """simple docstring""" return ( 0 <= i < self.ROW and 0 <= j < self.COL and not visited[i][j] and self.graph[i][j] ) def _lowerCAmelCase ( self : Union[str, Any] , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Optional[int] ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase : List[Any] = [-1, -1, -1, 0, 0, 1, 1, 1] # Coordinate order _UpperCAmelCase : Union[str, Any] = [-1, 0, 1, -1, 1, -1, 0, 1] _UpperCAmelCase : Optional[int] = True # Make those cells visited for k in range(8 ): if self.is_safe(i + row_nbr[k] , j + col_nbr[k] , _a ): self.diffs(i + row_nbr[k] , j + col_nbr[k] , _a ) def _lowerCAmelCase ( self : int ) -> str: # And finally, count all islands. """simple docstring""" _UpperCAmelCase : Any = [[False for j in range(self.COL )] for i in range(self.ROW )] _UpperCAmelCase : str = 0 for i in range(self.ROW ): for j in range(self.COL ): if visited[i][j] is False and self.graph[i][j] == 1: self.diffs(_a , _a , _a ) count += 1 return count
145
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowercase_ = { "configuration_roformer": ["ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "RoFormerConfig", "RoFormerOnnxConfig"], "tokenization_roformer": ["RoFormerTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["RoFormerTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "RoFormerForCausalLM", "RoFormerForMaskedLM", "RoFormerForMultipleChoice", "RoFormerForQuestionAnswering", "RoFormerForSequenceClassification", "RoFormerForTokenClassification", "RoFormerLayer", "RoFormerModel", "RoFormerPreTrainedModel", "load_tf_weights_in_roformer", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TFRoFormerForCausalLM", "TFRoFormerForMaskedLM", "TFRoFormerForMultipleChoice", "TFRoFormerForQuestionAnswering", "TFRoFormerForSequenceClassification", "TFRoFormerForTokenClassification", "TFRoFormerLayer", "TFRoFormerModel", "TFRoFormerPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "FlaxRoFormerForMaskedLM", "FlaxRoFormerForMultipleChoice", "FlaxRoFormerForQuestionAnswering", "FlaxRoFormerForSequenceClassification", "FlaxRoFormerForTokenClassification", "FlaxRoFormerModel", "FlaxRoFormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_roformer import ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, RoFormerConfig, RoFormerOnnxConfig from .tokenization_roformer import RoFormerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roformer_fast import RoFormerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roformer import ( ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, RoFormerForCausalLM, RoFormerForMaskedLM, RoFormerForMultipleChoice, RoFormerForQuestionAnswering, RoFormerForSequenceClassification, RoFormerForTokenClassification, RoFormerLayer, RoFormerModel, RoFormerPreTrainedModel, load_tf_weights_in_roformer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roformer import ( TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerLayer, TFRoFormerModel, TFRoFormerPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roformer import ( FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, FlaxRoFormerPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
45
0
import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_albert import AlbertTokenizer else: __a :Optional[int] = None __a :Tuple = logging.get_logger(__name__) __a :Union[str, Any] = {'vocab_file': 'spiece.model', 'tokenizer_file': 'tokenizer.json'} __a :Union[str, Any] = { 'vocab_file': { 'albert-base-v1': 'https://huggingface.co/albert-base-v1/resolve/main/spiece.model', 'albert-large-v1': 'https://huggingface.co/albert-large-v1/resolve/main/spiece.model', 'albert-xlarge-v1': 'https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model', 'albert-xxlarge-v1': 'https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model', 'albert-base-v2': 'https://huggingface.co/albert-base-v2/resolve/main/spiece.model', 'albert-large-v2': 'https://huggingface.co/albert-large-v2/resolve/main/spiece.model', 'albert-xlarge-v2': 'https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model', 'albert-xxlarge-v2': 'https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model', }, 'tokenizer_file': { 'albert-base-v1': 'https://huggingface.co/albert-base-v1/resolve/main/tokenizer.json', 'albert-large-v1': 'https://huggingface.co/albert-large-v1/resolve/main/tokenizer.json', 'albert-xlarge-v1': 'https://huggingface.co/albert-xlarge-v1/resolve/main/tokenizer.json', 'albert-xxlarge-v1': 'https://huggingface.co/albert-xxlarge-v1/resolve/main/tokenizer.json', 'albert-base-v2': 'https://huggingface.co/albert-base-v2/resolve/main/tokenizer.json', 'albert-large-v2': 'https://huggingface.co/albert-large-v2/resolve/main/tokenizer.json', 'albert-xlarge-v2': 'https://huggingface.co/albert-xlarge-v2/resolve/main/tokenizer.json', 'albert-xxlarge-v2': 'https://huggingface.co/albert-xxlarge-v2/resolve/main/tokenizer.json', }, } __a :Optional[int] = { 'albert-base-v1': 512, 'albert-large-v1': 512, 'albert-xlarge-v1': 512, 'albert-xxlarge-v1': 512, 'albert-base-v2': 512, 'albert-large-v2': 512, 'albert-xlarge-v2': 512, 'albert-xxlarge-v2': 512, } __a :int = '▁' class _a ( __SCREAMING_SNAKE_CASE ): """simple docstring""" _lowerCamelCase : List[str] = VOCAB_FILES_NAMES _lowerCamelCase : List[Any] = PRETRAINED_VOCAB_FILES_MAP _lowerCamelCase : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowerCamelCase : int = AlbertTokenizer def __init__( self : Dict , UpperCAmelCase : Tuple=None , UpperCAmelCase : Tuple=None , UpperCAmelCase : str=True , UpperCAmelCase : Dict=True , UpperCAmelCase : Any=False , UpperCAmelCase : Any="[CLS]" , UpperCAmelCase : List[str]="[SEP]" , UpperCAmelCase : int="<unk>" , UpperCAmelCase : Tuple="[SEP]" , UpperCAmelCase : Optional[Any]="<pad>" , UpperCAmelCase : List[str]="[CLS]" , UpperCAmelCase : Optional[Any]="[MASK]" , **UpperCAmelCase : Union[str, Any] , ): # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. A_ = ( AddedToken(_a , lstrip=_a , rstrip=_a , normalized=_a ) if isinstance(_a , _a ) else mask_token ) super().__init__( _a , tokenizer_file=_a , do_lower_case=_a , remove_space=_a , keep_accents=_a , bos_token=_a , eos_token=_a , unk_token=_a , sep_token=_a , pad_token=_a , cls_token=_a , mask_token=_a , **_a , ) A_ = do_lower_case A_ = remove_space A_ = keep_accents A_ = vocab_file A_ = False if not self.vocab_file else True def __A ( self : Any , UpperCAmelCase : List[Any] , UpperCAmelCase : List[str] = None ): A_ = [self.sep_token_id] A_ = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def __A ( self : Optional[Any] , UpperCAmelCase : List[Any] , UpperCAmelCase : str = None ): A_ = [self.sep_token_id] A_ = [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 __A ( self : List[str] , UpperCAmelCase : List[str] , UpperCAmelCase : Dict = None ): if not self.can_save_slow_tokenizer: raise ValueError( "Your fast tokenizer does not have the necessary information to save the vocabulary for a slow " "tokenizer." ) if not os.path.isdir(_a ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return A_ = 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 ): copyfile(self.vocab_file , _a ) return (out_vocab_file,)
312
"""simple docstring""" import warnings from ..trainer import Trainer from ..utils import logging lowercase_ = logging.get_logger(__name__) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a=None , **_a ): warnings.warn( '''`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` ''' '''instead.''' , _a , ) super().__init__(args=_a , **_a )
45
0
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 ): '''simple docstring''' def a__ ( self : str ) -> Optional[Any]: """simple docstring""" lowerCamelCase_ = inspect.getfile(accelerate.test_utils ) lowerCamelCase_ = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['scripts', 'test_script.py'] ) lowerCamelCase_ = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ['scripts', 'test_distributed_data_loop.py'] ) lowerCamelCase_ = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['scripts', 'test_ops.py'] ) @require_multi_gpu def a__ ( self : List[Any] ) -> Any: """simple docstring""" print(f"""Found {torch.cuda.device_count()} devices.""" ) lowerCamelCase_ = ['torchrun', f"""--nproc_per_node={torch.cuda.device_count()}""", self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(_a , env=os.environ.copy() ) @require_multi_gpu def a__ ( self : Tuple ) -> List[Any]: """simple docstring""" print(f"""Found {torch.cuda.device_count()} devices.""" ) lowerCamelCase_ = ['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(_a , env=os.environ.copy() ) @require_multi_gpu def a__ ( self : List[str] ) -> List[Any]: """simple docstring""" lowerCamelCase_ = ['torchrun', f"""--nproc_per_node={torch.cuda.device_count()}""", inspect.getfile(self.__class__ )] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(_a , env=os.environ.copy() ) @require_multi_gpu def a__ ( self : str ) -> Any: """simple docstring""" print(f"""Found {torch.cuda.device_count()} devices, using 2 devices only""" ) lowerCamelCase_ = ['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(_a , env=os.environ.copy() ) if __name__ == "__main__": lowerCamelCase : List[Any] = Accelerator() lowerCamelCase : List[Any] = (accelerator.state.process_index + 2, 10) lowerCamelCase : Dict = torch.randint(0, 10, shape).to(accelerator.device) lowerCamelCase : Tuple = "" lowerCamelCase : Optional[Any] = 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)." lowerCamelCase : Union[str, Any] = 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." lowerCamelCase : Union[str, Any] = 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)
204
"""simple docstring""" import math def lowercase ( lowerCAmelCase__ : list , lowerCAmelCase__ : int ) -> int: __a = len(lowerCAmelCase__ ) __a = int(math.floor(math.sqrt(lowerCAmelCase__ ) ) ) __a = 0 while arr[min(lowerCAmelCase__ , lowerCAmelCase__ ) - 1] < x: __a = step step += int(math.floor(math.sqrt(lowerCAmelCase__ ) ) ) if prev >= n: return -1 while arr[prev] < x: __a = prev + 1 if prev == min(lowerCAmelCase__ , lowerCAmelCase__ ): return -1 if arr[prev] == x: return prev return -1 if __name__ == "__main__": lowercase_ = input("Enter numbers separated by a comma:\n").strip() lowercase_ = [int(item) for item in user_input.split(",")] lowercase_ = int(input("Enter the number to be searched:\n")) lowercase_ = jump_search(arr, x) if res == -1: print("Number not found!") else: print(F'''Number {x} is at index {res}''')
45
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowerCAmelCase : List[str] = logging.get_logger(__name__) _lowerCAmelCase : Optional[int] = { '''facebook/xmod-base''': '''https://huggingface.co/facebook/xmod-base/resolve/main/config.json''', '''facebook/xmod-large-prenorm''': '''https://huggingface.co/facebook/xmod-large-prenorm/resolve/main/config.json''', '''facebook/xmod-base-13-125k''': '''https://huggingface.co/facebook/xmod-base-13-125k/resolve/main/config.json''', '''facebook/xmod-base-30-125k''': '''https://huggingface.co/facebook/xmod-base-30-125k/resolve/main/config.json''', '''facebook/xmod-base-30-195k''': '''https://huggingface.co/facebook/xmod-base-30-195k/resolve/main/config.json''', '''facebook/xmod-base-60-125k''': '''https://huggingface.co/facebook/xmod-base-60-125k/resolve/main/config.json''', '''facebook/xmod-base-60-265k''': '''https://huggingface.co/facebook/xmod-base-60-265k/resolve/main/config.json''', '''facebook/xmod-base-75-125k''': '''https://huggingface.co/facebook/xmod-base-75-125k/resolve/main/config.json''', '''facebook/xmod-base-75-269k''': '''https://huggingface.co/facebook/xmod-base-75-269k/resolve/main/config.json''', } class __magic_name__ ( __SCREAMING_SNAKE_CASE ): """simple docstring""" __UpperCamelCase = 'xmod' def __init__( self :str , snake_case :Any=30_522 , snake_case :int=768 , snake_case :List[Any]=12 , snake_case :Tuple=12 , snake_case :List[Any]=3_072 , snake_case :Optional[Any]="gelu" , snake_case :Optional[Any]=0.1 , snake_case :List[Any]=0.1 , snake_case :Union[str, Any]=512 , snake_case :Dict=2 , snake_case :Optional[Any]=0.02 , snake_case :List[Any]=1e-12 , snake_case :Optional[int]=1 , snake_case :List[str]=0 , snake_case :List[Any]=2 , snake_case :int="absolute" , snake_case :Optional[Any]=True , snake_case :Union[str, Any]=None , snake_case :Dict=False , snake_case :str=2 , snake_case :Optional[int]=False , snake_case :Any=True , snake_case :List[Any]=True , snake_case :Union[str, Any]=("en_XX",) , snake_case :Optional[Any]=None , **snake_case :List[Any] , ): '''simple docstring''' super().__init__(pad_token_id=_a , bos_token_id=_a , eos_token_id=_a , **_a ) A_ : Dict = vocab_size A_ : int = hidden_size A_ : str = num_hidden_layers A_ : Union[str, Any] = num_attention_heads A_ : Optional[int] = hidden_act A_ : Union[str, Any] = intermediate_size A_ : int = hidden_dropout_prob A_ : str = attention_probs_dropout_prob A_ : Union[str, Any] = max_position_embeddings A_ : int = type_vocab_size A_ : str = initializer_range A_ : str = layer_norm_eps A_ : str = position_embedding_type A_ : List[str] = use_cache A_ : Dict = classifier_dropout A_ : Optional[Any] = pre_norm A_ : Optional[int] = adapter_reduction_factor A_ : Optional[Any] = adapter_layer_norm A_ : Tuple = adapter_reuse_layer_norm A_ : Optional[Any] = ln_before_adapter A_ : Optional[int] = list(_a ) A_ : Union[str, Any] = default_language class __magic_name__ ( __SCREAMING_SNAKE_CASE ): """simple docstring""" @property def SCREAMING_SNAKE_CASE ( self :List[Any] ): '''simple docstring''' if self.task == "multiple-choice": A_ : Union[str, Any] = {0: "batch", 1: "choice", 2: "sequence"} else: A_ : int = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
300
"""simple docstring""" lowercase_ = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] lowercase_ = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] lowercase_ = { 0: "Sunday", 1: "Monday", 2: "Tuesday", 3: "Wednesday", 4: "Thursday", 5: "Friday", 6: "Saturday", } def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : int , lowerCAmelCase__ : int ) -> str: assert len(str(lowerCAmelCase__ ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 12, "month should be between 1 to 12" assert 1 <= day <= 31, "day should be between 1 to 31" # Doomsday algorithm: __a = year // 100 __a = (5 * (century % 4) + 2) % 7 __a = year % 100 __a = centurian % 12 __a = ( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 __a = ( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 400) == 0) else DOOMSDAY_LEAP[month - 1] ) __a = (dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
45
0
'''simple docstring''' import io import itertools import json from dataclasses import dataclass from typing import Optional import pyarrow as pa import pyarrow.json as paj import datasets from datasets.table import table_cast from datasets.utils.file_utils import readline _UpperCAmelCase : Optional[int] = datasets.utils.logging.get_logger(__name__) @dataclass class a__ ( datasets.BuilderConfig ): """simple docstring""" __UpperCamelCase : Optional[datasets.Features] = None __UpperCamelCase : str = "utf-8" __UpperCamelCase : Optional[str] = None __UpperCamelCase : Optional[str] = None __UpperCamelCase : bool = True # deprecated __UpperCamelCase : Optional[int] = None # deprecated __UpperCamelCase : int = 10 << 20 # 10MB __UpperCamelCase : Optional[bool] = None class a__ ( datasets.ArrowBasedBuilder ): """simple docstring""" __UpperCamelCase : Optional[Any] = JsonConfig def _snake_case (self ): if self.config.block_size is not None: logger.warning('''The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead''' ) __lowerCAmelCase = self.config.block_size if self.config.use_threads is not True: logger.warning( '''The JSON loader parameter `use_threads` is deprecated and doesn\'t have any effect anymore.''' ) if self.config.newlines_in_values is not None: raise ValueError('''The JSON loader parameter `newlines_in_values` is no longer supported''' ) return datasets.DatasetInfo(features=self.config.features ) def _snake_case (self , __lowercase ): if not self.config.data_files: raise ValueError(F"""At least one data file must be specified, but got data_files={self.config.data_files}""" ) __lowerCAmelCase = dl_manager.download_and_extract(self.config.data_files ) if isinstance(_a , (str, list, tuple) ): __lowerCAmelCase = data_files if isinstance(_a , _a ): __lowerCAmelCase = [files] __lowerCAmelCase = [dl_manager.iter_files(_a ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'''files''': files} )] __lowerCAmelCase = [] for split_name, files in data_files.items(): if isinstance(_a , _a ): __lowerCAmelCase = [files] __lowerCAmelCase = [dl_manager.iter_files(_a ) for file in files] splits.append(datasets.SplitGenerator(name=_a , gen_kwargs={'''files''': files} ) ) return splits def _snake_case (self , __lowercase ): if self.config.features is not None: # adding missing columns for column_name in set(self.config.features ) - set(pa_table.column_names ): __lowerCAmelCase = self.config.features.arrow_schema.field(_a ).type __lowerCAmelCase = pa_table.append_column(_a , pa.array([None] * len(_a ) , type=_a ) ) # more expensive cast to support nested structures with keys in a different order # allows str <-> int/float or str to Audio for example __lowerCAmelCase = table_cast(_a , self.config.features.arrow_schema ) return pa_table def _snake_case (self , __lowercase ): for file_idx, file in enumerate(itertools.chain.from_iterable(_a ) ): # If the file is one json object and if we need to look at the list of items in one specific field if self.config.field is not None: with open(_a , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f: __lowerCAmelCase = json.load(_a ) # We keep only the field we are interested in __lowerCAmelCase = dataset[self.config.field] # We accept two format: a list of dicts or a dict of lists if isinstance(_a , (list, tuple) ): __lowerCAmelCase = set().union(*[row.keys() for row in dataset] ) __lowerCAmelCase = {col: [row.get(_a ) for row in dataset] for col in keys} else: __lowerCAmelCase = dataset __lowerCAmelCase = pa.Table.from_pydict(_a ) yield file_idx, self._cast_table(_a ) # If the file has one json object per line else: with open(_a , '''rb''' ) as f: __lowerCAmelCase = 0 # Use block_size equal to the chunk size divided by 32 to leverage multithreading # Set a default minimum value of 16kB if the chunk size is really small __lowerCAmelCase = max(self.config.chunksize // 32 , 16 << 10 ) __lowerCAmelCase = ( self.config.encoding_errors if self.config.encoding_errors is not None else '''strict''' ) while True: __lowerCAmelCase = f.read(self.config.chunksize ) if not batch: break # Finish current line try: batch += f.readline() except (AttributeError, io.UnsupportedOperation): batch += readline(_a ) # PyArrow only accepts utf-8 encoded bytes if self.config.encoding != "utf-8": __lowerCAmelCase = batch.decode(self.config.encoding , errors=_a ).encode('''utf-8''' ) try: while True: try: __lowerCAmelCase = paj.read_json( io.BytesIO(_a ) , read_options=paj.ReadOptions(block_size=_a ) ) break except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e: if ( isinstance(_a , pa.ArrowInvalid ) and "straddling" not in str(_a ) or block_size > len(_a ) ): raise else: # Increase the block size in case it was too small. # The block size will be reset for the next file. logger.debug( F"""Batch of {len(_a )} bytes couldn\'t be parsed with block_size={block_size}. Retrying with block_size={block_size * 2}.""" ) block_size *= 2 except pa.ArrowInvalid as e: try: with open( _a , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f: __lowerCAmelCase = json.load(_a ) except json.JSONDecodeError: logger.error(F"""Failed to read file \'{file}\' with error {type(_a )}: {e}""" ) raise e # If possible, parse the file as a list of json objects and exit the loop if isinstance(_a , _a ): # list is the only sequence type supported in JSON try: __lowerCAmelCase = set().union(*[row.keys() for row in dataset] ) __lowerCAmelCase = {col: [row.get(_a ) for row in dataset] for col in keys} __lowerCAmelCase = pa.Table.from_pydict(_a ) except (pa.ArrowInvalid, AttributeError) as e: logger.error(F"""Failed to read file \'{file}\' with error {type(_a )}: {e}""" ) raise ValueError(F"""Not able to read records in the JSON file at {file}.""" ) from None yield file_idx, self._cast_table(_a ) break else: logger.error(F"""Failed to read file \'{file}\' with error {type(_a )}: {e}""" ) raise ValueError( F"""Not able to read records in the JSON file at {file}. """ F"""You should probably indicate the field of the JSON file containing your records. """ F"""This JSON file contain the following fields: {str(list(dataset.keys() ) )}. """ F"""Select the correct one and provide it as `field=\'XXX\'` to the dataset loading method. """ ) from None # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(_a ) batch_idx += 1
174
"""simple docstring""" def lowercase ( lowerCAmelCase__ : list ) -> bool: if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise ValueError('''Input series is not valid, valid series - [2, 4, 6]''' ) if len(lowerCAmelCase__ ) == 0: raise ValueError('''Input list must be a non empty list''' ) if len(lowerCAmelCase__ ) == 1: return True __a = series[1] - series[0] for index in range(len(lowerCAmelCase__ ) - 1 ): if series[index + 1] - series[index] != common_diff: return False return True def lowercase ( lowerCAmelCase__ : list ) -> float: if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise ValueError('''Input series is not valid, valid series - [2, 4, 6]''' ) if len(lowerCAmelCase__ ) == 0: raise ValueError('''Input list must be a non empty list''' ) __a = 0 for val in series: answer += val return answer / len(lowerCAmelCase__ ) if __name__ == "__main__": import doctest doctest.testmod()
45
0
import logging import os from .state import PartialState class __UpperCamelCase ( logging.LoggerAdapter ): """simple docstring""" @staticmethod def UpperCAmelCase__ ( _A : int ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[str] = PartialState() return not main_process_only or (main_process_only and state.is_main_process) def UpperCAmelCase__ ( self : int , _A : Optional[Any] , _A : int , *_A : Optional[int] , **_A : Optional[Any] ): """simple docstring""" if PartialState._shared_state == {}: raise RuntimeError( '''You must initialize the accelerate state by calling either `PartialState()` or `Accelerator()` before using the logging utility.''' ) __SCREAMING_SNAKE_CASE : List[str] = kwargs.pop('''main_process_only''' , _a ) __SCREAMING_SNAKE_CASE : Optional[Any] = kwargs.pop('''in_order''' , _a ) if self.isEnabledFor(_a ): if self._should_log(_a ): __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Dict = self.process(_a , _a ) self.logger.log(_a , _a , *_a , **_a ) elif in_order: __SCREAMING_SNAKE_CASE : Union[str, Any] = PartialState() for i in range(state.num_processes ): if i == state.process_index: __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : List[Any] = self.process(_a , _a ) self.logger.log(_a , _a , *_a , **_a ) state.wait_for_everyone() def a__ ( snake_case , snake_case = None ): """simple docstring""" if log_level is None: __SCREAMING_SNAKE_CASE : List[str] = os.environ.get('''ACCELERATE_LOG_LEVEL''' , lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : int = logging.getLogger(lowerCAmelCase__ ) if log_level is not None: logger.setLevel(log_level.upper() ) logger.root.setLevel(log_level.upper() ) return MultiProcessAdapter(lowerCAmelCase__ , {} )
303
"""simple docstring""" from argparse import ArgumentParser, Namespace from ..utils import logging from . import BaseTransformersCLICommand def lowercase ( lowerCAmelCase__ : Namespace ) -> Tuple: return ConvertCommand( args.model_type , args.tf_checkpoint , args.pytorch_dump_output , args.config , args.finetuning_task_name ) lowercase_ = "\ntransformers can only be used from the commandline to convert TensorFlow models in PyTorch, In that case, it requires\nTensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installation instructions.\n" class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' @staticmethod def __UpperCAmelCase ( _a ): __a = parser.add_parser( '''convert''' , help='''CLI tool to run convert model from original author checkpoints to Transformers PyTorch checkpoints.''' , ) train_parser.add_argument('''--model_type''' , type=_a , required=_a , help='''Model\'s type.''' ) train_parser.add_argument( '''--tf_checkpoint''' , type=_a , required=_a , help='''TensorFlow checkpoint path or folder.''' ) train_parser.add_argument( '''--pytorch_dump_output''' , type=_a , required=_a , help='''Path to the PyTorch saved model output.''' ) train_parser.add_argument('''--config''' , type=_a , default='''''' , help='''Configuration file path or folder.''' ) train_parser.add_argument( '''--finetuning_task_name''' , type=_a , default=_a , help='''Optional fine-tuning task name if the TF model was a finetuned model.''' , ) train_parser.set_defaults(func=_a ) def __init__( self , _a , _a , _a , _a , _a , *_a , ): __a = logging.get_logger('''transformers-cli/converting''' ) self._logger.info(f'''Loading model {model_type}''' ) __a = model_type __a = tf_checkpoint __a = pytorch_dump_output __a = config __a = finetuning_task_name def __UpperCAmelCase ( self ): if self._model_type == "albert": try: from ..models.albert.convert_albert_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "bert": try: from ..models.bert.convert_bert_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "funnel": try: from ..models.funnel.convert_funnel_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "t5": try: from ..models.ta.convert_ta_original_tf_checkpoint_to_pytorch import convert_tf_checkpoint_to_pytorch except ImportError: raise ImportError(_a ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "gpt": from ..models.openai.convert_openai_original_tf_checkpoint_to_pytorch import ( convert_openai_checkpoint_to_pytorch, ) convert_openai_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "transfo_xl": try: from ..models.transfo_xl.convert_transfo_xl_original_tf_checkpoint_to_pytorch import ( convert_transfo_xl_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) if "ckpt" in self._tf_checkpoint.lower(): __a = self._tf_checkpoint __a = '''''' else: __a = self._tf_checkpoint __a = '''''' convert_transfo_xl_checkpoint_to_pytorch( _a , self._config , self._pytorch_dump_output , _a ) elif self._model_type == "gpt2": try: from ..models.gpta.convert_gpta_original_tf_checkpoint_to_pytorch import ( convert_gpta_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_gpta_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "xlnet": try: from ..models.xlnet.convert_xlnet_original_tf_checkpoint_to_pytorch import ( convert_xlnet_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_xlnet_checkpoint_to_pytorch( self._tf_checkpoint , self._config , self._pytorch_dump_output , self._finetuning_task_name ) elif self._model_type == "xlm": from ..models.xlm.convert_xlm_original_pytorch_checkpoint_to_pytorch import ( convert_xlm_checkpoint_to_pytorch, ) convert_xlm_checkpoint_to_pytorch(self._tf_checkpoint , self._pytorch_dump_output ) elif self._model_type == "lxmert": from ..models.lxmert.convert_lxmert_original_tf_checkpoint_to_pytorch import ( convert_lxmert_checkpoint_to_pytorch, ) convert_lxmert_checkpoint_to_pytorch(self._tf_checkpoint , self._pytorch_dump_output ) elif self._model_type == "rembert": from ..models.rembert.convert_rembert_tf_checkpoint_to_pytorch import ( convert_rembert_tf_checkpoint_to_pytorch, ) convert_rembert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) else: raise ValueError( '''--model_type should be selected in the list [bert, gpt, gpt2, t5, transfo_xl, xlnet, xlm, lxmert]''' )
45
0
"""simple docstring""" import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConfig, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaForCTC, WavaVecaForPreTraining, WavaVecaProcessor, logging, ) from transformers.models.wavaveca.modeling_wavaveca import WavaVecaForSequenceClassification logging.set_verbosity_info() UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = { """post_extract_proj""": """feature_projection.projection""", """encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""", """self_attn.k_proj""": """encoder.layers.*.attention.k_proj""", """self_attn.v_proj""": """encoder.layers.*.attention.v_proj""", """self_attn.q_proj""": """encoder.layers.*.attention.q_proj""", """self_attn.out_proj""": """encoder.layers.*.attention.out_proj""", """self_attn_layer_norm""": """encoder.layers.*.layer_norm""", """fc1""": """encoder.layers.*.feed_forward.intermediate_dense""", """fc2""": """encoder.layers.*.feed_forward.output_dense""", """final_layer_norm""": """encoder.layers.*.final_layer_norm""", """encoder.layer_norm""": """encoder.layer_norm""", """adapter_layer""": """encoder.layers.*.adapter_layer""", """w2v_model.layer_norm""": """feature_projection.layer_norm""", """quantizer.weight_proj""": """quantizer.weight_proj""", """quantizer.vars""": """quantizer.codevectors""", """project_q""": """project_q""", """final_proj""": """project_hid""", """w2v_encoder.proj""": """lm_head""", """mask_emb""": """masked_spec_embed""", """pooling_layer.linear""": """projector""", """pooling_layer.projection""": """classifier""", } UpperCAmelCase = [ """lm_head""", """quantizer.weight_proj""", """quantizer.codevectors""", """project_q""", """project_hid""", """projector""", """classifier""", ] def lowercase ( a__ : Dict ) -> Union[str, Any]: _UpperCamelCase = {} with open(lowerCAmelCase__ , '''r''' ) as file: for line_number, line in enumerate(lowerCAmelCase__ ): _UpperCamelCase = line.strip() if line: _UpperCamelCase = line.split() _UpperCamelCase = line_number _UpperCamelCase = words[0] _UpperCamelCase = value return result def lowercase ( a__ : int , a__ : str , a__ : Tuple , a__ : Optional[Any] , a__ : Optional[int] ) -> Union[str, Any]: for attribute in key.split('''.''' ): _UpperCamelCase = getattr(lowerCAmelCase__ , lowerCAmelCase__ ) _UpperCamelCase = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(lowerCAmelCase__ ): _UpperCamelCase = PARAM_MAPPING[full_name.split('''.''' )[-1]] _UpperCamelCase = '''param''' if weight_type is not None and weight_type != "param": _UpperCamelCase = getattr(lowerCAmelCase__ , lowerCAmelCase__ ).shape elif weight_type is not None and weight_type == "param": _UpperCamelCase = hf_pointer for attribute in hf_param_name.split('''.''' ): _UpperCamelCase = getattr(lowerCAmelCase__ , lowerCAmelCase__ ) _UpperCamelCase = shape_pointer.shape # let's reduce dimension _UpperCamelCase = value[0] 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 == "param": for attribute in hf_param_name.split('''.''' ): _UpperCamelCase = getattr(lowerCAmelCase__ , lowerCAmelCase__ ) _UpperCamelCase = value else: _UpperCamelCase = value logger.info(F'''{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.''' ) def lowercase ( a__ : Any , a__ : int , a__ : Tuple , a__ : int , a__ : Any ) -> Any: _UpperCamelCase = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(lowerCAmelCase__ ): _UpperCamelCase = PARAM_MAPPING[full_name.split('''.''' )[-1]] _UpperCamelCase = '''param''' if weight_type is not None and weight_type != "param": _UpperCamelCase = '''.'''.join([key, weight_type] ) elif weight_type is not None and weight_type == "param": _UpperCamelCase = '''.'''.join([key, hf_param_name] ) else: _UpperCamelCase = key _UpperCamelCase = value if '''lm_head''' in full_key else value[0] UpperCAmelCase = { """W_a""": """linear_1.weight""", """W_b""": """linear_2.weight""", """b_a""": """linear_1.bias""", """b_b""": """linear_2.bias""", """ln_W""": """norm.weight""", """ln_b""": """norm.bias""", } def lowercase ( a__ : Dict , a__ : Any , a__ : Union[str, Any]=None , a__ : Union[str, Any]=None ) -> List[Any]: _UpperCamelCase = False for key, mapped_key in MAPPING.items(): _UpperCamelCase = '''wav2vec2.''' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0]: _UpperCamelCase = True if "*" in mapped_key: _UpperCamelCase = name.split(lowerCAmelCase__ )[0].split('''.''' )[-2] _UpperCamelCase = mapped_key.replace('''*''' , lowerCAmelCase__ ) 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: # TODO: don't match quantizer.weight_proj _UpperCamelCase = '''weight''' else: _UpperCamelCase = None if hf_dict is not None: rename_dict(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) else: set_recursively(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) return is_used return is_used def lowercase ( a__ : Union[str, Any] , a__ : Optional[int] , a__ : Union[str, Any] ) -> Dict: _UpperCamelCase = [] _UpperCamelCase = fairseq_model.state_dict() _UpperCamelCase = hf_model.wavaveca.feature_extractor for name, value in fairseq_dict.items(): _UpperCamelCase = False if "conv_layers" in name: load_conv_layer( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , hf_model.config.feat_extract_norm == '''group''' , ) _UpperCamelCase = True else: _UpperCamelCase = load_wavaveca_layer(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) if not is_used: unused_weights.append(lowerCAmelCase__ ) logger.warning(F'''Unused weights: {unused_weights}''' ) def lowercase ( a__ : int , a__ : Union[str, Any] , a__ : Dict , a__ : List[str] , a__ : List[Any] ) -> Union[str, Any]: _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(lowerCAmelCase__ ) @torch.no_grad() def lowercase ( a__ : Optional[Any] , a__ : Optional[int] , a__ : int=None , a__ : Optional[Any]=None , a__ : Dict=True , a__ : int=False ) -> Optional[Any]: if config_path is not None: _UpperCamelCase = WavaVecaConfig.from_pretrained(lowerCAmelCase__ ) else: _UpperCamelCase = WavaVecaConfig() if is_seq_class: _UpperCamelCase = read_txt_into_dict(lowerCAmelCase__ ) _UpperCamelCase = idalabel _UpperCamelCase = WavaVecaForSequenceClassification(lowerCAmelCase__ ) _UpperCamelCase = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16000 , padding_value=0 , do_normalize=lowerCAmelCase__ , return_attention_mask=lowerCAmelCase__ , ) feature_extractor.save_pretrained(lowerCAmelCase__ ) elif is_finetuned: if dict_path: _UpperCamelCase = Dictionary.load(lowerCAmelCase__ ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq _UpperCamelCase = target_dict.pad_index _UpperCamelCase = target_dict.bos_index _UpperCamelCase = target_dict.eos_index _UpperCamelCase = len(target_dict.symbols ) _UpperCamelCase = os.path.join(lowerCAmelCase__ , '''vocab.json''' ) if not os.path.isdir(lowerCAmelCase__ ): logger.error('''--pytorch_dump_folder_path ({}) should be a directory'''.format(lowerCAmelCase__ ) ) return os.makedirs(lowerCAmelCase__ , exist_ok=lowerCAmelCase__ ) _UpperCamelCase = target_dict.indices # fairseq has the <pad> and <s> switched _UpperCamelCase = 0 _UpperCamelCase = 1 with open(lowerCAmelCase__ , '''w''' , encoding='''utf-8''' ) as vocab_handle: json.dump(lowerCAmelCase__ , lowerCAmelCase__ ) _UpperCamelCase = WavaVecaCTCTokenizer( lowerCAmelCase__ , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token='''|''' , do_lower_case=lowerCAmelCase__ , ) _UpperCamelCase = True if config.feat_extract_norm == '''layer''' else False _UpperCamelCase = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16000 , padding_value=0 , do_normalize=lowerCAmelCase__ , return_attention_mask=lowerCAmelCase__ , ) _UpperCamelCase = WavaVecaProcessor(feature_extractor=lowerCAmelCase__ , tokenizer=lowerCAmelCase__ ) processor.save_pretrained(lowerCAmelCase__ ) _UpperCamelCase = WavaVecaForCTC(lowerCAmelCase__ ) else: _UpperCamelCase = WavaVecaForPreTraining(lowerCAmelCase__ ) if is_finetuned or is_seq_class: _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] )} ) else: _UpperCamelCase = argparse.Namespace(task='''audio_pretraining''' ) _UpperCamelCase = fairseq.tasks.setup_task(lowerCAmelCase__ ) _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=lowerCAmelCase__ ) _UpperCamelCase = model[0].eval() recursively_load_weights(lowerCAmelCase__ , lowerCAmelCase__ , not is_finetuned ) hf_wavavec.save_pretrained(lowerCAmelCase__ ) if __name__ == "__main__": UpperCAmelCase = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""") parser.add_argument("""--dict_path""", default=None, type=str, help="""Path to dict of fine-tuned model""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument( """--not_finetuned""", action="""store_true""", help="""Whether the model to convert is a fine-tuned model or not""" ) parser.add_argument( """--is_seq_class""", action="""store_true""", help="""Whether the model to convert is a fine-tuned sequence classification model or not""", ) UpperCAmelCase = parser.parse_args() UpperCAmelCase = not args.not_finetuned and not args.is_seq_class convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, is_finetuned, args.is_seq_class, )
256
"""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 lowercase_ = logging.get_logger(__name__) lowercase_ = { "microsoft/beit-base-patch16-224-pt22k": ( "https://huggingface.co/microsoft/beit-base-patch16-224-pt22k/resolve/main/config.json" ), # See all BEiT models at https://huggingface.co/models?filter=beit } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : List[str] = 'beit' def __init__( self , _a=8_192 , _a=768 , _a=12 , _a=12 , _a=3_072 , _a="gelu" , _a=0.0 , _a=0.0 , _a=0.02 , _a=1E-12 , _a=224 , _a=16 , _a=3 , _a=False , _a=False , _a=False , _a=False , _a=0.1 , _a=0.1 , _a=True , _a=[3, 5, 7, 11] , _a=[1, 2, 3, 6] , _a=True , _a=0.4 , _a=256 , _a=1 , _a=False , _a=255 , **_a , ): super().__init__(**_a ) __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 = initializer_range __a = layer_norm_eps __a = image_size __a = patch_size __a = num_channels __a = use_mask_token __a = use_absolute_position_embeddings __a = use_relative_position_bias __a = use_shared_relative_position_bias __a = layer_scale_init_value __a = drop_path_rate __a = use_mean_pooling # decode head attributes (semantic segmentation) __a = out_indices __a = pool_scales # auxiliary head attributes (semantic segmentation) __a = use_auxiliary_head __a = auxiliary_loss_weight __a = auxiliary_channels __a = auxiliary_num_convs __a = auxiliary_concat_input __a = semantic_loss_ignore_index class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : List[Any] = version.parse('1.11' ) @property def __UpperCAmelCase ( self ): return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def __UpperCAmelCase ( self ): return 1E-4
45
0
"""simple docstring""" import unittest from knapsack import greedy_knapsack as kp class snake_case__ ( unittest.TestCase ): def a__ ( self ): __a = [10, 20, 30, 40, 50, 60] __a = [2, 4, 6, 8, 10, 12] __a = 100 self.assertEqual(kp.calc_profit(_a , _a , _a ) , 210 ) def a__ ( self ): self.assertRaisesRegex(_a , "max_weight must greater than zero." ) def a__ ( self ): self.assertRaisesRegex(_a , "Weight can not be negative." ) def a__ ( self ): self.assertRaisesRegex(_a , "Profit can not be negative." ) def a__ ( self ): self.assertRaisesRegex(_a , "max_weight must greater than zero." ) def a__ ( self ): self.assertRaisesRegex( _a , "The length of profit and weight must be same." ) if __name__ == "__main__": unittest.main()
261
"""simple docstring""" def lowercase ( lowerCAmelCase__ : str ) -> list: if n_term == "": return [] __a = [] for temp in range(int(lowerCAmelCase__ ) ): series.append(f'''1/{temp + 1}''' if series else '''1''' ) return series if __name__ == "__main__": lowercase_ = input("Enter the last number (nth term) of the Harmonic Series") print("Formula of Harmonic Series => 1+1/2+1/3 ..... 1/n") print(harmonic_series(nth_term))
45
0
"""simple docstring""" import logging import random import ray from transformers import RagConfig, RagRetriever, RagTokenizer from transformers.models.rag.retrieval_rag import CustomHFIndex UpperCAmelCase__ = logging.getLogger(__name__) class lowerCAmelCase__ : def __init__( self : str ): _snake_case = False def lowercase ( self : Tuple , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : Optional[int] , _lowerCamelCase : Optional[Any] ): if not self.initialized: _snake_case = RagRetriever( _a , question_encoder_tokenizer=_a , generator_tokenizer=_a , index=_a , init_retrieval=_a , ) _snake_case = True def lowercase ( self : Union[str, Any] ): self.retriever.index.init_index() def lowercase ( self : str , _lowerCamelCase : Tuple , _lowerCamelCase : str ): _snake_case , _snake_case = self.retriever._main_retrieve(_a , _a ) return doc_ids, retrieved_doc_embeds class lowerCAmelCase__ ( __SCREAMING_SNAKE_CASE ): def __init__( self : Any , _lowerCamelCase : List[str] , _lowerCamelCase : int , _lowerCamelCase : Optional[Any] , _lowerCamelCase : Tuple , _lowerCamelCase : List[str]=None ): if index is not None and index.is_initialized() and len(_a ) > 0: raise ValueError( '''When using Ray for distributed fine-tuning, ''' '''you\'ll need to provide the paths instead, ''' '''as the dataset and the index are loaded ''' '''separately. More info in examples/rag/use_own_knowledge_dataset.py ''' ) super().__init__( _a , question_encoder_tokenizer=_a , generator_tokenizer=_a , index=_a , init_retrieval=_a , ) _snake_case = retrieval_workers if len(self.retrieval_workers ) > 0: ray.get( [ worker.create_rag_retriever.remote(_a , _a , _a , _a ) for worker in self.retrieval_workers ] ) def lowercase ( self : List[str] ): logger.info('''initializing retrieval''' ) if len(self.retrieval_workers ) > 0: ray.get([worker.init_retrieval.remote() for worker in self.retrieval_workers] ) else: # Non-distributed training. Load index into this same process. self.index.init_index() def lowercase ( self : int , _lowerCamelCase : Optional[Any] , _lowerCamelCase : Union[str, Any] ): if len(self.retrieval_workers ) > 0: # Select a random retrieval actor. _snake_case = self.retrieval_workers[random.randint(0 , len(self.retrieval_workers ) - 1 )] _snake_case , _snake_case = ray.get(random_worker.retrieve.remote(_a , _a ) ) else: _snake_case , _snake_case = self._main_retrieve(_a , _a ) return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(_a ) @classmethod def lowercase ( cls : Union[str, Any] , _lowerCamelCase : Any , _lowerCamelCase : Optional[Any]=None , **_lowerCamelCase : Optional[Any] ): return super(_a , cls ).get_tokenizers(_a , _a , **_a ) @classmethod def lowercase ( cls : Union[str, Any] , _lowerCamelCase : List[Any] , _lowerCamelCase : List[str] , _lowerCamelCase : Any=None , **_lowerCamelCase : Optional[Any] ): _snake_case = kwargs.pop('''config''' , _a ) or RagConfig.from_pretrained(_a , **_a ) _snake_case = RagTokenizer.from_pretrained(_a , config=_a ) _snake_case = rag_tokenizer.question_encoder _snake_case = rag_tokenizer.generator if indexed_dataset is not None: _snake_case = '''custom''' _snake_case = CustomHFIndex(config.retrieval_vector_size , _a ) else: _snake_case = cls._build_index(_a ) return cls( _a , question_encoder_tokenizer=_a , generator_tokenizer=_a , retrieval_workers=_a , index=_a , )
288
"""simple docstring""" from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import pyarrow as pa if TYPE_CHECKING: from .features import FeatureType @dataclass class __lowerCAmelCase : '''simple docstring''' __UpperCAmelCase : List[str] __UpperCAmelCase : Optional[str] = None # Automatically constructed __UpperCAmelCase : ClassVar[str] = "dict" __UpperCAmelCase : ClassVar[Any] = None __UpperCAmelCase : str = field(default='Translation' , init=__SCREAMING_SNAKE_CASE , repr=__SCREAMING_SNAKE_CASE ) def __call__( self ): return pa.struct({lang: pa.string() for lang in sorted(self.languages )} ) def __UpperCAmelCase ( self ): from .features import Value return {k: Value('''string''' ) for k in sorted(self.languages )} @dataclass class __lowerCAmelCase : '''simple docstring''' __UpperCAmelCase : Optional[List] = None __UpperCAmelCase : Optional[int] = None __UpperCAmelCase : Optional[str] = None # Automatically constructed __UpperCAmelCase : ClassVar[str] = "dict" __UpperCAmelCase : ClassVar[Any] = None __UpperCAmelCase : str = field(default='TranslationVariableLanguages' , init=__SCREAMING_SNAKE_CASE , repr=__SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self ): __a = sorted(set(self.languages ) ) if self.languages else None __a = len(self.languages ) if self.languages else None def __call__( self ): return pa.struct({'''language''': pa.list_(pa.string() ), '''translation''': pa.list_(pa.string() )} ) def __UpperCAmelCase ( self , _a ): __a = set(self.languages ) if self.languages and set(_a ) - lang_set: raise ValueError( f'''Some languages in example ({', '.join(sorted(set(_a ) - lang_set ) )}) are not in valid set ({', '.join(_a )}).''' ) # Convert dictionary into tuples, splitting out cases where there are # multiple translations for a single language. __a = [] for lang, text in translation_dict.items(): if isinstance(_a , _a ): translation_tuples.append((lang, text) ) else: translation_tuples.extend([(lang, el) for el in text] ) # Ensure translations are in ascending order by language code. __a , __a = zip(*sorted(_a ) ) return {"language": languages, "translation": translations} def __UpperCAmelCase ( self ): from .features import Sequence, Value return { "language": Sequence(Value('''string''' ) ), "translation": Sequence(Value('''string''' ) ), }
45
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available lowerCAmelCase__ = { """configuration_m2m_100""": ["""M2M_100_PRETRAINED_CONFIG_ARCHIVE_MAP""", """M2M100Config""", """M2M100OnnxConfig"""], """tokenization_m2m_100""": ["""M2M100Tokenizer"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ """M2M_100_PRETRAINED_MODEL_ARCHIVE_LIST""", """M2M100ForConditionalGeneration""", """M2M100Model""", """M2M100PreTrainedModel""", ] if TYPE_CHECKING: from .configuration_mam_aaa import M2M_100_PRETRAINED_CONFIG_ARCHIVE_MAP, MaMaaaConfig, MaMaaaOnnxConfig from .tokenization_mam_aaa import MaMaaaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mam_aaa import ( M2M_100_PRETRAINED_MODEL_ARCHIVE_LIST, MaMaaaForConditionalGeneration, MaMaaaModel, MaMaaaPreTrainedModel, ) else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
68
"""simple docstring""" def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list ) -> List[Any]: _enforce_args(lowerCAmelCase__ , lowerCAmelCase__ ) if n == 0: return 0 __a = float('''-inf''' ) for i in range(1 , n + 1 ): __a = max( lowerCAmelCase__ , prices[i - 1] + naive_cut_rod_recursive(n - i , lowerCAmelCase__ ) ) return max_revue def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list ) -> List[str]: _enforce_args(lowerCAmelCase__ , lowerCAmelCase__ ) __a = [float('''-inf''' ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list , lowerCAmelCase__ : list ) -> Union[str, Any]: if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: __a = float('''-inf''' ) for i in range(1 , n + 1 ): __a = max( lowerCAmelCase__ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , lowerCAmelCase__ , lowerCAmelCase__ ) , ) __a = max_revenue return max_rev[n] def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list ) -> Dict: _enforce_args(lowerCAmelCase__ , lowerCAmelCase__ ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. __a = [float('''-inf''' ) for _ in range(n + 1 )] __a = 0 for i in range(1 , n + 1 ): __a = max_rev[i] for j in range(1 , i + 1 ): __a = max(lowerCAmelCase__ , prices[j - 1] + max_rev[i - j] ) __a = max_revenue_i return max_rev[n] def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list ) -> str: if n < 0: __a = f'''n must be greater than or equal to 0. Got n = {n}''' raise ValueError(lowerCAmelCase__ ) if n > len(lowerCAmelCase__ ): __a = ( '''Each integral piece of rod must have a corresponding price. ''' f'''Got n = {n} but length of prices = {len(lowerCAmelCase__ )}''' ) raise ValueError(lowerCAmelCase__ ) def lowercase ( ) -> int: __a = [6, 10, 12, 15, 20, 23] __a = len(lowerCAmelCase__ ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. __a = 36 __a = top_down_cut_rod(lowerCAmelCase__ , lowerCAmelCase__ ) __a = bottom_up_cut_rod(lowerCAmelCase__ , lowerCAmelCase__ ) __a = naive_cut_rod_recursive(lowerCAmelCase__ , lowerCAmelCase__ ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
45
0
import importlib import math import os from dataclasses import dataclass from enum import Enum from typing import Any, Dict, Optional, Tuple, Union import flax import jax.numpy as jnp from ..utils import BaseOutput lowerCAmelCase__ :Optional[int] = '''scheduler_config.json''' class __a ( __SCREAMING_SNAKE_CASE ): _a : str = 1 _a : Dict = 2 _a : int = 3 _a : Tuple = 4 _a : Union[str, Any] = 5 @dataclass class __a ( __SCREAMING_SNAKE_CASE ): _a : jnp.ndarray class __a : _a : int = SCHEDULER_CONFIG_NAME _a : str = ['dtype'] _a : List[str] = [] _a : Any = True @classmethod def UpperCAmelCase__ ( cls , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE=False , **_SCREAMING_SNAKE_CASE , ) -> Dict: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = cls.load_config( pretrained_model_name_or_path=_a , subfolder=_a , return_unused_kwargs=_a , **_a , ) _UpperCAmelCase , _UpperCAmelCase = cls.from_config(_a , return_unused_kwargs=_a , **_a ) if hasattr(_a , 'create_state' ) and getattr(_a , 'has_state' , _a ): _UpperCAmelCase = scheduler.create_state() if return_unused_kwargs: return scheduler, state, unused_kwargs return scheduler, state def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = False , **_SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" self.save_config(save_directory=_a , push_to_hub=_a , **_a ) @property def UpperCAmelCase__ ( self ) -> List[Any]: """simple docstring""" return self._get_compatibles() @classmethod def UpperCAmelCase__ ( cls ) -> List[str]: """simple docstring""" _UpperCAmelCase = list(set([cls.__name__] + cls._compatibles ) ) _UpperCAmelCase = importlib.import_module(__name__.split('.' )[0] ) _UpperCAmelCase = [ getattr(_a , _a ) for c in compatible_classes_str if hasattr(_a , _a ) ] return compatible_classes def lowerCAmelCase__ ( a__: jnp.ndarray , a__: Tuple[int] ) -> jnp.ndarray: '''simple docstring''' assert len(lowerCAmelCase__ ) >= x.ndim return jnp.broadcast_to(x.reshape(x.shape + (1,) * (len(lowerCAmelCase__ ) - x.ndim) ) , lowerCAmelCase__ ) def lowerCAmelCase__ ( a__: int , a__: str=0.999 , a__: List[str]=jnp.floataa ) -> jnp.ndarray: '''simple docstring''' def alpha_bar(a__: str ): return math.cos((time_step + 0.008) / 1.008 * math.pi / 2 ) ** 2 _UpperCAmelCase = [] for i in range(lowerCAmelCase__ ): _UpperCAmelCase = i / num_diffusion_timesteps _UpperCAmelCase = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar(lowerCAmelCase__ ) / alpha_bar(lowerCAmelCase__ ) , lowerCAmelCase__ ) ) return jnp.array(lowerCAmelCase__ , dtype=lowerCAmelCase__ ) @flax.struct.dataclass class __a : _a : jnp.ndarray _a : jnp.ndarray _a : jnp.ndarray @classmethod def UpperCAmelCase__ ( cls , _SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" _UpperCAmelCase = scheduler.config if config.trained_betas is not None: _UpperCAmelCase = jnp.asarray(config.trained_betas , dtype=scheduler.dtype ) elif config.beta_schedule == "linear": _UpperCAmelCase = jnp.linspace(config.beta_start , config.beta_end , config.num_train_timesteps , dtype=scheduler.dtype ) elif config.beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. _UpperCAmelCase = ( jnp.linspace( config.beta_start**0.5 , config.beta_end**0.5 , config.num_train_timesteps , dtype=scheduler.dtype ) ** 2 ) elif config.beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule _UpperCAmelCase = betas_for_alpha_bar(config.num_train_timesteps , dtype=scheduler.dtype ) else: raise NotImplementedError( f'''beta_schedule {config.beta_schedule} is not implemented for scheduler {scheduler.__class__.__name__}''' ) _UpperCAmelCase = 1.0 - betas _UpperCAmelCase = jnp.cumprod(_a , axis=0 ) return cls( alphas=_a , betas=_a , alphas_cumprod=_a , ) def lowerCAmelCase__ ( a__: CommonSchedulerState , a__: jnp.ndarray , a__: jnp.ndarray , a__: jnp.ndarray ) -> Optional[int]: '''simple docstring''' _UpperCAmelCase = state.alphas_cumprod _UpperCAmelCase = alphas_cumprod[timesteps] ** 0.5 _UpperCAmelCase = sqrt_alpha_prod.flatten() _UpperCAmelCase = broadcast_to_shape_from_left(lowerCAmelCase__ , original_samples.shape ) _UpperCAmelCase = (1 - alphas_cumprod[timesteps]) ** 0.5 _UpperCAmelCase = sqrt_one_minus_alpha_prod.flatten() _UpperCAmelCase = broadcast_to_shape_from_left(lowerCAmelCase__ , original_samples.shape ) return sqrt_alpha_prod, sqrt_one_minus_alpha_prod def lowerCAmelCase__ ( a__: CommonSchedulerState , a__: jnp.ndarray , a__: jnp.ndarray , a__: jnp.ndarray ) -> Dict: '''simple docstring''' _UpperCAmelCase , _UpperCAmelCase = get_sqrt_alpha_prod(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) _UpperCAmelCase = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise return noisy_samples def lowerCAmelCase__ ( a__: CommonSchedulerState , a__: jnp.ndarray , a__: jnp.ndarray , a__: jnp.ndarray ) -> List[Any]: '''simple docstring''' _UpperCAmelCase , _UpperCAmelCase = get_sqrt_alpha_prod(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) _UpperCAmelCase = sqrt_alpha_prod * noise - sqrt_one_minus_alpha_prod * sample return velocity
329
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) lowercase_ = {"configuration_unispeech": ["UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP", "UniSpeechConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST", "UniSpeechForCTC", "UniSpeechForPreTraining", "UniSpeechForSequenceClassification", "UniSpeechModel", "UniSpeechPreTrainedModel", ] if TYPE_CHECKING: from .configuration_unispeech import UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_unispeech import ( UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST, UniSpeechForCTC, UniSpeechForPreTraining, UniSpeechForSequenceClassification, UniSpeechModel, UniSpeechPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
45
0
'''simple docstring''' from collections.abc import Sequence def __UpperCAmelCase ( a_: Sequence[int] | None = None ): if nums is None or not nums: raise ValueError("Input sequence should not be empty" ) _UpperCAmelCase : List[str] = nums[0] for i in range(1, len(lowerCAmelCase__ ) ): _UpperCAmelCase : Tuple = nums[i] _UpperCAmelCase : List[str] = max(lowerCAmelCase__, ans + num, lowerCAmelCase__ ) return ans if __name__ == "__main__": import doctest doctest.testmod() # Try on a sample input from the user __a = int(input('Enter number of elements : ').strip()) __a = list(map(int, input('\nEnter the numbers : ').strip().split()))[:n] print(max_subsequence_sum(array))
145
"""simple docstring""" import unittest import torch from torch import nn from diffusers.models.activations import get_activation class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = get_activation('''swish''' ) self.assertIsInstance(_a , nn.SiLU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def __UpperCAmelCase ( self ): __a = get_activation('''silu''' ) self.assertIsInstance(_a , nn.SiLU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def __UpperCAmelCase ( self ): __a = get_activation('''mish''' ) self.assertIsInstance(_a , nn.Mish ) self.assertEqual(act(torch.tensor(-200 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def __UpperCAmelCase ( self ): __a = get_activation('''gelu''' ) self.assertIsInstance(_a , nn.GELU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 )
45
0
import unittest import numpy as np import torch from torch import nn from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import KandinskyVaaPriorPipeline, PriorTransformer, UnCLIPScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import enable_full_determinism, skip_mps from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class _a ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): """simple docstring""" _lowerCamelCase : List[str] = KandinskyVaaPriorPipeline _lowerCamelCase : Optional[int] = ['prompt'] _lowerCamelCase : int = ['prompt', 'negative_prompt'] _lowerCamelCase : Optional[Any] = [ 'num_images_per_prompt', 'generator', 'num_inference_steps', 'latents', 'negative_prompt', 'guidance_scale', 'output_type', 'return_dict', ] _lowerCamelCase : Any = False @property def __A ( self : Optional[Any] ): return 32 @property def __A ( self : Optional[Any] ): return 32 @property def __A ( self : Tuple ): return self.time_input_dim @property def __A ( self : List[str] ): return self.time_input_dim * 4 @property def __A ( self : Optional[int] ): return 100 @property def __A ( self : str ): A_ = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) return tokenizer @property def __A ( self : Any ): torch.manual_seed(0 ) A_ = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(_a ) @property def __A ( self : int ): torch.manual_seed(0 ) A_ = { "num_attention_heads": 2, "attention_head_dim": 12, "embedding_dim": self.text_embedder_hidden_size, "num_layers": 1, } A_ = PriorTransformer(**_a ) # clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0 A_ = nn.Parameter(torch.ones(model.clip_std.shape ) ) return model @property def __A ( self : List[str] ): torch.manual_seed(0 ) A_ = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=224 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=14 , ) A_ = CLIPVisionModelWithProjection(_a ) return model @property def __A ( self : Tuple ): A_ = CLIPImageProcessor( crop_size=224 , do_center_crop=_a , do_normalize=_a , do_resize=_a , image_mean=[0.48_145_466, 0.4_578_275, 0.40_821_073] , image_std=[0.26_862_954, 0.26_130_258, 0.27_577_711] , resample=3 , size=224 , ) return image_processor def __A ( self : Optional[int] ): A_ = self.dummy_prior A_ = self.dummy_image_encoder A_ = self.dummy_text_encoder A_ = self.dummy_tokenizer A_ = self.dummy_image_processor A_ = UnCLIPScheduler( variance_type="fixed_small_log" , prediction_type="sample" , num_train_timesteps=1000 , clip_sample=_a , clip_sample_range=10.0 , ) A_ = { "prior": prior, "image_encoder": image_encoder, "text_encoder": text_encoder, "tokenizer": tokenizer, "scheduler": scheduler, "image_processor": image_processor, } return components def __A ( self : Optional[Any] , UpperCAmelCase : int , UpperCAmelCase : Union[str, Any]=0 ): if str(_a ).startswith("mps" ): A_ = torch.manual_seed(_a ) else: A_ = torch.Generator(device=_a ).manual_seed(_a ) A_ = { "prompt": "horse", "generator": generator, "guidance_scale": 4.0, "num_inference_steps": 2, "output_type": "np", } return inputs def __A ( self : Any ): A_ = "cpu" A_ = self.get_dummy_components() A_ = self.pipeline_class(**_a ) A_ = pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) A_ = pipe(**self.get_dummy_inputs(_a ) ) A_ = output.image_embeds A_ = pipe( **self.get_dummy_inputs(_a ) , return_dict=_a , )[0] A_ = image[0, -10:] A_ = image_from_tuple[0, -10:] assert image.shape == (1, 32) A_ = np.array( [-0.0_532, 1.7_120, 0.3_656, -1.0_852, -0.8_946, -1.1_756, 0.4_348, 0.2_482, 0.5_146, -0.1_156] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 @skip_mps def __A ( self : Union[str, Any] ): A_ = torch_device == "cpu" A_ = True A_ = False self._test_inference_batch_single_identical( test_max_difference=_a , relax_max_difference=_a , test_mean_pixel_difference=_a , ) @skip_mps def __A ( self : Optional[Any] ): A_ = torch_device == "cpu" A_ = False self._test_attention_slicing_forward_pass( test_max_difference=_a , test_mean_pixel_difference=_a , )
312
"""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 : '''simple docstring''' def __init__( self , _a , ): __a = parent __a = 13 __a = 7 __a = True __a = True __a = True __a = 99 __a = 32 __a = 2 __a = 4 __a = 37 __a = '''gelu''' __a = 0.1 __a = 0.1 __a = 512 __a = 16 __a = 2 __a = 0.02 __a = 3 __a = 4 __a = None def __UpperCAmelCase ( self ): __a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a = None if self.use_input_mask: __a = random_attention_mask([self.batch_size, self.seq_length] ) __a = None __a = None __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __a = ids_tensor([self.batch_size] , self.num_choices ) __a = 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 __UpperCAmelCase ( self ): ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = self.prepare_config_and_inputs() __a = True __a = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __a = 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 __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a ): __a = TFEsmModel(config=_a ) __a = {'''input_ids''': input_ids, '''attention_mask''': input_mask} __a = model(_a ) __a = [input_ids, input_mask] __a = model(_a ) __a = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a , _a , ): __a = True __a = TFEsmModel(config=_a ) __a = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''encoder_hidden_states''': encoder_hidden_states, '''encoder_attention_mask''': encoder_attention_mask, } __a = model(_a ) __a = [input_ids, input_mask] __a = model(_a , encoder_hidden_states=_a ) # Also check the case where encoder outputs are not passed __a = model(_a , attention_mask=_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a ): __a = TFEsmForMaskedLM(config=_a ) __a = model([input_ids, input_mask] ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , _a ): __a = self.num_labels __a = TFEsmForTokenClassification(config=_a ) __a = {'''input_ids''': input_ids, '''attention_mask''': input_mask} __a = model(_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCAmelCase ( self ): __a = self.prepare_config_and_inputs() ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = config_and_inputs __a = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_tf class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : int = ( ( TFEsmModel, TFEsmForMaskedLM, TFEsmForSequenceClassification, TFEsmForTokenClassification, ) if is_tf_available() else () ) __UpperCAmelCase : Tuple = ( { 'feature-extraction': TFEsmModel, 'fill-mask': TFEsmForMaskedLM, 'text-classification': TFEsmForSequenceClassification, 'token-classification': TFEsmForTokenClassification, 'zero-shot': TFEsmForSequenceClassification, } if is_tf_available() else {} ) __UpperCAmelCase : Tuple = False __UpperCAmelCase : Union[str, Any] = False def __UpperCAmelCase ( self ): __a = TFEsmModelTester(self ) __a = ConfigTester(self , config_class=_a , hidden_size=37 ) def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_a ) @slow def __UpperCAmelCase ( self ): for model_name in TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = TFEsmModel.from_pretrained(_a ) self.assertIsNotNone(_a ) @unittest.skip('''Protein models do not support embedding resizing.''' ) def __UpperCAmelCase ( self ): pass @unittest.skip('''Protein models do not support embedding resizing.''' ) 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(_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 __a = model.get_bias() assert isinstance(_a , _a ) for k, v in name.items(): assert isinstance(_a , tf.Variable ) else: __a = model.get_output_embeddings() assert x is None __a = model.get_bias() assert name is None @require_tf class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @slow def __UpperCAmelCase ( self ): __a = TFEsmForMaskedLM.from_pretrained('''facebook/esm2_t6_8M_UR50D''' ) __a = tf.constant([[0, 1, 2, 3, 4, 5]] ) __a = model(_a )[0] __a = [1, 6, 33] self.assertEqual(list(output.numpy().shape ) , _a ) # compare the actual values for a slice. __a = tf.constant( [ [ [8.92_1518, -10.58_9814, -6.467_1307], [-6.396_7156, -13.91_1377, -1.121_1915], [-7.78_1247, -13.95_1557, -3.74_0592], ] ] ) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-2 ) ) @slow def __UpperCAmelCase ( self ): __a = TFEsmModel.from_pretrained('''facebook/esm2_t6_8M_UR50D''' ) __a = tf.constant([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] ) __a = model(_a )[0] # compare the actual values for a slice. __a = tf.constant( [ [ [0.1444_3092, 0.5412_5327, 0.324_7739], [0.3034_0484, 0.0052_6676, 0.3107_7722], [0.3227_8043, -0.2498_7096, 0.341_4628], ] ] ) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4 ) )
45
0
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 : Tuple = re.compile("[^A-Za-z_0-9]") # parameters used in DuplicationIndex lowerCamelCase : Dict = 10 lowerCamelCase : int = 256 def _SCREAMING_SNAKE_CASE ( lowercase : List[str] ): '''simple docstring''' if len(lowerCAmelCase__ ) < MIN_NUM_TOKENS: return None lowerCamelCase_ = MinHash(num_perm=lowerCAmelCase__ ) for token in set(lowerCAmelCase__ ): min_hash.update(token.encode() ) return min_hash def _SCREAMING_SNAKE_CASE ( lowercase : str ): '''simple docstring''' return {t for t in NON_ALPHA.split(lowerCAmelCase__ ) if len(t.strip() ) > 0} class A: '''simple docstring''' def __init__( self : int , *, A_ : Union[str, Any] = 0.85 , ) -> Optional[Any]: """simple docstring""" lowerCamelCase_ = duplication_jaccard_threshold lowerCamelCase_ = NUM_PERM lowerCamelCase_ = MinHashLSH(threshold=self._duplication_jaccard_threshold , num_perm=self._num_perm ) lowerCamelCase_ = defaultdict(_a ) def a__ ( self : Union[str, Any] , A_ : Optional[int] , A_ : int ) -> Any: """simple docstring""" lowerCamelCase_ = 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 a__ ( self : List[str] ) -> Dict: """simple docstring""" lowerCamelCase_ = [] for base, duplicates in self._duplicate_clusters.items(): lowerCamelCase_ = [base] + list(_a ) # reformat the cluster to be a list of dict lowerCamelCase_ = [{'base_index': el[0], 'repo_name': el[1], 'path': el[2]} for el in cluster] duplicate_clusters.append(_a ) return duplicate_clusters def a__ ( self : Tuple , A_ : Dict ) -> Union[str, Any]: """simple docstring""" lowerCamelCase_ = self.get_duplicate_clusters() with open(_a , 'w' ) as f: json.dump(_a , _a ) def _SCREAMING_SNAKE_CASE ( lowercase : List[str] ): '''simple docstring''' lowerCamelCase_ , lowerCamelCase_ = element lowerCamelCase_ = 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 _SCREAMING_SNAKE_CASE ( lowercase : Type[Dataset] ): '''simple docstring''' with mp.Pool() as pool: for data in pool.imap_unordered( _compute_min_hash , ThreadedIterator(lowerCAmelCase__ , max_queue_size=1_00_00 ) , chunksize=1_00 , ): if data is not None: yield data def _SCREAMING_SNAKE_CASE ( lowercase : Type[Dataset] , lowercase : float ): '''simple docstring''' lowerCamelCase_ = DuplicationIndex(duplication_jaccard_threshold=lowerCAmelCase__ ) for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(lowerCAmelCase__ ) ) , max_queue_size=1_00 ) ): di.add(lowerCAmelCase__ , lowerCAmelCase__ ) # Returns a List[Cluster] where Cluster is List[str] with the filenames. return di.get_duplicate_clusters() def _SCREAMING_SNAKE_CASE ( lowercase : str , lowercase : str ): '''simple docstring''' lowerCamelCase_ = get_tokens(lowerCAmelCase__ ) lowerCamelCase_ = get_tokens(lowerCAmelCase__ ) return len(tokensa & tokensa ) / len(tokensa | tokensa ) lowerCamelCase : Optional[Any] = None def _SCREAMING_SNAKE_CASE ( lowercase : Optional[Any] , lowercase : Union[str, Any] ): '''simple docstring''' lowerCamelCase_ = [] for elementa in cluster: lowerCamelCase_ = _shared_dataset[elementa['base_index']]['content'] for elementa in extremes: lowerCamelCase_ = _shared_dataset[elementa['base_index']]['content'] if jaccard_similarity(lowerCAmelCase__ , lowerCAmelCase__ ) >= jaccard_threshold: elementa["copies"] += 1 break else: lowerCamelCase_ = 1 extremes.append(lowerCAmelCase__ ) return extremes def _SCREAMING_SNAKE_CASE ( lowercase : Union[str, Any] , lowercase : Optional[Any] , lowercase : Optional[int] ): '''simple docstring''' global _shared_dataset lowerCamelCase_ = dataset lowerCamelCase_ = [] lowerCamelCase_ = 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 _SCREAMING_SNAKE_CASE ( lowercase : Type[Dataset] , lowercase : float = 0.85 ): '''simple docstring''' lowerCamelCase_ = make_duplicate_clusters(lowerCAmelCase__ , lowerCAmelCase__ ) lowerCamelCase_ = {x['base_index'] for cluster in duplicate_clusters for x in cluster} lowerCamelCase_ = {} lowerCamelCase_ = find_extremes(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) for extremes in extremes_clusters: for element in extremes: lowerCamelCase_ = element lowerCamelCase_ = duplicate_indices - set(extreme_dict.keys() ) lowerCamelCase_ = dataset.filter(lambda lowercase , lowercase : idx not in remove_indices , with_indices=lowerCAmelCase__ ) # update duplicate_clusters for cluster in duplicate_clusters: for element in cluster: lowerCamelCase_ = element['base_index'] in extreme_dict if element["is_extreme"]: lowerCamelCase_ = 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
204
"""simple docstring""" def lowercase ( lowerCAmelCase__ : int ) -> str: if number > 0: raise ValueError('''input must be a negative integer''' ) __a = len(bin(lowerCAmelCase__ )[3:] ) __a = bin(abs(lowerCAmelCase__ ) - (1 << binary_number_length) )[3:] __a = ( ( '''1''' + '''0''' * (binary_number_length - len(lowerCAmelCase__ )) + twos_complement_number ) if number < 0 else '''0''' ) return "0b" + twos_complement_number if __name__ == "__main__": import doctest doctest.testmod()
45
0
import inspect import unittest from transformers import MobileNetVaConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation, MobileNetVaModel from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileNetVaImageProcessor class __magic_name__ ( __SCREAMING_SNAKE_CASE ): """simple docstring""" def SCREAMING_SNAKE_CASE ( self :str ): '''simple docstring''' A_ : Union[str, Any] = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(_a , "tf_padding" ) ) self.parent.assertTrue(hasattr(_a , "depth_multiplier" ) ) class __magic_name__ : """simple docstring""" def __init__( self :Any , snake_case :int , snake_case :Optional[int]=13 , snake_case :Union[str, Any]=3 , snake_case :Tuple=32 , snake_case :str=0.25 , snake_case :Optional[int]=8 , snake_case :Dict=8 , snake_case :Tuple=6 , snake_case :Union[str, Any]=32 , snake_case :List[Any]=True , snake_case :Optional[Any]=True , snake_case :Any=True , snake_case :List[str]="relu6" , snake_case :Dict=1_280 , snake_case :Tuple=0.1 , snake_case :List[Any]=0.02 , snake_case :List[str]=True , snake_case :Union[str, Any]=True , snake_case :Tuple=10 , snake_case :str=None , ): '''simple docstring''' A_ : Union[str, Any] = parent A_ : Tuple = batch_size A_ : str = num_channels A_ : Union[str, Any] = image_size A_ : Optional[int] = depth_multiplier A_ : int = depth_divisible_by A_ : str = min_depth A_ : Union[str, Any] = expand_ratio A_ : Any = tf_padding A_ : Optional[Any] = output_stride A_ : Union[str, Any] = first_layer_is_expansion A_ : Dict = finegrained_output A_ : Dict = hidden_act A_ : List[str] = last_hidden_size if finegrained_output else int(last_hidden_size * depth_multiplier ) A_ : List[Any] = classifier_dropout_prob A_ : List[Any] = use_labels A_ : List[str] = is_training A_ : int = num_labels A_ : List[str] = initializer_range A_ : Tuple = scope def SCREAMING_SNAKE_CASE ( self :str ): '''simple docstring''' A_ : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) A_ : Optional[Any] = None A_ : Dict = None if self.use_labels: A_ : Union[str, Any] = ids_tensor([self.batch_size] , self.num_labels ) A_ : Any = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) A_ : int = self.get_config() return config, pixel_values, labels, pixel_labels def SCREAMING_SNAKE_CASE ( self :Dict ): '''simple docstring''' return MobileNetVaConfig( num_channels=self.num_channels , image_size=self.image_size , depth_multiplier=self.depth_multiplier , depth_divisible_by=self.depth_divisible_by , min_depth=self.min_depth , expand_ratio=self.expand_ratio , output_stride=self.output_stride , first_layer_is_expansion=self.first_layer_is_expansion , finegrained_output=self.finegrained_output , hidden_act=self.hidden_act , tf_padding=self.tf_padding , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , ) def SCREAMING_SNAKE_CASE ( self :Union[str, Any] , snake_case :Optional[int] , snake_case :str , snake_case :Dict , snake_case :Dict ): '''simple docstring''' A_ : List[Any] = MobileNetVaModel(config=_a ) model.to(_a ) model.eval() A_ : Optional[int] = model(_a ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) self.parent.assertEqual( result.pooler_output.shape , (self.batch_size, self.last_hidden_size) , ) def SCREAMING_SNAKE_CASE ( self :str , snake_case :Optional[Any] , snake_case :Any , snake_case :str , snake_case :Optional[Any] ): '''simple docstring''' A_ : Union[str, Any] = self.num_labels A_ : Union[str, Any] = MobileNetVaForImageClassification(_a ) model.to(_a ) model.eval() A_ : str = model(_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE ( self :Any , snake_case :Tuple , snake_case :str , snake_case :Union[str, Any] , snake_case :Optional[Any] ): '''simple docstring''' A_ : Optional[Any] = self.num_labels A_ : List[Any] = MobileNetVaForSemanticSegmentation(_a ) model.to(_a ) model.eval() A_ : List[str] = model(_a ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) A_ : Any = model(_a , labels=_a ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def SCREAMING_SNAKE_CASE ( self :str ): '''simple docstring''' A_ : List[str] = self.prepare_config_and_inputs() A_ , A_ , A_ , A_ : int = config_and_inputs A_ : Union[str, Any] = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class __magic_name__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): """simple docstring""" __UpperCamelCase = ( (MobileNetVaModel, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation) if is_torch_available() else () ) __UpperCamelCase = ( { 'feature-extraction': MobileNetVaModel, 'image-classification': MobileNetVaForImageClassification, 'image-segmentation': MobileNetVaForSemanticSegmentation, } if is_torch_available() else {} ) __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False def SCREAMING_SNAKE_CASE ( self :List[str] ): '''simple docstring''' A_ : Optional[Any] = MobileNetVaModelTester(self ) A_ : Optional[int] = MobileNetVaConfigTester(self , config_class=_a , has_text_modality=_a ) def SCREAMING_SNAKE_CASE ( self :Tuple ): '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason="MobileNetV2 does not use inputs_embeds" ) def SCREAMING_SNAKE_CASE ( self :Optional[int] ): '''simple docstring''' pass @unittest.skip(reason="MobileNetV2 does not support input and output embeddings" ) def SCREAMING_SNAKE_CASE ( self :Dict ): '''simple docstring''' pass @unittest.skip(reason="MobileNetV2 does not output attentions" ) def SCREAMING_SNAKE_CASE ( self :Optional[Any] ): '''simple docstring''' pass def SCREAMING_SNAKE_CASE ( self :Any ): '''simple docstring''' A_ , A_ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A_ : List[str] = model_class(_a ) A_ : str = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic A_ : List[str] = [*signature.parameters.keys()] A_ : str = ["pixel_values"] self.assertListEqual(arg_names[:1] , _a ) def SCREAMING_SNAKE_CASE ( self :Tuple ): '''simple docstring''' A_ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def SCREAMING_SNAKE_CASE ( self :Dict ): '''simple docstring''' def check_hidden_states_output(snake_case :Optional[int] , snake_case :Dict , snake_case :Tuple ): A_ : Union[str, Any] = model_class(_a ) model.to(_a ) model.eval() with torch.no_grad(): A_ : Tuple = model(**self._prepare_for_class(_a , _a ) ) A_ : Optional[Any] = outputs.hidden_states A_ : Optional[Any] = 16 self.assertEqual(len(_a ) , _a ) A_ , A_ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A_ : List[str] = True check_hidden_states_output(_a , _a , _a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] A_ : List[Any] = True check_hidden_states_output(_a , _a , _a ) def SCREAMING_SNAKE_CASE ( self :Tuple ): '''simple docstring''' A_ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_a ) def SCREAMING_SNAKE_CASE ( self :List[str] ): '''simple docstring''' A_ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*_a ) @slow def SCREAMING_SNAKE_CASE ( self :Optional[Any] ): '''simple docstring''' for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A_ : List[str] = MobileNetVaModel.from_pretrained(_a ) self.assertIsNotNone(_a ) def __snake_case ( ) -> Dict: A_ : int = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class __magic_name__ ( unittest.TestCase ): """simple docstring""" @cached_property def SCREAMING_SNAKE_CASE ( self :Union[str, Any] ): '''simple docstring''' return ( MobileNetVaImageProcessor.from_pretrained("google/mobilenet_v2_1.0_224" ) if is_vision_available() else None ) @slow def SCREAMING_SNAKE_CASE ( self :Union[str, Any] ): '''simple docstring''' A_ : Any = MobileNetVaForImageClassification.from_pretrained("google/mobilenet_v2_1.0_224" ).to(_a ) A_ : int = self.default_image_processor A_ : List[str] = prepare_img() A_ : Tuple = image_processor(images=_a , return_tensors="pt" ).to(_a ) # forward pass with torch.no_grad(): A_ : Optional[int] = model(**_a ) # verify the logits A_ : Optional[int] = torch.Size((1, 1_001) ) self.assertEqual(outputs.logits.shape , _a ) A_ : Union[str, Any] = torch.tensor([0.2445, -1.1993, 0.1905] ).to(_a ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _a , atol=1e-4 ) ) @slow def SCREAMING_SNAKE_CASE ( self :Tuple ): '''simple docstring''' A_ : int = MobileNetVaForSemanticSegmentation.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513" ) A_ : Tuple = model.to(_a ) A_ : Tuple = MobileNetVaImageProcessor.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513" ) A_ : int = prepare_img() A_ : str = image_processor(images=_a , return_tensors="pt" ).to(_a ) # forward pass with torch.no_grad(): A_ : Any = model(**_a ) A_ : Optional[Any] = outputs.logits # verify the logits A_ : Optional[Any] = torch.Size((1, 21, 65, 65) ) self.assertEqual(logits.shape , _a ) A_ : Any = torch.tensor( [ [[17.5790, 17.7581, 18.3355], [18.3257, 18.4230, 18.8973], [18.6169, 18.8650, 19.2187]], [[-2.1595, -2.0977, -2.3741], [-2.4226, -2.3028, -2.6835], [-2.7819, -2.5991, -2.7706]], [[4.2058, 4.8317, 4.7638], [4.4136, 5.0361, 4.9383], [4.5028, 4.9644, 4.8734]], ] , device=_a , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , _a , atol=1e-4 ) )
300
"""simple docstring""" def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : list[str] ) -> str: __a = '''''' for word_or_phrase in separated: if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise Exception('''join() accepts only strings to be joined''' ) joined += word_or_phrase + separator return joined.strip(lowerCAmelCase__ ) if __name__ == "__main__": from doctest import testmod testmod()
45
0
'''simple docstring''' import argparse import torch from transformers import ( UniSpeechSatConfig, UniSpeechSatForAudioFrameClassification, UniSpeechSatForSequenceClassification, UniSpeechSatForXVector, WavaVecaFeatureExtractor, logging, ) logging.set_verbosity_info() _UpperCAmelCase : Optional[int] = logging.get_logger(__name__) def __magic_name__( lowerCamelCase, lowerCamelCase, lowerCamelCase): __lowerCAmelCase = UniSpeechSatForSequenceClassification.from_pretrained(lowerCAmelCase__, config=lowerCAmelCase__) __lowerCAmelCase = downstream_dict['''projector.weight'''] __lowerCAmelCase = downstream_dict['''projector.bias'''] __lowerCAmelCase = downstream_dict['''model.post_net.linear.weight'''] __lowerCAmelCase = downstream_dict['''model.post_net.linear.bias'''] return model def __magic_name__( lowerCamelCase, lowerCamelCase, lowerCamelCase): __lowerCAmelCase = UniSpeechSatForAudioFrameClassification.from_pretrained(lowerCAmelCase__, config=lowerCAmelCase__) __lowerCAmelCase = downstream_dict['''model.linear.weight'''] __lowerCAmelCase = downstream_dict['''model.linear.bias'''] return model def __magic_name__( lowerCamelCase, lowerCamelCase, lowerCamelCase): __lowerCAmelCase = UniSpeechSatForXVector.from_pretrained(lowerCAmelCase__, config=lowerCAmelCase__) __lowerCAmelCase = downstream_dict['''connector.weight'''] __lowerCAmelCase = downstream_dict['''connector.bias'''] for i, kernel_size in enumerate(hf_config.tdnn_kernel): __lowerCAmelCase = downstream_dict[ F"""model.framelevel_feature_extractor.module.{i}.kernel.weight""" ] __lowerCAmelCase = downstream_dict[F"""model.framelevel_feature_extractor.module.{i}.kernel.bias"""] __lowerCAmelCase = downstream_dict['''model.utterancelevel_feature_extractor.linear1.weight'''] __lowerCAmelCase = downstream_dict['''model.utterancelevel_feature_extractor.linear1.bias'''] __lowerCAmelCase = downstream_dict['''model.utterancelevel_feature_extractor.linear2.weight'''] __lowerCAmelCase = downstream_dict['''model.utterancelevel_feature_extractor.linear2.bias'''] __lowerCAmelCase = downstream_dict['''objective.W'''] return model @torch.no_grad() def __magic_name__( lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase): __lowerCAmelCase = torch.load(lowerCAmelCase__, map_location='''cpu''') __lowerCAmelCase = checkpoint['''Downstream'''] __lowerCAmelCase = UniSpeechSatConfig.from_pretrained(lowerCAmelCase__) __lowerCAmelCase = WavaVecaFeatureExtractor.from_pretrained( lowerCAmelCase__, return_attention_mask=lowerCAmelCase__, do_normalize=lowerCAmelCase__) __lowerCAmelCase = hf_config.architectures[0] if arch.endswith('''ForSequenceClassification'''): __lowerCAmelCase = convert_classification(lowerCAmelCase__, lowerCAmelCase__, lowerCAmelCase__) elif arch.endswith('''ForAudioFrameClassification'''): __lowerCAmelCase = convert_diarization(lowerCAmelCase__, lowerCAmelCase__, lowerCAmelCase__) elif arch.endswith('''ForXVector'''): __lowerCAmelCase = convert_xvector(lowerCAmelCase__, lowerCAmelCase__, lowerCAmelCase__) else: raise NotImplementedError(F"""S3PRL weights conversion is not supported for {arch}""") if hf_config.use_weighted_layer_sum: __lowerCAmelCase = checkpoint['''Featurizer''']['''weights'''] hf_feature_extractor.save_pretrained(lowerCAmelCase__) hf_model.save_pretrained(lowerCAmelCase__) if __name__ == "__main__": _UpperCAmelCase : Dict = argparse.ArgumentParser() parser.add_argument( """--base_model_name""", default=None, type=str, help="""Name of the huggingface pretrained base model.""" ) parser.add_argument("""--config_path""", default=None, type=str, help="""Path to the huggingface classifier config.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to the s3prl checkpoint.""") parser.add_argument("""--model_dump_path""", default=None, type=str, help="""Path to the final converted model.""") _UpperCAmelCase : Any = parser.parse_args() convert_saprl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path)
174
"""simple docstring""" lowercase_ = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" def lowercase ( lowerCAmelCase__ : bytes ) -> bytes: # Make sure the supplied data is a bytes-like object if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): __a = f'''a bytes-like object is required, not \'{data.__class__.__name__}\'''' raise TypeError(lowerCAmelCase__ ) __a = ''''''.join(bin(lowerCAmelCase__ )[2:].zfill(8 ) for byte in data ) __a = len(lowerCAmelCase__ ) % 6 != 0 if padding_needed: # The padding that will be added later __a = b'''=''' * ((6 - len(lowerCAmelCase__ ) % 6) // 2) # Append binary_stream with arbitrary binary digits (0's by default) to make its # length a multiple of 6. binary_stream += "0" * (6 - len(lowerCAmelCase__ ) % 6) else: __a = b'''''' # Encode every 6 binary digits to their corresponding Base64 character return ( "".join( B64_CHARSET[int(binary_stream[index : index + 6] , 2 )] for index in range(0 , len(lowerCAmelCase__ ) , 6 ) ).encode() + padding ) def lowercase ( lowerCAmelCase__ : str ) -> bytes: # Make sure encoded_data is either a string or a bytes-like object if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): __a = ( '''argument should be a bytes-like object or ASCII string, ''' f'''not \'{encoded_data.__class__.__name__}\'''' ) raise TypeError(lowerCAmelCase__ ) # In case encoded_data is a bytes-like object, make sure it contains only # ASCII characters so we convert it to a string object if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): try: __a = encoded_data.decode('''utf-8''' ) except UnicodeDecodeError: raise ValueError('''base64 encoded data should only contain ASCII characters''' ) __a = encoded_data.count('''=''' ) # Check if the encoded string contains non base64 characters if padding: assert all( char in B64_CHARSET for char in encoded_data[:-padding] ), "Invalid base64 character(s) found." else: assert all( char in B64_CHARSET for char in encoded_data ), "Invalid base64 character(s) found." # Check the padding assert len(lowerCAmelCase__ ) % 4 == 0 and padding < 3, "Incorrect padding" if padding: # Remove padding if there is one __a = encoded_data[:-padding] __a = ''''''.join( bin(B64_CHARSET.index(lowerCAmelCase__ ) )[2:].zfill(6 ) for char in encoded_data )[: -padding * 2] else: __a = ''''''.join( bin(B64_CHARSET.index(lowerCAmelCase__ ) )[2:].zfill(6 ) for char in encoded_data ) __a = [ int(binary_stream[index : index + 8] , 2 ) for index in range(0 , len(lowerCAmelCase__ ) , 8 ) ] return bytes(lowerCAmelCase__ ) if __name__ == "__main__": import doctest doctest.testmod()
45
0
def a__ ( snake_case ): """simple docstring""" return number & 1 == 0 if __name__ == "__main__": import doctest doctest.testmod()
303
"""simple docstring""" 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 __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = inspect.getfile(accelerate.test_utils ) __a = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_script.py'''] ) __a = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_distributed_data_loop.py'''] ) __a = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_ops.py'''] ) @require_multi_gpu def __UpperCAmelCase ( self ): print(f'''Found {torch.cuda.device_count()} devices.''' ) __a = ['''torchrun''', f'''--nproc_per_node={torch.cuda.device_count()}''', self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(_a , env=os.environ.copy() ) @require_multi_gpu def __UpperCAmelCase ( self ): print(f'''Found {torch.cuda.device_count()} devices.''' ) __a = ['''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(_a , env=os.environ.copy() ) @require_multi_gpu def __UpperCAmelCase ( self ): __a = ['''torchrun''', f'''--nproc_per_node={torch.cuda.device_count()}''', inspect.getfile(self.__class__ )] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(_a , env=os.environ.copy() ) @require_multi_gpu def __UpperCAmelCase ( self ): print(f'''Found {torch.cuda.device_count()} devices, using 2 devices only''' ) __a = ['''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(_a , env=os.environ.copy() ) if __name__ == "__main__": lowercase_ = Accelerator() lowercase_ = (accelerator.state.process_index + 2, 1_0) lowercase_ = torch.randint(0, 1_0, shape).to(accelerator.device) lowercase_ = "" lowercase_ = 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)." lowercase_ = 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." lowercase_ = 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)
45
0
"""simple docstring""" from collections import OrderedDict from typing import TYPE_CHECKING, Any, List, Mapping, Optional from packaging import version if TYPE_CHECKING: from ... import PreTrainedTokenizer, TensorType from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import is_torch_available, logging UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = { """bigscience/bloom""": """https://huggingface.co/bigscience/bloom/resolve/main/config.json""", """bigscience/bloom-560m""": """https://huggingface.co/bigscience/bloom-560m/blob/main/config.json""", """bigscience/bloom-1b1""": """https://huggingface.co/bigscience/bloom-1b1/blob/main/config.json""", """bigscience/bloom-1b7""": """https://huggingface.co/bigscience/bloom-1b7/blob/main/config.json""", """bigscience/bloom-3b""": """https://huggingface.co/bigscience/bloom-3b/blob/main/config.json""", """bigscience/bloom-7b1""": """https://huggingface.co/bigscience/bloom-7b1/blob/main/config.json""", } class UpperCAmelCase_ ( __SCREAMING_SNAKE_CASE): snake_case__ = 'bloom' snake_case__ = ['past_key_values'] snake_case__ = { 'num_hidden_layers': 'n_layer', 'num_attention_heads': 'n_head', } def __init__( self : Tuple , __UpperCamelCase : Dict=25_0880 , __UpperCamelCase : List[Any]=64 , __UpperCamelCase : List[str]=2 , __UpperCamelCase : Union[str, Any]=8 , __UpperCamelCase : List[str]=1E-5 , __UpperCamelCase : List[str]=0.0_2 , __UpperCamelCase : Optional[Any]=True , __UpperCamelCase : Tuple=1 , __UpperCamelCase : Optional[int]=2 , __UpperCamelCase : List[Any]=False , __UpperCamelCase : List[Any]=0.0 , __UpperCamelCase : Optional[int]=0.0 , __UpperCamelCase : Tuple=1 , __UpperCamelCase : Union[str, Any]=False , **__UpperCamelCase : Optional[Any] , ) -> List[str]: _UpperCamelCase = vocab_size # Backward compatibility with n_embed kwarg _UpperCamelCase = kwargs.pop('''n_embed''' , _a ) _UpperCamelCase = hidden_size if n_embed is None else n_embed _UpperCamelCase = n_layer _UpperCamelCase = n_head _UpperCamelCase = layer_norm_epsilon _UpperCamelCase = initializer_range _UpperCamelCase = use_cache _UpperCamelCase = pretraining_tp _UpperCamelCase = apply_residual_connection_post_layernorm _UpperCamelCase = hidden_dropout _UpperCamelCase = attention_dropout _UpperCamelCase = bos_token_id _UpperCamelCase = eos_token_id _UpperCamelCase = slow_but_exact super().__init__(bos_token_id=_a , eos_token_id=_a , **_a ) class UpperCAmelCase_ ( __SCREAMING_SNAKE_CASE): snake_case__ = version.parse('''1.12''') def __init__( self : Dict , __UpperCamelCase : Dict , __UpperCamelCase : Optional[Any] = "default" , __UpperCamelCase : Optional[int] = None , __UpperCamelCase : Tuple = False , ) -> Union[str, Any]: super().__init__(_a , task=_a , patching_specs=_a , use_past=_a ) if not getattr(self._config , '''pad_token_id''' , _a ): # TODO: how to do that better? _UpperCamelCase = 0 @property def _UpperCamelCase ( self : Optional[Any] ) -> List[str]: _UpperCamelCase = OrderedDict({'''input_ids''': {0: '''batch''', 1: '''sequence'''}} ) if self.use_past: # BLOOM stores values on dynamic axis 2. For more details see: https://github.com/huggingface/transformers/pull/18344 self.fill_with_past_key_values_(_a , direction='''inputs''' , inverted_values_shape=_a ) _UpperCamelCase = {0: '''batch''', 1: '''past_sequence + sequence'''} else: _UpperCamelCase = {0: '''batch''', 1: '''sequence'''} return common_inputs @property def _UpperCamelCase ( self : Optional[int] ) -> Tuple: return self._config.n_layer @property def _UpperCamelCase ( self : int ) -> Optional[int]: return self._config.n_head @property def _UpperCamelCase ( self : Optional[int] ) -> List[Any]: return 1E-3 def _UpperCamelCase ( self : Dict , __UpperCamelCase : str , __UpperCamelCase : Dict = -1 , __UpperCamelCase : List[Any] = -1 , __UpperCamelCase : Dict = False , __UpperCamelCase : List[Any] = None , ) -> Any: _UpperCamelCase = super(_a , self ).generate_dummy_inputs( _a , batch_size=_a , seq_length=_a , is_pair=_a , framework=_a ) # We need to order the input in the way they appears in the forward() _UpperCamelCase = 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 _UpperCamelCase , _UpperCamelCase = common_inputs['''input_ids'''].shape # Not using the same length for past_key_values _UpperCamelCase = seqlen + 2 _UpperCamelCase = self._config.hidden_size // self.num_attention_heads _UpperCamelCase = ( batch * self.num_attention_heads, head_dim, past_key_values_length, ) _UpperCamelCase = ( batch * self.num_attention_heads, past_key_values_length, head_dim, ) _UpperCamelCase = [ (torch.zeros(_a ), torch.zeros(_a )) for _ in range(self.num_layers ) ] _UpperCamelCase = common_inputs['''attention_mask'''] if self.use_past: _UpperCamelCase = ordered_inputs['''attention_mask'''].dtype _UpperCamelCase = torch.cat( [ordered_inputs['''attention_mask'''], torch.ones(_a , _a , dtype=_a )] , dim=1 ) return ordered_inputs @property def _UpperCamelCase ( self : Any ) -> Tuple: return 13
256
"""simple docstring""" import numpy as np def lowercase ( lowerCAmelCase__ : np.ndarray , lowerCAmelCase__ : float ) -> np.ndarray: return np.where(vector > 0 , lowerCAmelCase__ , (alpha * (np.exp(lowerCAmelCase__ ) - 1)) ) if __name__ == "__main__": import doctest doctest.testmod()
45
0
"""simple docstring""" from bisect import bisect from itertools import accumulate def _lowerCamelCase( a , a , a , a ): __a = sorted(zip(lowerCAmelCase__ , lowerCAmelCase__ ) , key=lambda a : x[0] / x[1] , reverse=lowerCAmelCase__ ) __a , __a = [i[0] for i in r], [i[1] for i in r] __a = list(accumulate(lowerCAmelCase__ ) ) __a = bisect(lowerCAmelCase__ , lowerCAmelCase__ ) return ( 0 if k == 0 else sum(vl[:k] ) + (w - acc[k - 1]) * (vl[k]) / (wt[k]) if k != n else sum(vl[:k] ) ) if __name__ == "__main__": import doctest doctest.testmod()
261
"""simple docstring""" def lowercase ( lowerCAmelCase__ : str = "The quick brown fox jumps over the lazy dog" , ) -> bool: __a = set() # Replace all the whitespace in our sentence __a = input_str.replace(''' ''' , '''''' ) for alpha in input_str: if "a" <= alpha.lower() <= "z": frequency.add(alpha.lower() ) return len(lowerCAmelCase__ ) == 26 def lowercase ( lowerCAmelCase__ : str = "The quick brown fox jumps over the lazy dog" , ) -> bool: __a = [False] * 26 for char in input_str: if char.islower(): __a = True elif char.isupper(): __a = True return all(lowerCAmelCase__ ) def lowercase ( lowerCAmelCase__ : str = "The quick brown fox jumps over the lazy dog" , ) -> bool: return len({char for char in input_str.lower() if char.isalpha()} ) == 26 def lowercase ( ) -> None: from timeit import timeit __a = '''from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest''' print(timeit('''is_pangram()''' , setup=lowerCAmelCase__ ) ) print(timeit('''is_pangram_faster()''' , setup=lowerCAmelCase__ ) ) print(timeit('''is_pangram_fastest()''' , setup=lowerCAmelCase__ ) ) # 5.348480500048026, 2.6477354579837993, 1.8470395830227062 # 5.036091582966037, 2.644472333951853, 1.8869528750656173 if __name__ == "__main__": import doctest doctest.testmod() benchmark()
45
0
"""simple docstring""" from copy import deepcopy class lowerCAmelCase__ : def __init__( self : Union[str, Any] , _lowerCamelCase : Tuple = None , _lowerCamelCase : Union[str, Any] = None ): if arr is None and size is not None: _snake_case = size _snake_case = [0] * size elif arr is not None: self.init(_a ) else: raise ValueError('''Either arr or size must be specified''' ) def lowercase ( self : int , _lowerCamelCase : Any ): _snake_case = len(_a ) _snake_case = deepcopy(_a ) for i in range(1 , self.size ): _snake_case = self.next_(_a ) if j < self.size: self.tree[j] += self.tree[i] def lowercase ( self : Union[str, Any] ): _snake_case = self.tree[:] for i in range(self.size - 1 , 0 , -1 ): _snake_case = self.next_(_a ) if j < self.size: arr[j] -= arr[i] return arr @staticmethod def lowercase ( _lowerCamelCase : str ): return index + (index & (-index)) @staticmethod def lowercase ( _lowerCamelCase : Tuple ): return index - (index & (-index)) def lowercase ( self : Optional[Any] , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : Tuple ): if index == 0: self.tree[0] += value return while index < self.size: self.tree[index] += value _snake_case = self.next_(_a ) def lowercase ( self : Any , _lowerCamelCase : int , _lowerCamelCase : Tuple ): self.add(_a , value - self.get(_a ) ) def lowercase ( self : List[str] , _lowerCamelCase : Dict ): if right == 0: return 0 _snake_case = self.tree[0] right -= 1 # make right inclusive while right > 0: result += self.tree[right] _snake_case = self.prev(_a ) return result def lowercase ( self : Union[str, Any] , _lowerCamelCase : Dict , _lowerCamelCase : Tuple ): return self.prefix(_a ) - self.prefix(_a ) def lowercase ( self : List[Any] , _lowerCamelCase : Tuple ): return self.query(_a , index + 1 ) def lowercase ( self : Optional[int] , _lowerCamelCase : Optional[Any] ): value -= self.tree[0] if value < 0: return -1 _snake_case = 1 # Largest power of 2 <= size while j * 2 < self.size: j *= 2 _snake_case = 0 while j > 0: if i + j < self.size and self.tree[i + j] <= value: value -= self.tree[i + j] i += j j //= 2 return i if __name__ == "__main__": import doctest doctest.testmod()
288
"""simple docstring""" import gc import unittest from transformers import CTRLConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, CTRLForSequenceClassification, CTRLLMHeadModel, CTRLModel, ) class __lowerCAmelCase : '''simple docstring''' def __init__( self , _a , _a=14 , _a=7 , _a=True , _a=True , _a=True , _a=True , _a=True , _a=99 , _a=32 , _a=5 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=16 , _a=2 , _a=0.02 , _a=3 , _a=4 , _a=None , ): __a = parent __a = batch_size __a = seq_length __a = is_training __a = use_token_type_ids __a = use_input_mask __a = use_labels __a = use_mc_token_ids __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = type_vocab_size __a = type_sequence_label_size __a = initializer_range __a = num_labels __a = num_choices __a = scope __a = self.vocab_size - 1 def __UpperCAmelCase ( self ): __a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a = None if self.use_input_mask: __a = random_attention_mask([self.batch_size, self.seq_length] ) __a = None if self.use_token_type_ids: __a = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __a = None if self.use_mc_token_ids: __a = ids_tensor([self.batch_size, self.num_choices] , self.seq_length ) __a = None __a = None __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __a = ids_tensor([self.batch_size] , self.num_choices ) __a = self.get_config() __a = ids_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 ) return ( config, input_ids, input_mask, head_mask, token_type_ids, mc_token_ids, sequence_labels, token_labels, choice_labels, ) def __UpperCAmelCase ( self ): return CTRLConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , pad_token_id=self.pad_token_id , ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , *_a ): __a = CTRLModel(config=_a ) model.to(_a ) model.eval() model(_a , token_type_ids=_a , head_mask=_a ) model(_a , token_type_ids=_a ) __a = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(len(result.past_key_values ) , config.n_layer ) def __UpperCAmelCase ( self , _a , _a , _a , _a , _a , *_a ): __a = CTRLLMHeadModel(_a ) model.to(_a ) model.eval() __a = model(_a , token_type_ids=_a , labels=_a ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self ): __a = self.prepare_config_and_inputs() ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = config_and_inputs __a = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''head_mask''': head_mask} return config, inputs_dict def __UpperCAmelCase ( self , _a , _a , _a , _a , *_a ): __a = self.num_labels __a = CTRLForSequenceClassification(_a ) model.to(_a ) model.eval() __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = model(_a , token_type_ids=_a , labels=_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) @require_torch class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase : str = (CTRLModel, CTRLLMHeadModel, CTRLForSequenceClassification) if is_torch_available() else () __UpperCAmelCase : Union[str, Any] = (CTRLLMHeadModel,) if is_torch_available() else () __UpperCAmelCase : Union[str, Any] = ( { 'feature-extraction': CTRLModel, 'text-classification': CTRLForSequenceClassification, 'text-generation': CTRLLMHeadModel, 'zero-shot': CTRLForSequenceClassification, } if is_torch_available() else {} ) __UpperCAmelCase : Optional[Any] = True __UpperCAmelCase : List[Any] = False __UpperCAmelCase : str = False def __UpperCAmelCase ( self , _a , _a , _a , _a , _a ): if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests": # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers. # `CTRLConfig` was never used in pipeline tests, either because of a missing checkpoint or because a tiny # config could not be created. return True return False def __UpperCAmelCase ( self ): __a = CTRLModelTester(self ) __a = ConfigTester(self , config_class=_a , n_embd=37 ) def __UpperCAmelCase ( self ): super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() torch.cuda.empty_cache() def __UpperCAmelCase ( self ): self.config_tester.run_common_tests() def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_ctrl_model(*_a ) def __UpperCAmelCase ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*_a ) @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def __UpperCAmelCase ( self ): pass @slow def __UpperCAmelCase ( self ): for model_name in CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = CTRLModel.from_pretrained(_a ) self.assertIsNotNone(_a ) @unittest.skip('''The model doesn\'t support left padding''' ) # and it's not used enough to be worth fixing :) def __UpperCAmelCase ( self ): pass @require_torch class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() torch.cuda.empty_cache() @slow def __UpperCAmelCase ( self ): __a = CTRLLMHeadModel.from_pretrained('''ctrl''' ) model.to(_a ) __a = torch.tensor( [[11_859, 0, 1_611, 8]] , dtype=torch.long , device=_a ) # Legal the president is __a = [ 11_859, 0, 1_611, 8, 5, 150, 26_449, 2, 19, 348, 469, 3, 2_595, 48, 20_740, 246_533, 246_533, 19, 30, 5, ] # Legal the president is a good guy and I don't want to lose my job. \n \n I have a __a = model.generate(_a , do_sample=_a ) self.assertListEqual(output_ids[0].tolist() , _a )
45
0
import json import logging import os import sys from pathlib import Path import finetune_rag from transformers.file_utils import is_apex_available from transformers.testing_utils import ( TestCasePlus, execute_subprocess_async, require_ray, require_torch_gpu, require_torch_multi_gpu, ) logging.basicConfig(level=logging.DEBUG) lowerCAmelCase__ = logging.getLogger() lowerCAmelCase__ = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class a__ ( __SCREAMING_SNAKE_CASE ): """simple docstring""" def UpperCamelCase ( self , lowercase ) -> Tuple: '''simple docstring''' os.makedirs(_a , exist_ok=_a ) A__ = {"source": "What is love ?", "target": "life"} A__ = {"train": 12, "val": 2, "test": 2} for split in ["train", "test", "val"]: for field in ["source", "target"]: A__ = "\n".join([contents[field]] * n_lines[split] ) with open(os.path.join(_a , F'{split}.{field}' ) , "w" ) as f: f.write(_a ) def UpperCamelCase ( self , lowercase , lowercase = "pytorch" ) -> int: '''simple docstring''' A__ = self.get_auto_remove_tmp_dir() A__ = os.path.join(_a , "output" ) A__ = os.path.join(_a , "data" ) self._create_dummy_data(data_dir=_a ) A__ = F'\n --data_dir {data_dir} \\n --output_dir {output_dir} \\n --model_name_or_path facebook/rag-sequence-base \\n --model_type rag_sequence \\n --do_train \\n --do_predict \\n --n_val -1 \\n --val_check_interval 1.0 \\n --train_batch_size 2 \\n --eval_batch_size 1 \\n --max_source_length 25 \\n --max_target_length 25 \\n --val_max_target_length 25 \\n --test_max_target_length 25 \\n --label_smoothing 0.1 \\n --dropout 0.1 \\n --attention_dropout 0.1 \\n --weight_decay 0.001 \\n --adam_epsilon 1e-08 \\n --max_grad_norm 0.1 \\n --lr_scheduler polynomial \\n --learning_rate 3e-04 \\n --num_train_epochs 1 \\n --warmup_steps 4 \\n --gradient_accumulation_steps 1 \\n --distributed-port 8787 \\n --use_dummy_dataset 1 \\n --distributed_retriever {distributed_retriever} \\n '.split() if gpus > 0: testargs.append(F'--gpus={gpus}' ) if is_apex_available(): testargs.append("--fp16" ) else: testargs.append("--gpus=0" ) testargs.append("--distributed_backend=ddp_cpu" ) testargs.append("--num_processes=2" ) A__ = [sys.executable, str(Path(finetune_rag.__file__ ).resolve() )] + testargs execute_subprocess_async(_a , env=self.get_env() ) A__ = os.path.join(_a , "metrics.json" ) with open(_a ) as f: A__ = json.load(_a ) return result @require_torch_gpu def UpperCamelCase ( self ) -> List[Any]: '''simple docstring''' A__ = self._run_finetune(gpus=1 ) self.assertGreaterEqual(result["test"][0]["test_avg_em"] , 0.2 ) @require_torch_multi_gpu def UpperCamelCase ( self ) -> List[str]: '''simple docstring''' A__ = self._run_finetune(gpus=2 ) self.assertGreaterEqual(result["test"][0]["test_avg_em"] , 0.2 ) @require_torch_gpu @require_ray def UpperCamelCase ( self ) -> Optional[int]: '''simple docstring''' A__ = self._run_finetune(gpus=1 , distributed_retriever="ray" ) self.assertGreaterEqual(result["test"][0]["test_avg_em"] , 0.2 ) @require_torch_multi_gpu @require_ray def UpperCamelCase ( self ) -> List[str]: '''simple docstring''' A__ = self._run_finetune(gpus=1 , distributed_retriever="ray" ) self.assertGreaterEqual(result["test"][0]["test_avg_em"] , 0.2 )
68
"""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, ) lowercase_ = {"configuration_xglm": ["XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP", "XGLMConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["XGLMTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["XGLMTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "XGLM_PRETRAINED_MODEL_ARCHIVE_LIST", "XGLMForCausalLM", "XGLMModel", "XGLMPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "FlaxXGLMForCausalLM", "FlaxXGLMModel", "FlaxXGLMPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST", "TFXGLMForCausalLM", "TFXGLMModel", "TFXGLMPreTrainedModel", ] if TYPE_CHECKING: from .configuration_xglm import XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XGLMConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm import XGLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm_fast import XGLMTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xglm import XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, XGLMForCausalLM, XGLMModel, XGLMPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_xglm import FlaxXGLMForCausalLM, FlaxXGLMModel, FlaxXGLMPreTrainedModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, TFXGLMPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure)
45
0
def lowerCAmelCase__ ( a__: int ) -> str: '''simple docstring''' if number > 0: raise ValueError('input must be a negative integer' ) _UpperCAmelCase = len(bin(lowerCAmelCase__ )[3:] ) _UpperCAmelCase = bin(abs(lowerCAmelCase__ ) - (1 << binary_number_length) )[3:] _UpperCAmelCase = ( ( '1' + '0' * (binary_number_length - len(lowerCAmelCase__ )) + twos_complement_number ) if number < 0 else '0' ) return "0b" + twos_complement_number if __name__ == "__main__": import doctest doctest.testmod()
329
"""simple docstring""" 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 lowercase_ = re.compile("[^A-Za-z_0-9]") # parameters used in DuplicationIndex lowercase_ = 1_0 lowercase_ = 2_5_6 def lowercase ( lowerCAmelCase__ : List[str] ) -> Optional[MinHash]: if len(lowerCAmelCase__ ) < MIN_NUM_TOKENS: return None __a = MinHash(num_perm=lowerCAmelCase__ ) for token in set(lowerCAmelCase__ ): min_hash.update(token.encode() ) return min_hash def lowercase ( lowerCAmelCase__ : str ) -> Set[str]: return {t for t in NON_ALPHA.split(lowerCAmelCase__ ) if len(t.strip() ) > 0} class __lowerCAmelCase : '''simple docstring''' def __init__( self , *, _a = 0.85 , ): __a = duplication_jaccard_threshold __a = NUM_PERM __a = MinHashLSH(threshold=self._duplication_jaccard_threshold , num_perm=self._num_perm ) __a = defaultdict(_a ) def __UpperCAmelCase ( self , _a , _a ): __a = 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 __UpperCAmelCase ( self ): __a = [] for base, duplicates in self._duplicate_clusters.items(): __a = [base] + list(_a ) # reformat the cluster to be a list of dict __a = [{'''base_index''': el[0], '''repo_name''': el[1], '''path''': el[2]} for el in cluster] duplicate_clusters.append(_a ) return duplicate_clusters def __UpperCAmelCase ( self , _a ): __a = self.get_duplicate_clusters() with open(_a , '''w''' ) as f: json.dump(_a , _a ) def lowercase ( lowerCAmelCase__ : List[str] ) -> int: __a , __a = element __a = 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 lowercase ( lowerCAmelCase__ : Type[Dataset] ) -> str: 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 lowercase ( lowerCAmelCase__ : Type[Dataset] , lowerCAmelCase__ : float ) -> Dict: __a = 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 lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : str ) -> float: __a = get_tokens(lowerCAmelCase__ ) __a = get_tokens(lowerCAmelCase__ ) return len(tokensa & tokensa ) / len(tokensa | tokensa ) lowercase_ = None def lowercase ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Union[str, Any] ) -> Any: __a = [] for elementa in cluster: __a = _shared_dataset[elementa['''base_index''']]['''content'''] for elementa in extremes: __a = _shared_dataset[elementa['''base_index''']]['''content'''] if jaccard_similarity(lowerCAmelCase__ , lowerCAmelCase__ ) >= jaccard_threshold: elementa["copies"] += 1 break else: __a = 1 extremes.append(lowerCAmelCase__ ) return extremes def lowercase ( lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Optional[int] ) -> Optional[int]: global _shared_dataset __a = dataset __a = [] __a = 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 lowercase ( lowerCAmelCase__ : Type[Dataset] , lowerCAmelCase__ : float = 0.85 ) -> Tuple[Type[Dataset], List[List[Dict]]]: __a = make_duplicate_clusters(lowerCAmelCase__ , lowerCAmelCase__ ) __a = {x['''base_index'''] for cluster in duplicate_clusters for x in cluster} __a = {} __a = find_extremes(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) for extremes in extremes_clusters: for element in extremes: __a = element __a = duplicate_indices - set(extreme_dict.keys() ) __a = 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: __a = element['''base_index'''] in extreme_dict if element["is_extreme"]: __a = 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
45
0
'''simple docstring''' import os import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from huggingface_hub.file_download import http_get from requests.exceptions import HTTPError from transformers import ( AlbertTokenizer, AutoTokenizer, BertTokenizer, BertTokenizerFast, GPTaTokenizerFast, is_tokenizers_available, ) from transformers.testing_utils import TOKEN, USER, is_staging_test, require_tokenizers from transformers.tokenization_utils import Trie sys.path.append(str(Path(__file__).parent.parent / 'utils')) from test_module.custom_tokenization import CustomTokenizer # noqa E402 if is_tokenizers_available(): from test_module.custom_tokenization_fast import CustomTokenizerFast class A__ ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : str ) -> Optional[int]: """simple docstring""" _UpperCAmelCase : Any = mock.Mock() _UpperCAmelCase : int = 5_0_0 _UpperCAmelCase : Optional[Any] = {} _UpperCAmelCase : List[str] = HTTPError _UpperCAmelCase : Tuple = {} # Download this model to make sure it's in the cache. _UpperCAmelCase : Tuple = BertTokenizer.from_pretrained("hf-internal-testing/tiny-random-bert" ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch("requests.Session.request" , return_value=_a ) as mock_head: _UpperCAmelCase : List[Any] = BertTokenizer.from_pretrained("hf-internal-testing/tiny-random-bert" ) # This check we did call the fake head request mock_head.assert_called() @require_tokenizers def _lowerCAmelCase ( self : int ) -> Tuple: """simple docstring""" _UpperCAmelCase : str = mock.Mock() _UpperCAmelCase : Union[str, Any] = 5_0_0 _UpperCAmelCase : Dict = {} _UpperCAmelCase : List[str] = HTTPError _UpperCAmelCase : int = {} # Download this model to make sure it's in the cache. _UpperCAmelCase : str = GPTaTokenizerFast.from_pretrained("gpt2" ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch("requests.Session.request" , return_value=_a ) as mock_head: _UpperCAmelCase : int = GPTaTokenizerFast.from_pretrained("gpt2" ) # This check we did call the fake head request mock_head.assert_called() def _lowerCAmelCase ( self : Tuple ) -> str: """simple docstring""" try: _UpperCAmelCase : Optional[Any] = tempfile.mktemp() with open(_a , "wb" ) as f: http_get("https://huggingface.co/albert-base-v1/resolve/main/spiece.model" , _a ) _UpperCAmelCase : int = AlbertTokenizer.from_pretrained(_a ) finally: os.remove(_a ) # Supporting this legacy load introduced a weird bug where the tokenizer would load local files if they are in # the current folder and have the right name. if os.path.isfile("tokenizer.json" ): # We skip the test if the user has a `tokenizer.json` in this folder to avoid deleting it. return try: with open("tokenizer.json" , "wb" ) as f: http_get("https://huggingface.co/hf-internal-testing/tiny-random-bert/blob/main/tokenizer.json" , _a ) _UpperCAmelCase : Union[str, Any] = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) # The tiny random BERT has a vocab size of 1024, tiny gpt2 as a vocab size of 1000 self.assertEqual(tokenizer.vocab_size , 1_0_0_0 ) # Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file. finally: os.remove("tokenizer.json" ) def _lowerCAmelCase ( self : Optional[int] ) -> int: """simple docstring""" _UpperCAmelCase : List[str] = AlbertTokenizer.from_pretrained("https://huggingface.co/albert-base-v1/resolve/main/spiece.model" ) @is_staging_test class A__ ( unittest.TestCase ): """simple docstring""" UpperCamelCase_ : List[str] = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'bla', 'blou'] @classmethod def _lowerCAmelCase ( cls : Any ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase : int = TOKEN HfFolder.save_token(_a ) @classmethod def _lowerCAmelCase ( cls : Tuple ) -> Optional[int]: """simple docstring""" try: delete_repo(token=cls._token , repo_id="test-tokenizer" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="valid_org/test-tokenizer-org" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="test-dynamic-tokenizer" ) except HTTPError: pass def _lowerCAmelCase ( self : Any ) -> Optional[Any]: """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: _UpperCAmelCase : List[Any] = os.path.join(_a , "vocab.txt" ) with open(_a , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) ) _UpperCAmelCase : int = BertTokenizer(_a ) tokenizer.push_to_hub("test-tokenizer" , use_auth_token=self._token ) _UpperCAmelCase : Dict = BertTokenizer.from_pretrained(F"""{USER}/test-tokenizer""" ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) # Reset repo delete_repo(token=self._token , repo_id="test-tokenizer" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(_a , repo_id="test-tokenizer" , push_to_hub=_a , use_auth_token=self._token ) _UpperCAmelCase : Tuple = BertTokenizer.from_pretrained(F"""{USER}/test-tokenizer""" ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) def _lowerCAmelCase ( self : Tuple ) -> Any: """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: _UpperCAmelCase : Dict = os.path.join(_a , "vocab.txt" ) with open(_a , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) ) _UpperCAmelCase : Optional[Any] = BertTokenizer(_a ) tokenizer.push_to_hub("valid_org/test-tokenizer-org" , use_auth_token=self._token ) _UpperCAmelCase : int = BertTokenizer.from_pretrained("valid_org/test-tokenizer-org" ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) # Reset repo delete_repo(token=self._token , repo_id="valid_org/test-tokenizer-org" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained( _a , repo_id="valid_org/test-tokenizer-org" , push_to_hub=_a , use_auth_token=self._token ) _UpperCAmelCase : Any = BertTokenizer.from_pretrained("valid_org/test-tokenizer-org" ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) @require_tokenizers def _lowerCAmelCase ( self : Optional[int] ) -> Optional[int]: """simple docstring""" CustomTokenizer.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: _UpperCAmelCase : Tuple = os.path.join(_a , "vocab.txt" ) with open(_a , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) ) _UpperCAmelCase : List[Any] = CustomTokenizer(_a ) # No fast custom tokenizer tokenizer.push_to_hub("test-dynamic-tokenizer" , use_auth_token=self._token ) _UpperCAmelCase : Dict = AutoTokenizer.from_pretrained(F"""{USER}/test-dynamic-tokenizer""" , trust_remote_code=_a ) # Can't make an isinstance check because the new_model.config is from the CustomTokenizer class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ , "CustomTokenizer" ) # Fast and slow custom tokenizer CustomTokenizerFast.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: _UpperCAmelCase : Dict = os.path.join(_a , "vocab.txt" ) with open(_a , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) ) _UpperCAmelCase : Dict = BertTokenizerFast.from_pretrained(_a ) bert_tokenizer.save_pretrained(_a ) _UpperCAmelCase : List[Any] = CustomTokenizerFast.from_pretrained(_a ) tokenizer.push_to_hub("test-dynamic-tokenizer" , use_auth_token=self._token ) _UpperCAmelCase : str = AutoTokenizer.from_pretrained(F"""{USER}/test-dynamic-tokenizer""" , trust_remote_code=_a ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ , "CustomTokenizerFast" ) _UpperCAmelCase : Optional[int] = AutoTokenizer.from_pretrained( F"""{USER}/test-dynamic-tokenizer""" , use_fast=_a , trust_remote_code=_a ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ , "CustomTokenizer" ) class A__ ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : Any ) -> int: """simple docstring""" _UpperCAmelCase : int = Trie() trie.add("Hello 友達" ) self.assertEqual(trie.data , {"H": {"e": {"l": {"l": {"o": {" ": {"友": {"達": {"": 1}}}}}}}}} ) trie.add("Hello" ) trie.data self.assertEqual(trie.data , {"H": {"e": {"l": {"l": {"o": {"": 1, " ": {"友": {"達": {"": 1}}}}}}}}} ) def _lowerCAmelCase ( self : str ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase : Optional[int] = Trie() self.assertEqual(trie.split("[CLS] This is a extra_id_100" ) , ["[CLS] This is a extra_id_100"] ) trie.add("[CLS]" ) trie.add("extra_id_1" ) trie.add("extra_id_100" ) self.assertEqual(trie.split("[CLS] This is a extra_id_100" ) , ["[CLS]", " This is a ", "extra_id_100"] ) def _lowerCAmelCase ( self : Union[str, Any] ) -> str: """simple docstring""" _UpperCAmelCase : Optional[Any] = Trie() trie.add("A" ) self.assertEqual(trie.split("ABC" ) , ["A", "BC"] ) self.assertEqual(trie.split("BCA" ) , ["BC", "A"] ) def _lowerCAmelCase ( self : List[str] ) -> Any: """simple docstring""" _UpperCAmelCase : List[Any] = Trie() trie.add("TOKEN]" ) trie.add("[SPECIAL_TOKEN]" ) self.assertEqual(trie.split("This is something [SPECIAL_TOKEN]" ) , ["This is something ", "[SPECIAL_TOKEN]"] ) def _lowerCAmelCase ( self : Optional[Any] ) -> Any: """simple docstring""" _UpperCAmelCase : Optional[int] = Trie() trie.add("A" ) trie.add("P" ) trie.add("[SPECIAL_TOKEN]" ) self.assertEqual(trie.split("This is something [SPECIAL_TOKEN]" ) , ["This is something ", "[SPECIAL_TOKEN]"] ) def _lowerCAmelCase ( self : List[Any] ) -> List[str]: """simple docstring""" _UpperCAmelCase : Dict = Trie() trie.add("AB" ) trie.add("B" ) trie.add("C" ) self.assertEqual(trie.split("ABC" ) , ["AB", "C"] ) def _lowerCAmelCase ( self : Optional[Any] ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase : int = Trie() trie.add("ABC" ) trie.add("B" ) trie.add("CD" ) self.assertEqual(trie.split("ABCD" ) , ["ABC", "D"] ) def _lowerCAmelCase ( self : Optional[Any] ) -> Any: """simple docstring""" _UpperCAmelCase : Union[str, Any] = Trie() _UpperCAmelCase : Union[str, Any] = trie.cut_text("ABC" , [0, 0, 2, 1, 2, 3] ) self.assertEqual(_a , ["AB", "C"] )
145
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowercase_ = { "configuration_roformer": ["ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "RoFormerConfig", "RoFormerOnnxConfig"], "tokenization_roformer": ["RoFormerTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["RoFormerTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "RoFormerForCausalLM", "RoFormerForMaskedLM", "RoFormerForMultipleChoice", "RoFormerForQuestionAnswering", "RoFormerForSequenceClassification", "RoFormerForTokenClassification", "RoFormerLayer", "RoFormerModel", "RoFormerPreTrainedModel", "load_tf_weights_in_roformer", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TFRoFormerForCausalLM", "TFRoFormerForMaskedLM", "TFRoFormerForMultipleChoice", "TFRoFormerForQuestionAnswering", "TFRoFormerForSequenceClassification", "TFRoFormerForTokenClassification", "TFRoFormerLayer", "TFRoFormerModel", "TFRoFormerPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "FlaxRoFormerForMaskedLM", "FlaxRoFormerForMultipleChoice", "FlaxRoFormerForQuestionAnswering", "FlaxRoFormerForSequenceClassification", "FlaxRoFormerForTokenClassification", "FlaxRoFormerModel", "FlaxRoFormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_roformer import ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, RoFormerConfig, RoFormerOnnxConfig from .tokenization_roformer import RoFormerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roformer_fast import RoFormerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roformer import ( ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, RoFormerForCausalLM, RoFormerForMaskedLM, RoFormerForMultipleChoice, RoFormerForQuestionAnswering, RoFormerForSequenceClassification, RoFormerForTokenClassification, RoFormerLayer, RoFormerModel, RoFormerPreTrainedModel, load_tf_weights_in_roformer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roformer import ( TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerLayer, TFRoFormerModel, TFRoFormerPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roformer import ( FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, FlaxRoFormerPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
45
0
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging __a :List[Any] = logging.get_logger(__name__) __a :Tuple = { 'asapp/sew-tiny-100k': 'https://huggingface.co/asapp/sew-tiny-100k/resolve/main/config.json', # See all SEW models at https://huggingface.co/models?filter=sew } class _a ( __SCREAMING_SNAKE_CASE ): """simple docstring""" _lowerCamelCase : int = 'sew' def __init__( self : List[Any] , UpperCAmelCase : Union[str, Any]=32 , UpperCAmelCase : Optional[int]=768 , UpperCAmelCase : str=12 , UpperCAmelCase : Optional[Any]=12 , UpperCAmelCase : List[str]=3072 , UpperCAmelCase : List[str]=2 , UpperCAmelCase : List[Any]="gelu" , UpperCAmelCase : int=0.1 , UpperCAmelCase : int=0.1 , UpperCAmelCase : Any=0.1 , UpperCAmelCase : Any=0.0 , UpperCAmelCase : Tuple=0.1 , UpperCAmelCase : int=0.1 , UpperCAmelCase : Any=0.02 , UpperCAmelCase : Optional[int]=1E-5 , UpperCAmelCase : Dict="group" , UpperCAmelCase : Any="gelu" , UpperCAmelCase : int=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512) , UpperCAmelCase : str=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) , UpperCAmelCase : Union[str, Any]=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) , UpperCAmelCase : Optional[Any]=False , UpperCAmelCase : Union[str, Any]=128 , UpperCAmelCase : List[str]=16 , UpperCAmelCase : Any=True , UpperCAmelCase : Optional[int]=0.05 , UpperCAmelCase : Optional[Any]=10 , UpperCAmelCase : Any=2 , UpperCAmelCase : List[Any]=0.0 , UpperCAmelCase : int=10 , UpperCAmelCase : List[Any]=0 , UpperCAmelCase : List[Any]="mean" , UpperCAmelCase : Union[str, Any]=False , UpperCAmelCase : List[Any]=False , UpperCAmelCase : List[Any]=256 , UpperCAmelCase : Optional[Any]=0 , UpperCAmelCase : List[Any]=1 , UpperCAmelCase : List[Any]=2 , **UpperCAmelCase : Union[str, Any] , ): super().__init__(**_a , pad_token_id=_a , bos_token_id=_a , eos_token_id=_a ) A_ = hidden_size A_ = feat_extract_norm A_ = feat_extract_activation A_ = list(_a ) A_ = list(_a ) A_ = list(_a ) A_ = conv_bias A_ = num_conv_pos_embeddings A_ = num_conv_pos_embedding_groups A_ = len(self.conv_dim ) A_ = num_hidden_layers A_ = intermediate_size A_ = squeeze_factor A_ = hidden_act A_ = num_attention_heads A_ = hidden_dropout A_ = attention_dropout A_ = activation_dropout A_ = feat_proj_dropout A_ = final_dropout A_ = layerdrop A_ = layer_norm_eps A_ = initializer_range A_ = vocab_size if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( "Configuration for convolutional layers is incorrect." "It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`," f'''but is `len(config.conv_dim) = {len(self.conv_dim )}`, `len(config.conv_stride)''' f'''= {len(self.conv_stride )}`, `len(config.conv_kernel) = {len(self.conv_kernel )}`.''' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 A_ = apply_spec_augment A_ = mask_time_prob A_ = mask_time_length A_ = mask_time_min_masks A_ = mask_feature_prob A_ = mask_feature_length A_ = mask_feature_min_masks # ctc loss A_ = ctc_loss_reduction A_ = ctc_zero_infinity # sequence classification A_ = use_weighted_layer_sum A_ = classifier_proj_size @property def __A ( self : Any ): return functools.reduce(operator.mul , self.conv_stride , 1 )
312
"""simple docstring""" import warnings from ..trainer import Trainer from ..utils import logging lowercase_ = logging.get_logger(__name__) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , _a=None , **_a ): warnings.warn( '''`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` ''' '''instead.''' , _a , ) super().__init__(args=_a , **_a )
45
0
from collections import namedtuple lowerCamelCase : Tuple = namedtuple("from_to", "from_ to") lowerCamelCase : Any = { "cubicmeter": from_to(1, 1), "litre": from_to(0.001, 1_000), "kilolitre": from_to(1, 1), "gallon": from_to(0.0_0454, 264.172), "cubicyard": from_to(0.7_6455, 1.3_0795), "cubicfoot": from_to(0.028, 35.3147), "cup": from_to(0.0_0023_6588, 4226.75), } def _SCREAMING_SNAKE_CASE ( lowercase : float , lowercase : str , lowercase : str ): '''simple docstring''' if from_type not in METRIC_CONVERSION: raise ValueError( f"""Invalid \'from_type\' value: {from_type!r} Supported values are:\n""" + ', '.join(lowerCAmelCase__ ) ) if to_type not in METRIC_CONVERSION: raise ValueError( f"""Invalid \'to_type\' value: {to_type!r}. Supported values are:\n""" + ', '.join(lowerCAmelCase__ ) ) return value * METRIC_CONVERSION[from_type].from_ * METRIC_CONVERSION[to_type].to if __name__ == "__main__": import doctest doctest.testmod()
204
"""simple docstring""" import math def lowercase ( lowerCAmelCase__ : list , lowerCAmelCase__ : int ) -> int: __a = len(lowerCAmelCase__ ) __a = int(math.floor(math.sqrt(lowerCAmelCase__ ) ) ) __a = 0 while arr[min(lowerCAmelCase__ , lowerCAmelCase__ ) - 1] < x: __a = step step += int(math.floor(math.sqrt(lowerCAmelCase__ ) ) ) if prev >= n: return -1 while arr[prev] < x: __a = prev + 1 if prev == min(lowerCAmelCase__ , lowerCAmelCase__ ): return -1 if arr[prev] == x: return prev return -1 if __name__ == "__main__": lowercase_ = input("Enter numbers separated by a comma:\n").strip() lowercase_ = [int(item) for item in user_input.split(",")] lowercase_ = int(input("Enter the number to be searched:\n")) lowercase_ = jump_search(arr, x) if res == -1: print("Number not found!") else: print(F'''Number {x} is at index {res}''')
45
0
import math from dataclasses import dataclass from typing import Optional, Tuple, Union import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin, SchedulerOutput @dataclass class __magic_name__ ( __SCREAMING_SNAKE_CASE ): """simple docstring""" __UpperCamelCase = 42 __UpperCamelCase = 42 class __magic_name__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" __UpperCamelCase = 1 @register_to_config def __init__( self :Any , snake_case :Optional[Any] = 2_000 , snake_case :Union[str, Any] = 0.15 , snake_case :Optional[int] = 0.01 , snake_case :str = 1348.0 , snake_case :List[str] = 1e-5 , snake_case :List[Any] = 1 , ): '''simple docstring''' A_ : Tuple = sigma_max # setable values A_ : str = None self.set_sigmas(_a , _a , _a , _a ) def SCREAMING_SNAKE_CASE ( self :Tuple , snake_case :List[str] , snake_case :Dict = None ): '''simple docstring''' return sample def SCREAMING_SNAKE_CASE ( self :Any , snake_case :str , snake_case :Any = None , snake_case :Optional[Any] = None ): '''simple docstring''' A_ : Optional[int] = sampling_eps if sampling_eps is not None else self.config.sampling_eps A_ : Optional[int] = torch.linspace(1 , _a , _a , device=_a ) def SCREAMING_SNAKE_CASE ( self :Optional[Any] , snake_case :Tuple , snake_case :str = None , snake_case :Dict = None , snake_case :str = None ): '''simple docstring''' A_ : List[str] = sigma_min if sigma_min is not None else self.config.sigma_min A_ : List[str] = sigma_max if sigma_max is not None else self.config.sigma_max A_ : Any = sampling_eps if sampling_eps is not None else self.config.sampling_eps if self.timesteps is None: self.set_timesteps(_a , _a ) A_ : Optional[int] = sigma_min * (sigma_max / sigma_min) ** (self.timesteps / sampling_eps) A_ : Optional[int] = torch.exp(torch.linspace(math.log(_a ) , math.log(_a ) , _a ) ) A_ : List[Any] = torch.tensor([sigma_min * (sigma_max / sigma_min) ** t for t in self.timesteps] ) def SCREAMING_SNAKE_CASE ( self :Union[str, Any] , snake_case :Tuple , snake_case :Dict ): '''simple docstring''' return torch.where( timesteps == 0 , torch.zeros_like(t.to(timesteps.device ) ) , self.discrete_sigmas[timesteps - 1].to(timesteps.device ) , ) def SCREAMING_SNAKE_CASE ( self :Union[str, Any] , snake_case :Any , snake_case :str , snake_case :Dict , snake_case :Dict = None , snake_case :List[Any] = True , ): '''simple docstring''' if self.timesteps is None: raise ValueError( "`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler" ) A_ : List[str] = timestep * torch.ones( sample.shape[0] , device=sample.device ) # torch.repeat_interleave(timestep, sample.shape[0]) A_ : str = (timestep * (len(self.timesteps ) - 1)).long() # mps requires indices to be in the same device, so we use cpu as is the default with cuda A_ : List[Any] = timesteps.to(self.discrete_sigmas.device ) A_ : str = self.discrete_sigmas[timesteps].to(sample.device ) A_ : List[Any] = self.get_adjacent_sigma(_a , _a ).to(sample.device ) A_ : Union[str, Any] = torch.zeros_like(_a ) A_ : Dict = (sigma**2 - adjacent_sigma**2) ** 0.5 # equation 6 in the paper: the model_output modeled by the network is grad_x log pt(x) # also equation 47 shows the analog from SDE models to ancestral sampling methods A_ : List[Any] = diffusion.flatten() while len(diffusion.shape ) < len(sample.shape ): A_ : List[Any] = diffusion.unsqueeze(-1 ) A_ : Optional[Any] = drift - diffusion**2 * model_output # equation 6: sample noise for the diffusion term of A_ : Any = randn_tensor( sample.shape , layout=sample.layout , generator=_a , device=sample.device , dtype=sample.dtype ) A_ : Optional[Any] = sample - drift # subtract because `dt` is a small negative timestep # TODO is the variable diffusion the correct scaling term for the noise? A_ : Tuple = prev_sample_mean + diffusion * noise # add impact of diffusion field g if not return_dict: return (prev_sample, prev_sample_mean) return SdeVeOutput(prev_sample=_a , prev_sample_mean=_a ) def SCREAMING_SNAKE_CASE ( self :Union[str, Any] , snake_case :Union[str, Any] , snake_case :List[str] , snake_case :List[str] = None , snake_case :Dict = True , ): '''simple docstring''' if self.timesteps is None: raise ValueError( "`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler" ) # For small batch sizes, the paper "suggest replacing norm(z) with sqrt(d), where d is the dim. of z" # sample noise for correction A_ : Tuple = randn_tensor(sample.shape , layout=sample.layout , generator=_a ).to(sample.device ) # compute step size from the model_output, the noise, and the snr A_ : Tuple = torch.norm(model_output.reshape(model_output.shape[0] , -1 ) , dim=-1 ).mean() A_ : Tuple = torch.norm(noise.reshape(noise.shape[0] , -1 ) , dim=-1 ).mean() A_ : int = (self.config.snr * noise_norm / grad_norm) ** 2 * 2 A_ : Dict = step_size * torch.ones(sample.shape[0] ).to(sample.device ) # self.repeat_scalar(step_size, sample.shape[0]) # compute corrected sample: model_output term and noise term A_ : Optional[Any] = step_size.flatten() while len(step_size.shape ) < len(sample.shape ): A_ : int = step_size.unsqueeze(-1 ) A_ : List[Any] = sample + step_size * model_output A_ : Tuple = prev_sample_mean + ((step_size * 2) ** 0.5) * noise if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=_a ) def SCREAMING_SNAKE_CASE ( self :Tuple , snake_case :Union[str, Any] , snake_case :Union[str, Any] , snake_case :Optional[Any] , ): '''simple docstring''' A_ : Tuple = timesteps.to(original_samples.device ) A_ : Optional[int] = self.discrete_sigmas.to(original_samples.device )[timesteps] A_ : Optional[int] = ( noise * sigmas[:, None, None, None] if noise is not None else torch.randn_like(_a ) * sigmas[:, None, None, None] ) A_ : int = noise + original_samples return noisy_samples def __len__( self :Tuple ): '''simple docstring''' return self.config.num_train_timesteps
300
"""simple docstring""" lowercase_ = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] lowercase_ = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] lowercase_ = { 0: "Sunday", 1: "Monday", 2: "Tuesday", 3: "Wednesday", 4: "Thursday", 5: "Friday", 6: "Saturday", } def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : int , lowerCAmelCase__ : int ) -> str: assert len(str(lowerCAmelCase__ ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 12, "month should be between 1 to 12" assert 1 <= day <= 31, "day should be between 1 to 31" # Doomsday algorithm: __a = year // 100 __a = (5 * (century % 4) + 2) % 7 __a = year % 100 __a = centurian % 12 __a = ( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 __a = ( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 400) == 0) else DOOMSDAY_LEAP[month - 1] ) __a = (dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
45
0
'''simple docstring''' def __magic_name__( lowerCamelCase, lowerCamelCase): __lowerCAmelCase = '''''' for word_or_phrase in separated: if not isinstance(lowerCAmelCase__, lowerCAmelCase__): raise Exception('''join() accepts only strings to be joined''') joined += word_or_phrase + separator return joined.strip(lowerCAmelCase__) if __name__ == "__main__": from doctest import testmod testmod()
174
"""simple docstring""" def lowercase ( lowerCAmelCase__ : list ) -> bool: if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise ValueError('''Input series is not valid, valid series - [2, 4, 6]''' ) if len(lowerCAmelCase__ ) == 0: raise ValueError('''Input list must be a non empty list''' ) if len(lowerCAmelCase__ ) == 1: return True __a = series[1] - series[0] for index in range(len(lowerCAmelCase__ ) - 1 ): if series[index + 1] - series[index] != common_diff: return False return True def lowercase ( lowerCAmelCase__ : list ) -> float: if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise ValueError('''Input series is not valid, valid series - [2, 4, 6]''' ) if len(lowerCAmelCase__ ) == 0: raise ValueError('''Input list must be a non empty list''' ) __a = 0 for val in series: answer += val return answer / len(lowerCAmelCase__ ) if __name__ == "__main__": import doctest doctest.testmod()
45
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 ConditionalDetrImageProcessor class __UpperCamelCase ( unittest.TestCase ): """simple docstring""" def __init__( self : Any , _A : Union[str, Any] , _A : Union[str, Any]=7 , _A : int=3 , _A : List[str]=30 , _A : Optional[Any]=400 , _A : List[str]=True , _A : Union[str, Any]=None , _A : Tuple=True , _A : Union[str, Any]=[0.5, 0.5, 0.5] , _A : List[str]=[0.5, 0.5, 0.5] , _A : str=True , _A : Optional[int]=1 / 255 , _A : Optional[int]=True , ): """simple docstring""" __SCREAMING_SNAKE_CASE : int = size if size is not None else {'''shortest_edge''': 18, '''longest_edge''': 1333} __SCREAMING_SNAKE_CASE : Optional[Any] = parent __SCREAMING_SNAKE_CASE : Dict = batch_size __SCREAMING_SNAKE_CASE : Optional[int] = num_channels __SCREAMING_SNAKE_CASE : int = min_resolution __SCREAMING_SNAKE_CASE : Dict = max_resolution __SCREAMING_SNAKE_CASE : Dict = do_resize __SCREAMING_SNAKE_CASE : Tuple = size __SCREAMING_SNAKE_CASE : Union[str, Any] = do_normalize __SCREAMING_SNAKE_CASE : Optional[int] = image_mean __SCREAMING_SNAKE_CASE : str = image_std __SCREAMING_SNAKE_CASE : Optional[Any] = do_rescale __SCREAMING_SNAKE_CASE : Any = rescale_factor __SCREAMING_SNAKE_CASE : Optional[Any] = do_pad def UpperCAmelCase__ ( self : Any ): """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 UpperCAmelCase__ ( self : Dict , _A : Union[str, Any] , _A : Dict=False ): """simple docstring""" if not batched: __SCREAMING_SNAKE_CASE : Union[str, Any] = image_inputs[0] if isinstance(_a , Image.Image ): __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Optional[int] = image.size else: __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Optional[int] = image.shape[1], image.shape[2] if w < h: __SCREAMING_SNAKE_CASE : Any = int(self.size['''shortest_edge'''] * h / w ) __SCREAMING_SNAKE_CASE : Any = self.size['''shortest_edge'''] elif w > h: __SCREAMING_SNAKE_CASE : Dict = self.size['''shortest_edge'''] __SCREAMING_SNAKE_CASE : List[Any] = int(self.size['''shortest_edge'''] * w / h ) else: __SCREAMING_SNAKE_CASE : Tuple = self.size['''shortest_edge'''] __SCREAMING_SNAKE_CASE : List[Any] = self.size['''shortest_edge'''] else: __SCREAMING_SNAKE_CASE : int = [] for image in image_inputs: __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __SCREAMING_SNAKE_CASE : Dict = max(_a , key=lambda _A : item[0] )[0] __SCREAMING_SNAKE_CASE : Optional[int] = max(_a , key=lambda _A : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class __UpperCamelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): """simple docstring""" lowerCAmelCase_ = ConditionalDetrImageProcessor if is_vision_available() else None def UpperCAmelCase__ ( self : int ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[Any] = ConditionalDetrImageProcessingTester(self ) @property def UpperCAmelCase__ ( self : Optional[int] ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase__ ( self : Any ): """simple docstring""" __SCREAMING_SNAKE_CASE : 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] ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[str] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''shortest_edge''': 18, '''longest_edge''': 1333} ) self.assertEqual(image_processor.do_pad , _a ) __SCREAMING_SNAKE_CASE : List[Any] = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=_a ) self.assertEqual(image_processor.size , {'''shortest_edge''': 42, '''longest_edge''': 84} ) self.assertEqual(image_processor.do_pad , _a ) def UpperCAmelCase__ ( self : Tuple ): """simple docstring""" pass def UpperCAmelCase__ ( self : Optional[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __SCREAMING_SNAKE_CASE : Optional[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_a ) for image in image_inputs: self.assertIsInstance(_a , Image.Image ) # Test not batched input __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Dict = self.image_processor_tester.get_expected_values(_a ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : List[str] = self.image_processor_tester.get_expected_values(_a , batched=_a ) __SCREAMING_SNAKE_CASE : str = image_processing(_a , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def UpperCAmelCase__ ( self : Any ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __SCREAMING_SNAKE_CASE : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=_a , numpify=_a ) for image in image_inputs: self.assertIsInstance(_a , np.ndarray ) # Test not batched input __SCREAMING_SNAKE_CASE : List[str] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : str = self.image_processor_tester.get_expected_values(_a ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE : Dict = image_processing(_a , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Tuple = self.image_processor_tester.get_expected_values(_a , batched=_a ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def UpperCAmelCase__ ( self : int ): """simple docstring""" __SCREAMING_SNAKE_CASE : int = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __SCREAMING_SNAKE_CASE : str = prepare_image_inputs(self.image_processor_tester , equal_resolution=_a , torchify=_a ) for image in image_inputs: self.assertIsInstance(_a , torch.Tensor ) # Test not batched input __SCREAMING_SNAKE_CASE : Dict = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : List[str] = self.image_processor_tester.get_expected_values(_a ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE : List[str] = image_processing(_a , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Tuple = self.image_processor_tester.get_expected_values(_a , batched=_a ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def UpperCAmelCase__ ( self : int ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_annotations.txt''' , '''r''' ) as f: __SCREAMING_SNAKE_CASE : List[str] = json.loads(f.read() ) __SCREAMING_SNAKE_CASE : Union[str, Any] = {'''image_id''': 3_9769, '''annotations''': target} # encode them __SCREAMING_SNAKE_CASE : List[str] = ConditionalDetrImageProcessor.from_pretrained('''microsoft/conditional-detr-resnet-50''' ) __SCREAMING_SNAKE_CASE : Optional[int] = image_processing(images=_a , annotations=_a , return_tensors='''pt''' ) # verify pixel values __SCREAMING_SNAKE_CASE : List[Any] = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding['''pixel_values'''].shape , _a ) __SCREAMING_SNAKE_CASE : Any = torch.tensor([0.27_96, 0.31_38, 0.34_81] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _a , atol=1e-4 ) ) # verify area __SCREAMING_SNAKE_CASE : Any = torch.tensor([58_87.96_00, 1_1250.2061, 48_9353.8438, 83_7122.7500, 14_7967.5156, 16_5732.3438] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _a ) ) # verify boxes __SCREAMING_SNAKE_CASE : List[Any] = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _a ) __SCREAMING_SNAKE_CASE : Any = torch.tensor([0.55_03, 0.27_65, 0.06_04, 0.22_15] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _a , atol=1e-3 ) ) # verify image_id __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([3_9769] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _a ) ) # verify is_crowd __SCREAMING_SNAKE_CASE : Dict = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _a ) ) # verify class_labels __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _a ) ) # verify orig_size __SCREAMING_SNAKE_CASE : Tuple = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _a ) ) # verify size __SCREAMING_SNAKE_CASE : Any = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _a ) ) @slow def UpperCAmelCase__ ( self : Union[str, Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt''' , '''r''' ) as f: __SCREAMING_SNAKE_CASE : Any = json.loads(f.read() ) __SCREAMING_SNAKE_CASE : int = {'''file_name''': '''000000039769.png''', '''image_id''': 3_9769, '''segments_info''': target} __SCREAMING_SNAKE_CASE : List[str] = pathlib.Path('''./tests/fixtures/tests_samples/COCO/coco_panoptic''' ) # encode them __SCREAMING_SNAKE_CASE : Optional[Any] = ConditionalDetrImageProcessor(format='''coco_panoptic''' ) __SCREAMING_SNAKE_CASE : Tuple = image_processing(images=_a , annotations=_a , masks_path=_a , return_tensors='''pt''' ) # verify pixel values __SCREAMING_SNAKE_CASE : int = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding['''pixel_values'''].shape , _a ) __SCREAMING_SNAKE_CASE : int = torch.tensor([0.27_96, 0.31_38, 0.34_81] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _a , atol=1e-4 ) ) # verify area __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([14_7979.6875, 16_5527.0469, 48_4638.5938, 1_1292.9375, 58_79.65_62, 76_34.11_47] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _a ) ) # verify boxes __SCREAMING_SNAKE_CASE : Any = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _a ) __SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([0.26_25, 0.54_37, 0.46_88, 0.86_25] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _a , atol=1e-3 ) ) # verify image_id __SCREAMING_SNAKE_CASE : Any = torch.tensor([3_9769] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _a ) ) # verify is_crowd __SCREAMING_SNAKE_CASE : Any = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _a ) ) # verify class_labels __SCREAMING_SNAKE_CASE : Any = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _a ) ) # verify masks __SCREAMING_SNAKE_CASE : List[Any] = 82_2873 self.assertEqual(encoding['''labels'''][0]['''masks'''].sum().item() , _a ) # verify orig_size __SCREAMING_SNAKE_CASE : int = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _a ) ) # verify size __SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _a ) )
303
"""simple docstring""" from argparse import ArgumentParser, Namespace from ..utils import logging from . import BaseTransformersCLICommand def lowercase ( lowerCAmelCase__ : Namespace ) -> Tuple: return ConvertCommand( args.model_type , args.tf_checkpoint , args.pytorch_dump_output , args.config , args.finetuning_task_name ) lowercase_ = "\ntransformers can only be used from the commandline to convert TensorFlow models in PyTorch, In that case, it requires\nTensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installation instructions.\n" class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' @staticmethod def __UpperCAmelCase ( _a ): __a = parser.add_parser( '''convert''' , help='''CLI tool to run convert model from original author checkpoints to Transformers PyTorch checkpoints.''' , ) train_parser.add_argument('''--model_type''' , type=_a , required=_a , help='''Model\'s type.''' ) train_parser.add_argument( '''--tf_checkpoint''' , type=_a , required=_a , help='''TensorFlow checkpoint path or folder.''' ) train_parser.add_argument( '''--pytorch_dump_output''' , type=_a , required=_a , help='''Path to the PyTorch saved model output.''' ) train_parser.add_argument('''--config''' , type=_a , default='''''' , help='''Configuration file path or folder.''' ) train_parser.add_argument( '''--finetuning_task_name''' , type=_a , default=_a , help='''Optional fine-tuning task name if the TF model was a finetuned model.''' , ) train_parser.set_defaults(func=_a ) def __init__( self , _a , _a , _a , _a , _a , *_a , ): __a = logging.get_logger('''transformers-cli/converting''' ) self._logger.info(f'''Loading model {model_type}''' ) __a = model_type __a = tf_checkpoint __a = pytorch_dump_output __a = config __a = finetuning_task_name def __UpperCAmelCase ( self ): if self._model_type == "albert": try: from ..models.albert.convert_albert_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "bert": try: from ..models.bert.convert_bert_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "funnel": try: from ..models.funnel.convert_funnel_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "t5": try: from ..models.ta.convert_ta_original_tf_checkpoint_to_pytorch import convert_tf_checkpoint_to_pytorch except ImportError: raise ImportError(_a ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "gpt": from ..models.openai.convert_openai_original_tf_checkpoint_to_pytorch import ( convert_openai_checkpoint_to_pytorch, ) convert_openai_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "transfo_xl": try: from ..models.transfo_xl.convert_transfo_xl_original_tf_checkpoint_to_pytorch import ( convert_transfo_xl_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) if "ckpt" in self._tf_checkpoint.lower(): __a = self._tf_checkpoint __a = '''''' else: __a = self._tf_checkpoint __a = '''''' convert_transfo_xl_checkpoint_to_pytorch( _a , self._config , self._pytorch_dump_output , _a ) elif self._model_type == "gpt2": try: from ..models.gpta.convert_gpta_original_tf_checkpoint_to_pytorch import ( convert_gpta_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_gpta_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "xlnet": try: from ..models.xlnet.convert_xlnet_original_tf_checkpoint_to_pytorch import ( convert_xlnet_checkpoint_to_pytorch, ) except ImportError: raise ImportError(_a ) convert_xlnet_checkpoint_to_pytorch( self._tf_checkpoint , self._config , self._pytorch_dump_output , self._finetuning_task_name ) elif self._model_type == "xlm": from ..models.xlm.convert_xlm_original_pytorch_checkpoint_to_pytorch import ( convert_xlm_checkpoint_to_pytorch, ) convert_xlm_checkpoint_to_pytorch(self._tf_checkpoint , self._pytorch_dump_output ) elif self._model_type == "lxmert": from ..models.lxmert.convert_lxmert_original_tf_checkpoint_to_pytorch import ( convert_lxmert_checkpoint_to_pytorch, ) convert_lxmert_checkpoint_to_pytorch(self._tf_checkpoint , self._pytorch_dump_output ) elif self._model_type == "rembert": from ..models.rembert.convert_rembert_tf_checkpoint_to_pytorch import ( convert_rembert_tf_checkpoint_to_pytorch, ) convert_rembert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) else: raise ValueError( '''--model_type should be selected in the list [bert, gpt, gpt2, t5, transfo_xl, xlnet, xlm, lxmert]''' )
45
0
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class UpperCAmelCase_ ( unittest.TestCase): def __init__( self : List[str] , __UpperCamelCase : List[str] , __UpperCamelCase : Any=7 , __UpperCamelCase : Optional[Any]=3 , __UpperCamelCase : List[Any]=18 , __UpperCamelCase : Dict=30 , __UpperCamelCase : List[str]=400 , __UpperCamelCase : Optional[int]=True , __UpperCamelCase : int=None , __UpperCamelCase : List[str]=True , ) -> str: _UpperCamelCase = size if size is not None else {'''height''': 18, '''width''': 18} _UpperCamelCase = parent _UpperCamelCase = batch_size _UpperCamelCase = num_channels _UpperCamelCase = image_size _UpperCamelCase = min_resolution _UpperCamelCase = max_resolution _UpperCamelCase = do_resize _UpperCamelCase = size _UpperCamelCase = apply_ocr def _UpperCamelCase ( self : Dict ) -> Optional[int]: return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class UpperCAmelCase_ ( __SCREAMING_SNAKE_CASE , unittest.TestCase): snake_case__ = LayoutLMvaImageProcessor if is_pytesseract_available() else None def _UpperCamelCase ( self : Optional[int] ) -> Union[str, Any]: _UpperCamelCase = LayoutLMvaImageProcessingTester(self ) @property def _UpperCamelCase ( self : Optional[Any] ) -> Optional[Any]: return self.image_processor_tester.prepare_image_processor_dict() def _UpperCamelCase ( self : Optional[int] ) -> Dict: _UpperCamelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_a , '''do_resize''' ) ) self.assertTrue(hasattr(_a , '''size''' ) ) self.assertTrue(hasattr(_a , '''apply_ocr''' ) ) def _UpperCamelCase ( self : Optional[int] ) -> Tuple: _UpperCamelCase = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''height''': 18, '''width''': 18} ) _UpperCamelCase = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {'''height''': 42, '''width''': 42} ) def _UpperCamelCase ( self : Union[str, Any] ) -> Any: pass def _UpperCamelCase ( self : Dict ) -> str: # Initialize image_processing _UpperCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _UpperCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=_a ) for image in image_inputs: self.assertIsInstance(_a , Image.Image ) # Test not batched input _UpperCamelCase = image_processing(image_inputs[0] , return_tensors='''pt''' ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) self.assertIsInstance(encoding.words , _a ) self.assertIsInstance(encoding.boxes , _a ) # Test batched _UpperCamelCase = image_processing(_a , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) def _UpperCamelCase ( self : List[Any] ) -> int: # Initialize image_processing _UpperCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _UpperCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=_a , numpify=_a ) for image in image_inputs: self.assertIsInstance(_a , np.ndarray ) # Test not batched input _UpperCamelCase = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) # Test batched _UpperCamelCase = image_processing(_a , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) def _UpperCamelCase ( self : Optional[int] ) -> List[str]: # Initialize image_processing _UpperCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _UpperCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=_a , torchify=_a ) for image in image_inputs: self.assertIsInstance(_a , torch.Tensor ) # Test not batched input _UpperCamelCase = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) # Test batched _UpperCamelCase = image_processing(_a , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) def _UpperCamelCase ( self : Optional[Any] ) -> Tuple: # with apply_OCR = True _UpperCamelCase = LayoutLMvaImageProcessor() from datasets import load_dataset _UpperCamelCase = load_dataset('''hf-internal-testing/fixtures_docvqa''' , split='''test''' ) _UpperCamelCase = Image.open(ds[0]['''file'''] ).convert('''RGB''' ) _UpperCamelCase = image_processing(_a , return_tensors='''pt''' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 _UpperCamelCase = [['''11:14''', '''to''', '''11:39''', '''a.m''', '''11:39''', '''to''', '''11:44''', '''a.m.''', '''11:44''', '''a.m.''', '''to''', '''12:25''', '''p.m.''', '''12:25''', '''to''', '''12:58''', '''p.m.''', '''12:58''', '''to''', '''4:00''', '''p.m.''', '''2:00''', '''to''', '''5:00''', '''p.m.''', '''Coffee''', '''Break''', '''Coffee''', '''will''', '''be''', '''served''', '''for''', '''men''', '''and''', '''women''', '''in''', '''the''', '''lobby''', '''adjacent''', '''to''', '''exhibit''', '''area.''', '''Please''', '''move''', '''into''', '''exhibit''', '''area.''', '''(Exhibits''', '''Open)''', '''TRRF''', '''GENERAL''', '''SESSION''', '''(PART''', '''|)''', '''Presiding:''', '''Lee''', '''A.''', '''Waller''', '''TRRF''', '''Vice''', '''President''', '''“Introductory''', '''Remarks”''', '''Lee''', '''A.''', '''Waller,''', '''TRRF''', '''Vice''', '''Presi-''', '''dent''', '''Individual''', '''Interviews''', '''with''', '''TRRF''', '''Public''', '''Board''', '''Members''', '''and''', '''Sci-''', '''entific''', '''Advisory''', '''Council''', '''Mem-''', '''bers''', '''Conducted''', '''by''', '''TRRF''', '''Treasurer''', '''Philip''', '''G.''', '''Kuehn''', '''to''', '''get''', '''answers''', '''which''', '''the''', '''public''', '''refrigerated''', '''warehousing''', '''industry''', '''is''', '''looking''', '''for.''', '''Plus''', '''questions''', '''from''', '''the''', '''floor.''', '''Dr.''', '''Emil''', '''M.''', '''Mrak,''', '''University''', '''of''', '''Cal-''', '''ifornia,''', '''Chairman,''', '''TRRF''', '''Board;''', '''Sam''', '''R.''', '''Cecil,''', '''University''', '''of''', '''Georgia''', '''College''', '''of''', '''Agriculture;''', '''Dr.''', '''Stanley''', '''Charm,''', '''Tufts''', '''University''', '''School''', '''of''', '''Medicine;''', '''Dr.''', '''Robert''', '''H.''', '''Cotton,''', '''ITT''', '''Continental''', '''Baking''', '''Company;''', '''Dr.''', '''Owen''', '''Fennema,''', '''University''', '''of''', '''Wis-''', '''consin;''', '''Dr.''', '''Robert''', '''E.''', '''Hardenburg,''', '''USDA.''', '''Questions''', '''and''', '''Answers''', '''Exhibits''', '''Open''', '''Capt.''', '''Jack''', '''Stoney''', '''Room''', '''TRRF''', '''Scientific''', '''Advisory''', '''Council''', '''Meeting''', '''Ballroom''', '''Foyer''']] # noqa: E231 _UpperCamelCase = [[[141, 57, 214, 69], [228, 58, 252, 69], [141, 75, 216, 88], [230, 79, 280, 88], [142, 260, 218, 273], [230, 261, 255, 273], [143, 279, 218, 290], [231, 282, 290, 291], [143, 342, 218, 354], [231, 345, 289, 355], [202, 362, 227, 373], [143, 379, 220, 392], [231, 382, 291, 394], [144, 714, 220, 726], [231, 715, 256, 726], [144, 732, 220, 745], [232, 736, 291, 747], [144, 769, 218, 782], [231, 770, 256, 782], [141, 788, 202, 801], [215, 791, 274, 804], [143, 826, 204, 838], [215, 826, 240, 838], [142, 844, 202, 857], [215, 847, 274, 859], [334, 57, 427, 69], [440, 57, 522, 69], [369, 75, 461, 88], [469, 75, 516, 88], [528, 76, 562, 88], [570, 76, 667, 88], [675, 75, 711, 87], [721, 79, 778, 88], [789, 75, 840, 88], [369, 97, 470, 107], [484, 94, 507, 106], [518, 94, 562, 107], [576, 94, 655, 110], [668, 94, 792, 109], [804, 95, 829, 107], [369, 113, 465, 125], [477, 116, 547, 125], [562, 113, 658, 125], [671, 116, 748, 125], [761, 113, 811, 125], [369, 131, 465, 143], [477, 133, 548, 143], [563, 130, 698, 145], [710, 130, 802, 146], [336, 171, 412, 183], [423, 171, 572, 183], [582, 170, 716, 184], [728, 171, 817, 187], [829, 171, 844, 186], [338, 197, 482, 212], [507, 196, 557, 209], [569, 196, 595, 208], [610, 196, 702, 209], [505, 214, 583, 226], [595, 214, 656, 227], [670, 215, 807, 227], [335, 259, 543, 274], [556, 259, 708, 272], [372, 279, 422, 291], [435, 279, 460, 291], [474, 279, 574, 292], [587, 278, 664, 291], [676, 278, 738, 291], [751, 279, 834, 291], [372, 298, 434, 310], [335, 341, 483, 354], [497, 341, 655, 354], [667, 341, 728, 354], [740, 341, 825, 354], [335, 360, 430, 372], [442, 360, 534, 372], [545, 359, 687, 372], [697, 360, 754, 372], [765, 360, 823, 373], [334, 378, 428, 391], [440, 378, 577, 394], [590, 378, 705, 391], [720, 378, 801, 391], [334, 397, 400, 409], [370, 416, 529, 429], [544, 416, 576, 432], [587, 416, 665, 428], [677, 416, 814, 429], [372, 435, 452, 450], [465, 434, 495, 447], [511, 434, 600, 447], [611, 436, 637, 447], [649, 436, 694, 451], [705, 438, 824, 447], [369, 453, 452, 466], [464, 454, 509, 466], [522, 453, 611, 469], [625, 453, 792, 469], [370, 472, 556, 488], [570, 472, 684, 487], [697, 472, 718, 485], [732, 472, 835, 488], [369, 490, 411, 503], [425, 490, 484, 503], [496, 490, 635, 506], [645, 490, 707, 503], [718, 491, 761, 503], [771, 490, 840, 503], [336, 510, 374, 521], [388, 510, 447, 522], [460, 510, 489, 521], [503, 510, 580, 522], [592, 509, 736, 525], [745, 509, 770, 522], [781, 509, 840, 522], [338, 528, 434, 541], [448, 528, 596, 541], [609, 527, 687, 540], [700, 528, 792, 541], [336, 546, 397, 559], [407, 546, 431, 559], [443, 546, 525, 560], [537, 546, 680, 562], [688, 546, 714, 559], [722, 546, 837, 562], [336, 565, 449, 581], [461, 565, 485, 577], [497, 565, 665, 581], [681, 565, 718, 577], [732, 565, 837, 580], [337, 584, 438, 597], [452, 583, 521, 596], [535, 584, 677, 599], [690, 583, 787, 596], [801, 583, 825, 596], [338, 602, 478, 615], [492, 602, 530, 614], [543, 602, 638, 615], [650, 602, 676, 614], [688, 602, 788, 615], [802, 602, 843, 614], [337, 621, 502, 633], [516, 621, 615, 637], [629, 621, 774, 636], [789, 621, 827, 633], [337, 639, 418, 652], [432, 640, 571, 653], [587, 639, 731, 655], [743, 639, 769, 652], [780, 639, 841, 652], [338, 658, 440, 673], [455, 658, 491, 670], [508, 658, 602, 671], [616, 658, 638, 670], [654, 658, 835, 674], [337, 677, 429, 689], [337, 714, 482, 726], [495, 714, 548, 726], [561, 714, 683, 726], [338, 770, 461, 782], [474, 769, 554, 785], [489, 788, 562, 803], [576, 788, 643, 801], [656, 787, 751, 804], [764, 788, 844, 801], [334, 825, 421, 838], [430, 824, 574, 838], [584, 824, 723, 841], [335, 844, 450, 857], [464, 843, 583, 860], [628, 862, 755, 875], [769, 861, 848, 878]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , _a ) self.assertListEqual(encoding.boxes , _a ) # with apply_OCR = False _UpperCamelCase = LayoutLMvaImageProcessor(apply_ocr=_a ) _UpperCamelCase = image_processing(_a , return_tensors='''pt''' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) )
256
"""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 lowercase_ = logging.get_logger(__name__) lowercase_ = { "microsoft/beit-base-patch16-224-pt22k": ( "https://huggingface.co/microsoft/beit-base-patch16-224-pt22k/resolve/main/config.json" ), # See all BEiT models at https://huggingface.co/models?filter=beit } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : List[str] = 'beit' def __init__( self , _a=8_192 , _a=768 , _a=12 , _a=12 , _a=3_072 , _a="gelu" , _a=0.0 , _a=0.0 , _a=0.02 , _a=1E-12 , _a=224 , _a=16 , _a=3 , _a=False , _a=False , _a=False , _a=False , _a=0.1 , _a=0.1 , _a=True , _a=[3, 5, 7, 11] , _a=[1, 2, 3, 6] , _a=True , _a=0.4 , _a=256 , _a=1 , _a=False , _a=255 , **_a , ): super().__init__(**_a ) __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 = initializer_range __a = layer_norm_eps __a = image_size __a = patch_size __a = num_channels __a = use_mask_token __a = use_absolute_position_embeddings __a = use_relative_position_bias __a = use_shared_relative_position_bias __a = layer_scale_init_value __a = drop_path_rate __a = use_mean_pooling # decode head attributes (semantic segmentation) __a = out_indices __a = pool_scales # auxiliary head attributes (semantic segmentation) __a = use_auxiliary_head __a = auxiliary_loss_weight __a = auxiliary_channels __a = auxiliary_num_convs __a = auxiliary_concat_input __a = semantic_loss_ignore_index class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : List[Any] = version.parse('1.11' ) @property def __UpperCAmelCase ( self ): return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def __UpperCAmelCase ( self ): return 1E-4
45
0
"""simple docstring""" from __future__ import annotations def _lowerCamelCase( a , a ): __a = get_failure_array(lowerCAmelCase__ ) # 2) Step through text searching for pattern __a , __a = 0, 0 # index into text, pattern while i < len(lowerCAmelCase__ ): if pattern[j] == text[i]: if j == (len(lowerCAmelCase__ ) - 1): return True j += 1 # if this is a prefix in our pattern # just go back far enough to continue elif j > 0: __a = failure[j - 1] continue i += 1 return False def _lowerCamelCase( a ): __a = [0] __a = 0 __a = 1 while j < len(lowerCAmelCase__ ): if pattern[i] == pattern[j]: i += 1 elif i > 0: __a = failure[i - 1] continue j += 1 failure.append(lowerCAmelCase__ ) return failure if __name__ == "__main__": # Test 1) SCREAMING_SNAKE_CASE__:Optional[int] = """abc1abc12""" SCREAMING_SNAKE_CASE__:Union[str, Any] = """alskfjaldsabc1abc1abc12k23adsfabcabc""" SCREAMING_SNAKE_CASE__:int = """alskfjaldsk23adsfabcabc""" assert kmp(pattern, texta) and not kmp(pattern, texta) # Test 2) SCREAMING_SNAKE_CASE__:Any = """ABABX""" SCREAMING_SNAKE_CASE__:Any = """ABABZABABYABABX""" assert kmp(pattern, text) # Test 3) SCREAMING_SNAKE_CASE__:Optional[int] = """AAAB""" SCREAMING_SNAKE_CASE__:Tuple = """ABAAAAAB""" assert kmp(pattern, text) # Test 4) SCREAMING_SNAKE_CASE__:Optional[int] = """abcdabcy""" SCREAMING_SNAKE_CASE__:Dict = """abcxabcdabxabcdabcdabcy""" assert kmp(pattern, text) # Test 5) SCREAMING_SNAKE_CASE__:Optional[Any] = """aabaabaaa""" assert get_failure_array(pattern) == [0, 1, 0, 1, 2, 3, 4, 5, 2]
261
"""simple docstring""" def lowercase ( lowerCAmelCase__ : str ) -> list: if n_term == "": return [] __a = [] for temp in range(int(lowerCAmelCase__ ) ): series.append(f'''1/{temp + 1}''' if series else '''1''' ) return series if __name__ == "__main__": lowercase_ = input("Enter the last number (nth term) of the Harmonic Series") print("Formula of Harmonic Series => 1+1/2+1/3 ..... 1/n") print(harmonic_series(nth_term))
45
0
"""simple docstring""" import math import os import sys def _UpperCAmelCase ( __lowerCamelCase : str ) -> str: _snake_case = '''''' try: with open(lowerCAmelCase__ , '''rb''' ) as binary_file: _snake_case = binary_file.read() for dat in data: _snake_case = f'''{dat:08b}''' result += curr_byte return result except OSError: print('''File not accessible''' ) sys.exit() def _UpperCAmelCase ( __lowerCamelCase : dict[str, str] , __lowerCamelCase : str , __lowerCamelCase : int , __lowerCamelCase : str ) -> None: lexicon.pop(lowerCAmelCase__ ) _snake_case = last_match_id if math.loga(lowerCAmelCase__ ).is_integer(): for curr_key in lexicon: _snake_case = '''0''' + lexicon[curr_key] _snake_case = bin(lowerCAmelCase__ )[2:] def _UpperCAmelCase ( __lowerCamelCase : str ) -> str: _snake_case = {'''0''': '''0''', '''1''': '''1'''} _snake_case , _snake_case = '''''', '''''' _snake_case = len(lowerCAmelCase__ ) for i in range(len(lowerCAmelCase__ ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue _snake_case = lexicon[curr_string] result += last_match_id add_key_to_lexicon(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) index += 1 _snake_case = '''''' while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": _snake_case = lexicon[curr_string] result += last_match_id return result def _UpperCAmelCase ( __lowerCamelCase : str , __lowerCamelCase : str ) -> str: _snake_case = os.path.getsize(lowerCAmelCase__ ) _snake_case = bin(lowerCAmelCase__ )[2:] _snake_case = len(lowerCAmelCase__ ) return "0" * (length_length - 1) + file_length_binary + compressed def _UpperCAmelCase ( __lowerCamelCase : str , __lowerCamelCase : str ) -> None: _snake_case = 8 try: with open(lowerCAmelCase__ , '''wb''' ) as opened_file: _snake_case = [ to_write[i : i + byte_length] for i in range(0 , len(lowerCAmelCase__ ) , lowerCAmelCase__ ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append('''10000000''' ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array: opened_file.write(int(lowerCAmelCase__ , 2 ).to_bytes(1 , byteorder='''big''' ) ) except OSError: print('''File not accessible''' ) sys.exit() def _UpperCAmelCase ( __lowerCamelCase : str , __lowerCamelCase : str ) -> None: _snake_case = read_file_binary(lowerCAmelCase__ ) _snake_case = compress_data(lowerCAmelCase__ ) _snake_case = add_file_length(lowerCAmelCase__ , lowerCAmelCase__ ) write_file_binary(lowerCAmelCase__ , lowerCAmelCase__ ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
288
"""simple docstring""" from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import pyarrow as pa if TYPE_CHECKING: from .features import FeatureType @dataclass class __lowerCAmelCase : '''simple docstring''' __UpperCAmelCase : List[str] __UpperCAmelCase : Optional[str] = None # Automatically constructed __UpperCAmelCase : ClassVar[str] = "dict" __UpperCAmelCase : ClassVar[Any] = None __UpperCAmelCase : str = field(default='Translation' , init=__SCREAMING_SNAKE_CASE , repr=__SCREAMING_SNAKE_CASE ) def __call__( self ): return pa.struct({lang: pa.string() for lang in sorted(self.languages )} ) def __UpperCAmelCase ( self ): from .features import Value return {k: Value('''string''' ) for k in sorted(self.languages )} @dataclass class __lowerCAmelCase : '''simple docstring''' __UpperCAmelCase : Optional[List] = None __UpperCAmelCase : Optional[int] = None __UpperCAmelCase : Optional[str] = None # Automatically constructed __UpperCAmelCase : ClassVar[str] = "dict" __UpperCAmelCase : ClassVar[Any] = None __UpperCAmelCase : str = field(default='TranslationVariableLanguages' , init=__SCREAMING_SNAKE_CASE , repr=__SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self ): __a = sorted(set(self.languages ) ) if self.languages else None __a = len(self.languages ) if self.languages else None def __call__( self ): return pa.struct({'''language''': pa.list_(pa.string() ), '''translation''': pa.list_(pa.string() )} ) def __UpperCAmelCase ( self , _a ): __a = set(self.languages ) if self.languages and set(_a ) - lang_set: raise ValueError( f'''Some languages in example ({', '.join(sorted(set(_a ) - lang_set ) )}) are not in valid set ({', '.join(_a )}).''' ) # Convert dictionary into tuples, splitting out cases where there are # multiple translations for a single language. __a = [] for lang, text in translation_dict.items(): if isinstance(_a , _a ): translation_tuples.append((lang, text) ) else: translation_tuples.extend([(lang, el) for el in text] ) # Ensure translations are in ascending order by language code. __a , __a = zip(*sorted(_a ) ) return {"language": languages, "translation": translations} def __UpperCAmelCase ( self ): from .features import Sequence, Value return { "language": Sequence(Value('''string''' ) ), "translation": Sequence(Value('''string''' ) ), }
45
0
import unittest from accelerate import debug_launcher from accelerate.test_utils import require_cpu, test_ops, test_script @require_cpu class a__ ( unittest.TestCase ): """simple docstring""" def UpperCamelCase ( self ) -> Optional[Any]: '''simple docstring''' debug_launcher(test_script.main ) def UpperCamelCase ( self ) -> Any: '''simple docstring''' debug_launcher(test_ops.main )
68
"""simple docstring""" def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list ) -> List[Any]: _enforce_args(lowerCAmelCase__ , lowerCAmelCase__ ) if n == 0: return 0 __a = float('''-inf''' ) for i in range(1 , n + 1 ): __a = max( lowerCAmelCase__ , prices[i - 1] + naive_cut_rod_recursive(n - i , lowerCAmelCase__ ) ) return max_revue def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list ) -> List[str]: _enforce_args(lowerCAmelCase__ , lowerCAmelCase__ ) __a = [float('''-inf''' ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list , lowerCAmelCase__ : list ) -> Union[str, Any]: if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: __a = float('''-inf''' ) for i in range(1 , n + 1 ): __a = max( lowerCAmelCase__ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , lowerCAmelCase__ , lowerCAmelCase__ ) , ) __a = max_revenue return max_rev[n] def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list ) -> Dict: _enforce_args(lowerCAmelCase__ , lowerCAmelCase__ ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. __a = [float('''-inf''' ) for _ in range(n + 1 )] __a = 0 for i in range(1 , n + 1 ): __a = max_rev[i] for j in range(1 , i + 1 ): __a = max(lowerCAmelCase__ , prices[j - 1] + max_rev[i - j] ) __a = max_revenue_i return max_rev[n] def lowercase ( lowerCAmelCase__ : int , lowerCAmelCase__ : list ) -> str: if n < 0: __a = f'''n must be greater than or equal to 0. Got n = {n}''' raise ValueError(lowerCAmelCase__ ) if n > len(lowerCAmelCase__ ): __a = ( '''Each integral piece of rod must have a corresponding price. ''' f'''Got n = {n} but length of prices = {len(lowerCAmelCase__ )}''' ) raise ValueError(lowerCAmelCase__ ) def lowercase ( ) -> int: __a = [6, 10, 12, 15, 20, 23] __a = len(lowerCAmelCase__ ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. __a = 36 __a = top_down_cut_rod(lowerCAmelCase__ , lowerCAmelCase__ ) __a = bottom_up_cut_rod(lowerCAmelCase__ , lowerCAmelCase__ ) __a = naive_cut_rod_recursive(lowerCAmelCase__ , lowerCAmelCase__ ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
45
0
import warnings from ..trainer import Trainer from ..utils import logging lowerCAmelCase__ :Optional[int] = logging.get_logger(__name__) class __a ( __SCREAMING_SNAKE_CASE ): def __init__( self , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" warnings.warn( '`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` ' 'instead.' , _a , ) super().__init__(args=_a , **_a )
329
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) lowercase_ = {"configuration_unispeech": ["UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP", "UniSpeechConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST", "UniSpeechForCTC", "UniSpeechForPreTraining", "UniSpeechForSequenceClassification", "UniSpeechModel", "UniSpeechPreTrainedModel", ] if TYPE_CHECKING: from .configuration_unispeech import UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_unispeech import ( UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST, UniSpeechForCTC, UniSpeechForPreTraining, UniSpeechForSequenceClassification, UniSpeechModel, UniSpeechPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
45
0
'''simple docstring''' def __UpperCAmelCase ( a_: str ): _UpperCAmelCase : Optional[int] = [0 for i in range(len(lowerCAmelCase__ ) )] # initialize interval's left pointer and right pointer _UpperCAmelCase , _UpperCAmelCase : Union[str, Any] = 0, 0 for i in range(1, len(lowerCAmelCase__ ) ): # case when current index is inside the interval if i <= right_pointer: _UpperCAmelCase : Any = min(right_pointer - i + 1, z_result[i - left_pointer] ) _UpperCAmelCase : Dict = min_edge while go_next(lowerCAmelCase__, lowerCAmelCase__, lowerCAmelCase__ ): z_result[i] += 1 # if new index's result gives us more right interval, # we've to update left_pointer and right_pointer if i + z_result[i] - 1 > right_pointer: _UpperCAmelCase , _UpperCAmelCase : Union[str, Any] = i, i + z_result[i] - 1 return z_result def __UpperCAmelCase ( a_: int, a_: list[int], a_: str ): return i + z_result[i] < len(lowerCAmelCase__ ) and s[z_result[i]] == s[i + z_result[i]] def __UpperCAmelCase ( a_: str, a_: str ): _UpperCAmelCase : int = 0 # concatenate 'pattern' and 'input_str' and call z_function # with concatenated string _UpperCAmelCase : str = z_function(pattern + input_str ) for val in z_result: # if value is greater then length of the pattern string # that means this index is starting position of substring # which is equal to pattern string if val >= len(lowerCAmelCase__ ): answer += 1 return answer if __name__ == "__main__": import doctest doctest.testmod()
145
"""simple docstring""" import unittest import torch from torch import nn from diffusers.models.activations import get_activation class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = get_activation('''swish''' ) self.assertIsInstance(_a , nn.SiLU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def __UpperCAmelCase ( self ): __a = get_activation('''silu''' ) self.assertIsInstance(_a , nn.SiLU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def __UpperCAmelCase ( self ): __a = get_activation('''mish''' ) self.assertIsInstance(_a , nn.Mish ) self.assertEqual(act(torch.tensor(-200 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def __UpperCAmelCase ( self ): __a = get_activation('''gelu''' ) self.assertIsInstance(_a , nn.GELU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 )
45
0