code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
"""simple docstring""" import warnings from ...utils import logging from .image_processing_deformable_detr import DeformableDetrImageProcessor lowercase__ : str = logging.get_logger(__name__) class UpperCamelCase__ ( lowercase_ ): """simple docstring""" def __init__( self : Tuple , *SCREAMING_SNAKE_CASE_ : Dict , **SCREAMING_SNAKE_CASE_ : Union[str, Any] ): warnings.warn( 'The class DeformableDetrFeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use DeformableDetrImageProcessor instead.' , SCREAMING_SNAKE_CASE_ , ) super().__init__(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
224
"""simple docstring""" import warnings from diffusers import StableDiffusionImgaImgPipeline # noqa F401 warnings.warn( """The `image_to_image.py` script is outdated. Please use directly `from diffusers import""" """ StableDiffusionImg2ImgPipeline` instead.""" )
224
1
'''simple docstring''' import json import os from pathlib import Path import pytest from datasets.download.download_config import DownloadConfig from datasets.download.download_manager import DownloadManager from datasets.utils.file_utils import hash_url_to_filename _a : List[Any] = """http://www.mocksite.com/file1.txt""" _a : Any = """\"text\": [\"foo\", \"foo\"]""" _a : int = """6d8ce9aa78a471c7477201efbeabd3bb01ac2e7d100a6dc024ba1608361f90a8""" class _UpperCAmelCase : a : int =2_00 a : Tuple ={"""Content-Length""": """100"""} a : Optional[Any] ={} def lowerCamelCase__ ( self,**__SCREAMING_SNAKE_CASE ): '''simple docstring''' return [bytes(__SCREAMING_SNAKE_CASE,"""utf-8""" )] def _lowerCAmelCase ( *lowercase , **lowercase ) -> Dict: return MockResponse() @pytest.mark.parametrize("""urls_type""" , [str, list, dict] ) def _lowerCAmelCase ( lowercase , lowercase , lowercase ) -> List[str]: import requests monkeypatch.setattr(lowercase , """request""" , lowercase ) __lowerCAmelCase = URL if issubclass(lowercase , lowercase ): __lowerCAmelCase = url elif issubclass(lowercase , lowercase ): __lowerCAmelCase = [url] elif issubclass(lowercase , lowercase ): __lowerCAmelCase = {"""train""": url} __lowerCAmelCase = """dummy""" __lowerCAmelCase = """downloads""" __lowerCAmelCase = tmp_path __lowerCAmelCase = DownloadConfig( cache_dir=os.path.join(lowercase , lowercase ) , use_etag=lowercase , ) __lowerCAmelCase = DownloadManager(dataset_name=lowercase , download_config=lowercase ) __lowerCAmelCase = dl_manager.download(lowercase ) __lowerCAmelCase = urls for downloaded_paths in [downloaded_paths]: if isinstance(lowercase , lowercase ): __lowerCAmelCase = [downloaded_paths] __lowerCAmelCase = [urls] elif isinstance(lowercase , lowercase ): assert "train" in downloaded_paths.keys() __lowerCAmelCase = downloaded_paths.values() __lowerCAmelCase = urls.values() assert downloaded_paths for downloaded_path, input_url in zip(lowercase , lowercase ): assert downloaded_path == dl_manager.downloaded_paths[input_url] __lowerCAmelCase = Path(lowercase ) __lowerCAmelCase = downloaded_path.parts assert parts[-1] == HASH assert parts[-2] == cache_subdir assert downloaded_path.exists() __lowerCAmelCase = downloaded_path.read_text() assert content == CONTENT __lowerCAmelCase = downloaded_path.with_suffix(""".json""" ) assert metadata_downloaded_path.exists() __lowerCAmelCase = json.loads(metadata_downloaded_path.read_text() ) assert metadata_content == {"url": URL, "etag": None} @pytest.mark.parametrize("""paths_type""" , [str, list, dict] ) def _lowerCAmelCase ( lowercase , lowercase , lowercase ) -> Union[str, Any]: __lowerCAmelCase = str(lowercase ) if issubclass(lowercase , lowercase ): __lowerCAmelCase = filename elif issubclass(lowercase , lowercase ): __lowerCAmelCase = [filename] elif issubclass(lowercase , lowercase ): __lowerCAmelCase = {"""train""": filename} __lowerCAmelCase = """dummy""" __lowerCAmelCase = xz_file.parent __lowerCAmelCase = """extracted""" __lowerCAmelCase = DownloadConfig( cache_dir=lowercase , use_etag=lowercase , ) __lowerCAmelCase = DownloadManager(dataset_name=lowercase , download_config=lowercase ) __lowerCAmelCase = dl_manager.extract(lowercase ) __lowerCAmelCase = paths for extracted_paths in [extracted_paths]: if isinstance(lowercase , lowercase ): __lowerCAmelCase = [extracted_paths] __lowerCAmelCase = [paths] elif isinstance(lowercase , lowercase ): assert "train" in extracted_paths.keys() __lowerCAmelCase = extracted_paths.values() __lowerCAmelCase = paths.values() assert extracted_paths for extracted_path, input_path in zip(lowercase , lowercase ): assert extracted_path == dl_manager.extracted_paths[input_path] __lowerCAmelCase = Path(lowercase ) __lowerCAmelCase = extracted_path.parts assert parts[-1] == hash_url_to_filename(lowercase , etag=lowercase ) assert parts[-2] == extracted_subdir assert extracted_path.exists() __lowerCAmelCase = extracted_path.read_text() __lowerCAmelCase = text_file.read_text() assert extracted_file_content == expected_file_content def _lowerCAmelCase ( lowercase , lowercase ) -> Tuple: assert path.endswith(""".jsonl""" ) for num_items, line in enumerate(lowercase , start=1 ): __lowerCAmelCase = json.loads(line.decode("""utf-8""" ) ) assert item.keys() == {"col_1", "col_2", "col_3"} assert num_items == 4 @pytest.mark.parametrize("""archive_jsonl""" , ["""tar_jsonl_path""", """zip_jsonl_path"""] ) def _lowerCAmelCase ( lowercase , lowercase ) -> List[str]: __lowerCAmelCase = request.getfixturevalue(lowercase ) __lowerCAmelCase = DownloadManager() for num_jsonl, (path, file) in enumerate(dl_manager.iter_archive(lowercase ) , start=1 ): _test_jsonl(lowercase , lowercase ) assert num_jsonl == 2 @pytest.mark.parametrize("""archive_nested_jsonl""" , ["""tar_nested_jsonl_path""", """zip_nested_jsonl_path"""] ) def _lowerCAmelCase ( lowercase , lowercase ) -> List[Any]: __lowerCAmelCase = request.getfixturevalue(lowercase ) __lowerCAmelCase = DownloadManager() for num_tar, (path, file) in enumerate(dl_manager.iter_archive(lowercase ) , start=1 ): for num_jsonl, (subpath, subfile) in enumerate(dl_manager.iter_archive(lowercase ) , start=1 ): _test_jsonl(lowercase , lowercase ) assert num_tar == 1 assert num_jsonl == 2 def _lowerCAmelCase ( lowercase ) -> List[Any]: __lowerCAmelCase = DownloadManager() for num_file, file in enumerate(dl_manager.iter_files(lowercase ) , start=1 ): assert os.path.basename(lowercase ) == ("test.txt" if num_file == 1 else "train.txt") assert num_file == 2
46
'''simple docstring''' from __future__ import annotations from numpy import array, cos, cross, floataa, radians, sin from numpy.typing import NDArray def _lowerCAmelCase ( lowercase , lowercase , lowercase = False ) -> list[float]: if radian_mode: return [magnitude * cos(lowercase ), magnitude * sin(lowercase )] return [magnitude * cos(radians(lowercase ) ), magnitude * sin(radians(lowercase ) )] def _lowerCAmelCase ( lowercase , lowercase , lowercase = 10**-1 ) -> bool: __lowerCAmelCase = cross(lowercase , lowercase ) __lowerCAmelCase = sum(lowercase ) return abs(lowercase ) < eps if __name__ == "__main__": # Test to check if it works _a : Any = array( [ polar_force(718.4, 1_8_0 - 3_0), polar_force(879.54, 4_5), polar_force(1_0_0, -9_0), ] ) _a : NDArray[floataa] = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem 1 in image_data/2D_problems.jpg _a : List[Any] = array( [ polar_force(3_0 * 9.81, 1_5), polar_force(2_1_5, 1_8_0 - 4_5), polar_force(2_6_4, 9_0 - 3_0), ] ) _a : Optional[int] = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem in image_data/2D_problems_1.jpg _a : Union[str, Any] = array([[0, -2_0_0_0], [0, -1_2_0_0], [0, 1_5_6_0_0], [0, -1_2_4_0_0]]) _a : Optional[int] = array([[0, 0], [6, 0], [1_0, 0], [1_2, 0]]) assert in_static_equilibrium(forces, location) import doctest doctest.testmod()
46
1
'''simple docstring''' import sacrebleu as scb from packaging import version from sacrebleu import CHRF import datasets __A = "\\n@inproceedings{popovic-2015-chrf,\n title = \"chr{F}: character n-gram {F}-score for automatic {MT} evaluation\",\n author = \"Popovi{\'c}, Maja\",\n booktitle = \"Proceedings of the Tenth Workshop on Statistical Machine Translation\",\n month = sep,\n year = \"2015\",\n address = \"Lisbon, Portugal\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://aclanthology.org/W15-3049\",\n doi = \"10.18653/v1/W15-3049\",\n pages = \"392--395\",\n}\n@inproceedings{popovic-2017-chrf,\n title = \"chr{F}++: words helping character n-grams\",\n author = \"Popovi{\'c}, Maja\",\n booktitle = \"Proceedings of the Second Conference on Machine Translation\",\n month = sep,\n year = \"2017\",\n address = \"Copenhagen, Denmark\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://aclanthology.org/W17-4770\",\n doi = \"10.18653/v1/W17-4770\",\n pages = \"612--618\",\n}\n@inproceedings{post-2018-call,\n title = \"A Call for Clarity in Reporting {BLEU} Scores\",\n author = \"Post, Matt\",\n booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\",\n month = oct,\n year = \"2018\",\n address = \"Belgium, Brussels\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://www.aclweb.org/anthology/W18-6319\",\n pages = \"186--191\",\n}\n" __A = "\\nChrF and ChrF++ are two MT evaluation metrics. They both use the F-score statistic for character n-gram matches,\nand ChrF++ adds word n-grams as well which correlates more strongly with direct assessment. We use the implementation\nthat is already present in sacrebleu.\n\nThe implementation here is slightly different from sacrebleu in terms of the required input format. The length of\nthe references and hypotheses lists need to be the same, so you may need to transpose your references compared to\nsacrebleu's required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534\n\nSee the README.md file at https://github.com/mjpost/sacreBLEU#chrf--chrf for more information.\n" __A = "\nProduces ChrF(++) scores for hypotheses given reference translations.\n\nArgs:\n predictions (list of str): The predicted sentences.\n references (list of list of str): The references. There should be one reference sub-list for each prediction sentence.\n char_order (int): Character n-gram order. Defaults to `6`.\n word_order (int): Word n-gram order. If equals to `2`, the metric is referred to as chrF++. Defaults to `0`.\n beta (int): Determine the importance of recall w.r.t precision. Defaults to `2`.\n lowercase (bool): if `True`, enables case-insensitivity. Defaults to `False`.\n whitespace (bool): If `True`, include whitespaces when extracting character n-grams.\n eps_smoothing (bool): If `True`, applies epsilon smoothing similar\n to reference chrF++.py, NLTK and Moses implementations. If `False`,\n it takes into account effective match order similar to sacreBLEU < 2.0.0. Defaults to `False`.\n\nReturns:\n 'score' (float): The chrF (chrF++) score,\n 'char_order' (int): The character n-gram order,\n 'word_order' (int): The word n-gram order. If equals to 2, the metric is referred to as chrF++,\n 'beta' (int): Determine the importance of recall w.r.t precision\n\nExamples:\n Example 1--a simple example of calculating chrF:\n >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n >>> chrf = datasets.load_metric(\"chrf\")\n >>> results = chrf.compute(predictions=prediction, references=reference)\n >>> print(results)\n {'score': 84.64214891738334, 'char_order': 6, 'word_order': 0, 'beta': 2}\n\n Example 2--the same example, but with the argument word_order=2, to calculate chrF++ instead of chrF:\n >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n >>> chrf = datasets.load_metric(\"chrf\")\n >>> results = chrf.compute(predictions=prediction,\n ... references=reference,\n ... word_order=2)\n >>> print(results)\n {'score': 82.87263732906315, 'char_order': 6, 'word_order': 2, 'beta': 2}\n\n Example 3--the same chrF++ example as above, but with `lowercase=True` to normalize all case:\n >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n >>> chrf = datasets.load_metric(\"chrf\")\n >>> results = chrf.compute(predictions=prediction,\n ... references=reference,\n ... word_order=2,\n ... lowercase=True)\n >>> print(results)\n {'score': 92.12853119829202, 'char_order': 6, 'word_order': 2, 'beta': 2}\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A ( datasets.Metric ): def A__ ( self ) -> Any: '''simple docstring''' if version.parse(scb.__version__ ) < version.parse("""1.4.12""" ): raise ImportWarning( """To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn't match this condition.\n""" """You can install it with `pip install \"sacrebleu>=1.4.12\"`.""" ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage="""https://github.com/mjpost/sacreBLEU#chrf--chrf""" , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""string""" , id="""sequence""" ), """references""": datasets.Sequence(datasets.Value("""string""" , id="""sequence""" ) , id="""references""" ), } ) , codebase_urls=["""https://github.com/mjpost/sacreBLEU#chrf--chrf"""] , reference_urls=[ """https://github.com/m-popovic/chrF""", ] , ) def A__ ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = CHRF.CHAR_ORDER , lowerCamelCase__ = CHRF.WORD_ORDER , lowerCamelCase__ = CHRF.BETA , lowerCamelCase__ = False , lowerCamelCase__ = False , lowerCamelCase__ = False , ) -> Tuple: '''simple docstring''' lowercase__ = len(references[0] ) if any(len(lowerCamelCase__ ) != references_per_prediction for refs in references ): raise ValueError("""Sacrebleu requires the same number of references for each prediction""" ) lowercase__ = [[refs[i] for refs in references] for i in range(lowerCamelCase__ )] lowercase__ = CHRF(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) lowercase__ = sb_chrf.corpus_score(lowerCamelCase__ , lowerCamelCase__ ) return { "score": output.score, "char_order": output.char_order, "word_order": output.word_order, "beta": output.beta, }
164
'''simple docstring''' from __future__ import annotations import collections import pprint from pathlib import Path def _A ( lowercase__ ): return "".join(sorted(lowercase__ ) ) def _A ( lowercase__ ): return word_by_signature[signature(lowercase__ )] __A = Path(__file__).parent.joinpath("words.txt").read_text(encoding="utf-8") __A = sorted({word.strip().lower() for word in data.splitlines()}) __A = collections.defaultdict(list) for word in word_list: word_by_signature[signature(word)].append(word) if __name__ == "__main__": __A = {word: anagram(word) for word in word_list if len(anagram(word)) > 1} with open("anagrams.txt", "w") as file: file.write("all_anagrams = \n ") file.write(pprint.pformat(all_anagrams))
164
1
"""simple docstring""" def _lowercase ( __lowerCAmelCase , __lowerCAmelCase = 0 ) -> list: SCREAMING_SNAKE_CASE__ : Optional[int] = length or len(_snake_case ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = False for i in range(length - 1 ): if list_data[i] > list_data[i + 1]: SCREAMING_SNAKE_CASE__ : List[str] = list_data[i + 1], list_data[i] SCREAMING_SNAKE_CASE__ : int = True return list_data if not swapped else bubble_sort(_snake_case , length - 1 ) if __name__ == "__main__": import doctest doctest.testmod()
369
"""simple docstring""" from math import loga def _lowercase ( __lowerCAmelCase ) -> int: if a < 0: raise ValueError("""Input value must be a positive integer""" ) elif isinstance(__lowerCAmelCase , __lowerCAmelCase ): raise TypeError("""Input value must be a 'int' type""" ) return 0 if (a == 0) else int(loga(a & -a ) ) if __name__ == "__main__": import doctest doctest.testmod()
56
0
from collections import namedtuple UpperCAmelCase : int = namedtuple('''from_to''', '''from_ to''') UpperCAmelCase : List[str] = { '''cubicmeter''': from_to(1, 1), '''litre''': from_to(0.001, 10_00), '''kilolitre''': from_to(1, 1), '''gallon''': from_to(0.00454, 264.172), '''cubicyard''': from_to(0.76455, 1.30795), '''cubicfoot''': from_to(0.028, 35.3147), '''cup''': from_to(0.000236588, 4226.75), } def _SCREAMING_SNAKE_CASE ( a , a , a ) -> float: if from_type not in METRIC_CONVERSION: raise ValueError( F"""Invalid 'from_type' value: {from_type!r} Supported values are:\n""" + ', '.join(a ) ) if to_type not in METRIC_CONVERSION: raise ValueError( F"""Invalid 'to_type' value: {to_type!r}. Supported values are:\n""" + ', '.join(a ) ) return value * METRIC_CONVERSION[from_type].from_ * METRIC_CONVERSION[to_type].to if __name__ == "__main__": import doctest doctest.testmod()
280
import argparse import os import gluonnlp as nlp import mxnet as mx import numpy as np import torch from gluonnlp.base import get_home_dir from gluonnlp.model.bert import BERTEncoder from gluonnlp.model.utils import _load_vocab from gluonnlp.vocab import Vocab from packaging import version from torch import nn from transformers import BertConfig, BertForMaskedLM, BertModel, RobertaTokenizer from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertSelfAttention, BertSelfOutput, ) from transformers.utils import logging if version.parse(nlp.__version__) != version.parse('''0.8.3'''): raise Exception('''requires gluonnlp == 0.8.3''') if version.parse(mx.__version__) != version.parse('''1.5.0'''): raise Exception('''requires mxnet == 1.5.0''') logging.set_verbosity_info() UpperCAmelCase : List[Any] = logging.get_logger(__name__) UpperCAmelCase : Optional[Any] = '''The Nymphenburg Palace is a beautiful palace in Munich!''' def _SCREAMING_SNAKE_CASE ( a , a ) -> Optional[Any]: __A : Any = { 'attention_cell': 'multi_head', 'num_layers': 4, 'units': 10_24, 'hidden_size': 7_68, 'max_length': 5_12, 'num_heads': 8, 'scaled': True, 'dropout': 0.1, 'use_residual': True, 'embed_size': 10_24, 'embed_dropout': 0.1, 'word_embed': None, 'layer_norm_eps': 1e-5, 'token_type_vocab_size': 2, } __A : str = bort_4_8_768_1024_hparams # Let's construct the original Bort model here # Taken from official BERT implementation, see: # https://github.com/alexa/bort/blob/master/bort/bort.py __A : Optional[int] = BERTEncoder( attention_cell=predefined_args['attention_cell'] , num_layers=predefined_args['num_layers'] , units=predefined_args['units'] , hidden_size=predefined_args['hidden_size'] , max_length=predefined_args['max_length'] , num_heads=predefined_args['num_heads'] , scaled=predefined_args['scaled'] , dropout=predefined_args['dropout'] , output_attention=a , output_all_encodings=a , use_residual=predefined_args['use_residual'] , activation=predefined_args.get('activation' , 'gelu' ) , layer_norm_eps=predefined_args.get('layer_norm_eps' , a ) , ) # Vocab information needs to be fetched first # It's the same as RoBERTa, so RobertaTokenizer can be used later __A : Union[str, Any] = 'openwebtext_ccnews_stories_books_cased' # Specify download folder to Gluonnlp's vocab __A : Any = os.path.join(get_home_dir() , 'models' ) __A : List[Any] = _load_vocab(a , a , a , cls=a ) __A : Dict = nlp.model.BERTModel( a , len(a ) , units=predefined_args['units'] , embed_size=predefined_args['embed_size'] , embed_dropout=predefined_args['embed_dropout'] , word_embed=predefined_args['word_embed'] , use_pooler=a , use_token_type_embed=a , token_type_vocab_size=predefined_args['token_type_vocab_size'] , use_classifier=a , use_decoder=a , ) original_bort.load_parameters(a , cast_dtype=a , ignore_extra=a ) __A : Union[str, Any] = original_bort._collect_params_with_prefix() # Build our config 🤗 __A : Any = { 'architectures': ['BertForMaskedLM'], 'attention_probs_dropout_prob': predefined_args['dropout'], 'hidden_act': 'gelu', 'hidden_dropout_prob': predefined_args['dropout'], 'hidden_size': predefined_args['embed_size'], 'initializer_range': 0.02, 'intermediate_size': predefined_args['hidden_size'], 'layer_norm_eps': predefined_args['layer_norm_eps'], 'max_position_embeddings': predefined_args['max_length'], 'model_type': 'bort', 'num_attention_heads': predefined_args['num_heads'], 'num_hidden_layers': predefined_args['num_layers'], 'pad_token_id': 1, # 2 = BERT, 1 = RoBERTa 'type_vocab_size': 1, # 2 = BERT, 1 = RoBERTa 'vocab_size': len(a ), } __A : int = BertConfig.from_dict(a ) __A : Union[str, Any] = BertForMaskedLM(a ) hf_bort_model.eval() # Parameter mapping table (Gluonnlp to Transformers) # * denotes layer index # # | Gluon Parameter | Transformers Parameter # | -------------------------------------------------------------- | ---------------------- # | `encoder.layer_norm.beta` | `bert.embeddings.LayerNorm.bias` # | `encoder.layer_norm.gamma` | `bert.embeddings.LayerNorm.weight` # | `encoder.position_weight` | `bert.embeddings.position_embeddings.weight` # | `word_embed.0.weight` | `bert.embeddings.word_embeddings.weight` # | `encoder.transformer_cells.*.attention_cell.proj_key.bias` | `bert.encoder.layer.*.attention.self.key.bias` # | `encoder.transformer_cells.*.attention_cell.proj_key.weight` | `bert.encoder.layer.*.attention.self.key.weight` # | `encoder.transformer_cells.*.attention_cell.proj_query.bias` | `bert.encoder.layer.*.attention.self.query.bias` # | `encoder.transformer_cells.*.attention_cell.proj_query.weight` | `bert.encoder.layer.*.attention.self.query.weight` # | `encoder.transformer_cells.*.attention_cell.proj_value.bias` | `bert.encoder.layer.*.attention.self.value.bias` # | `encoder.transformer_cells.*.attention_cell.proj_value.weight` | `bert.encoder.layer.*.attention.self.value.weight` # | `encoder.transformer_cells.*.ffn.ffn_2.bias` | `bert.encoder.layer.*.attention.output.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_2.weight` | `bert.encoder.layer.*.attention.output.dense.weight` # | `encoder.transformer_cells.*.layer_norm.beta` | `bert.encoder.layer.*.attention.output.LayerNorm.bias` # | `encoder.transformer_cells.*.layer_norm.gamma` | `bert.encoder.layer.*.attention.output.LayerNorm.weight` # | `encoder.transformer_cells.*.ffn.ffn_1.bias` | `bert.encoder.layer.*.intermediate.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_1.weight` | `bert.encoder.layer.*.intermediate.dense.weight` # | `encoder.transformer_cells.*.ffn.layer_norm.beta` | `bert.encoder.layer.*.output.LayerNorm.bias` # | `encoder.transformer_cells.*.ffn.layer_norm.gamma` | `bert.encoder.layer.*.output.LayerNorm.weight` # | `encoder.transformer_cells.*.proj.bias` | `bert.encoder.layer.*.output.dense.bias` # | `encoder.transformer_cells.*.proj.weight` | `bert.encoder.layer.*.output.dense.weight` # Helper function to convert MXNET Arrays to PyTorch def to_torch(a ) -> nn.Parameter: return nn.Parameter(torch.FloatTensor(mx_array.data().asnumpy() ) ) # Check param shapes and map new HF param back def check_and_map_params(a , a ): __A : Tuple = hf_param.shape __A : str = to_torch(params[gluon_param] ) __A : Union[str, Any] = gluon_param.shape assert ( shape_hf == shape_gluon ), F"""The gluon parameter {gluon_param} has shape {shape_gluon}, but expects shape {shape_hf} for Transformers""" return gluon_param __A : str = check_and_map_params( hf_bort_model.bert.embeddings.word_embeddings.weight , 'word_embed.0.weight' ) __A : Tuple = check_and_map_params( hf_bort_model.bert.embeddings.position_embeddings.weight , 'encoder.position_weight' ) __A : List[str] = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.bias , 'encoder.layer_norm.beta' ) __A : Tuple = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.weight , 'encoder.layer_norm.gamma' ) # Inspired by RoBERTa conversion script, we just zero them out (Bort does not use them) __A : Tuple = torch.zeros_like( hf_bort_model.bert.embeddings.token_type_embeddings.weight.data ) for i in range(hf_bort_config.num_hidden_layers ): __A : BertLayer = hf_bort_model.bert.encoder.layer[i] # self attention __A : BertSelfAttention = layer.attention.self __A : Optional[Any] = check_and_map_params( self_attn.key.bias.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_key.bias""" ) __A : Optional[int] = check_and_map_params( self_attn.key.weight.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_key.weight""" ) __A : Union[str, Any] = check_and_map_params( self_attn.query.bias.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_query.bias""" ) __A : Optional[Any] = check_and_map_params( self_attn.query.weight.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_query.weight""" ) __A : Union[str, Any] = check_and_map_params( self_attn.value.bias.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_value.bias""" ) __A : Optional[int] = check_and_map_params( self_attn.value.weight.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_value.weight""" ) # self attention output __A : BertSelfOutput = layer.attention.output __A : Tuple = check_and_map_params( self_output.dense.bias , F"""encoder.transformer_cells.{i}.proj.bias""" ) __A : int = check_and_map_params( self_output.dense.weight , F"""encoder.transformer_cells.{i}.proj.weight""" ) __A : List[Any] = check_and_map_params( self_output.LayerNorm.bias , F"""encoder.transformer_cells.{i}.layer_norm.beta""" ) __A : str = check_and_map_params( self_output.LayerNorm.weight , F"""encoder.transformer_cells.{i}.layer_norm.gamma""" ) # intermediate __A : BertIntermediate = layer.intermediate __A : int = check_and_map_params( intermediate.dense.bias , F"""encoder.transformer_cells.{i}.ffn.ffn_1.bias""" ) __A : List[Any] = check_and_map_params( intermediate.dense.weight , F"""encoder.transformer_cells.{i}.ffn.ffn_1.weight""" ) # output __A : BertOutput = layer.output __A : List[Any] = check_and_map_params( bert_output.dense.bias , F"""encoder.transformer_cells.{i}.ffn.ffn_2.bias""" ) __A : Dict = check_and_map_params( bert_output.dense.weight , F"""encoder.transformer_cells.{i}.ffn.ffn_2.weight""" ) __A : Optional[int] = check_and_map_params( bert_output.LayerNorm.bias , F"""encoder.transformer_cells.{i}.ffn.layer_norm.beta""" ) __A : Dict = check_and_map_params( bert_output.LayerNorm.weight , F"""encoder.transformer_cells.{i}.ffn.layer_norm.gamma""" ) # Save space and energy 🎄 hf_bort_model.half() # Compare output of both models __A : Any = RobertaTokenizer.from_pretrained('roberta-base' ) __A : List[str] = tokenizer.encode_plus(a )['input_ids'] # Get gluon output __A : List[str] = mx.nd.array([input_ids] ) __A : Union[str, Any] = original_bort(inputs=a , token_types=[] ) # Get Transformer output (save and reload model again) hf_bort_model.save_pretrained(a ) __A : Optional[Any] = BertModel.from_pretrained(a ) hf_bort_model.eval() __A : Tuple = tokenizer.encode_plus(a , return_tensors='pt' ) __A : Any = hf_bort_model(**a )[0] __A : Union[str, Any] = output_gluon[0].asnumpy() __A : Tuple = output_hf[0].detach().numpy() __A : int = np.max(np.abs(hf_layer - gluon_layer ) ).item() __A : int = np.allclose(a , a , atol=1e-3 ) if success: print('✔️ Both model do output the same tensors' ) else: print('❌ Both model do **NOT** output the same tensors' ) print('Absolute difference is:' , a ) if __name__ == "__main__": UpperCAmelCase : int = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--bort_checkpoint_path''', default=None, type=str, required=True, help='''Path the official Bort params file.''' ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) UpperCAmelCase : Dict = parser.parse_args() convert_bort_checkpoint_to_pytorch(args.bort_checkpoint_path, args.pytorch_dump_folder_path)
280
1
"""simple docstring""" import requests from bsa import BeautifulSoup def _A ( lowercase = "https://www.worldometers.info/coronavirus" ): """simple docstring""" a =BeautifulSoup(requests.get(lowercase ).text , '''html.parser''' ) a =soup.findAll('''h1''' ) a =soup.findAll('''div''' , {'''class''': '''maincounter-number'''} ) keys += soup.findAll('''span''' , {'''class''': '''panel-title'''} ) values += soup.findAll('''div''' , {'''class''': '''number-table-main'''} ) return {key.text.strip(): value.text.strip() for key, value in zip(lowercase , lowercase )} if __name__ == "__main__": print("""\033[1m""" + """COVID-19 Status of the World""" + """\033[0m\n""") for key, value in world_covidaa_stats().items(): print(F'{key}\n{value}\n')
215
"""simple docstring""" import os import sys import unittest lowerCamelCase_ : Tuple = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, """utils""")) import get_test_info # noqa: E402 from get_test_info import ( # noqa: E402 get_model_to_test_mapping, get_model_to_tester_mapping, get_test_to_tester_mapping, ) lowerCamelCase_ : Dict = os.path.join("""tests""", """models""", """bert""", """test_modeling_bert.py""") lowerCamelCase_ : Dict = os.path.join("""tests""", """models""", """blip""", """test_modeling_blip.py""") class __A ( unittest.TestCase ): """simple docstring""" def SCREAMING_SNAKE_CASE ( self ) -> Any: a =get_test_to_tester_mapping(__A ) a =get_test_to_tester_mapping(__A ) a ={'''BertModelTest''': '''BertModelTester'''} a ={ '''BlipModelTest''': '''BlipModelTester''', '''BlipTextImageModelTest''': '''BlipTextImageModelsModelTester''', '''BlipTextModelTest''': '''BlipTextModelTester''', '''BlipTextRetrievalModelTest''': '''BlipTextRetrievalModelTester''', '''BlipVQAModelTest''': '''BlipVQAModelTester''', '''BlipVisionModelTest''': '''BlipVisionModelTester''', } self.assertEqual(get_test_info.to_json(__A ) , __A ) self.assertEqual(get_test_info.to_json(__A ) , __A ) def SCREAMING_SNAKE_CASE ( self ) -> List[str]: a =get_model_to_test_mapping(__A ) a =get_model_to_test_mapping(__A ) a ={ '''BertForMaskedLM''': ['''BertModelTest'''], '''BertForMultipleChoice''': ['''BertModelTest'''], '''BertForNextSentencePrediction''': ['''BertModelTest'''], '''BertForPreTraining''': ['''BertModelTest'''], '''BertForQuestionAnswering''': ['''BertModelTest'''], '''BertForSequenceClassification''': ['''BertModelTest'''], '''BertForTokenClassification''': ['''BertModelTest'''], '''BertLMHeadModel''': ['''BertModelTest'''], '''BertModel''': ['''BertModelTest'''], } a ={ '''BlipForConditionalGeneration''': ['''BlipTextImageModelTest'''], '''BlipForImageTextRetrieval''': ['''BlipTextRetrievalModelTest'''], '''BlipForQuestionAnswering''': ['''BlipVQAModelTest'''], '''BlipModel''': ['''BlipModelTest'''], '''BlipTextModel''': ['''BlipTextModelTest'''], '''BlipVisionModel''': ['''BlipVisionModelTest'''], } self.assertEqual(get_test_info.to_json(__A ) , __A ) self.assertEqual(get_test_info.to_json(__A ) , __A ) def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: a =get_model_to_tester_mapping(__A ) a =get_model_to_tester_mapping(__A ) a ={ '''BertForMaskedLM''': ['''BertModelTester'''], '''BertForMultipleChoice''': ['''BertModelTester'''], '''BertForNextSentencePrediction''': ['''BertModelTester'''], '''BertForPreTraining''': ['''BertModelTester'''], '''BertForQuestionAnswering''': ['''BertModelTester'''], '''BertForSequenceClassification''': ['''BertModelTester'''], '''BertForTokenClassification''': ['''BertModelTester'''], '''BertLMHeadModel''': ['''BertModelTester'''], '''BertModel''': ['''BertModelTester'''], } a ={ '''BlipForConditionalGeneration''': ['''BlipTextImageModelsModelTester'''], '''BlipForImageTextRetrieval''': ['''BlipTextRetrievalModelTester'''], '''BlipForQuestionAnswering''': ['''BlipVQAModelTester'''], '''BlipModel''': ['''BlipModelTester'''], '''BlipTextModel''': ['''BlipTextModelTester'''], '''BlipVisionModel''': ['''BlipVisionModelTester'''], } self.assertEqual(get_test_info.to_json(__A ) , __A ) self.assertEqual(get_test_info.to_json(__A ) , __A )
215
1
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowercase = logging.get_logger(__name__) lowercase = { "YituTech/conv-bert-base": "https://huggingface.co/YituTech/conv-bert-base/resolve/main/config.json", "YituTech/conv-bert-medium-small": ( "https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/config.json" ), "YituTech/conv-bert-small": "https://huggingface.co/YituTech/conv-bert-small/resolve/main/config.json", # See all ConvBERT models at https://huggingface.co/models?filter=convbert } class UpperCamelCase_ ( snake_case_ ): '''simple docstring''' lowerCAmelCase = '''convbert''' def __init__( self , a=3_05_22 , a=7_68 , a=12 , a=12 , a=30_72 , a="gelu" , a=0.1 , a=0.1 , a=5_12 , a=2 , a=0.02 , a=1E-12 , a=1 , a=0 , a=2 , a=7_68 , a=2 , a=9 , a=1 , a=None , **a , ) -> Optional[int]: super().__init__( pad_token_id=a , bos_token_id=a , eos_token_id=a , **a , ) snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = max_position_embeddings snake_case_ = type_vocab_size snake_case_ = initializer_range snake_case_ = layer_norm_eps snake_case_ = embedding_size snake_case_ = head_ratio snake_case_ = conv_kernel_size snake_case_ = num_groups snake_case_ = classifier_dropout class UpperCamelCase_ ( snake_case_ ): '''simple docstring''' @property def _UpperCamelCase ( self ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": snake_case_ = {0: 'batch', 1: 'choice', 2: 'sequence'} else: snake_case_ = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ('token_type_ids', dynamic_axis), ] )
178
import logging from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import arg_to_scheduler from transformers import TrainingArguments lowercase = logging.getLogger(__name__) @dataclass class UpperCamelCase_ ( snake_case_ ): '''simple docstring''' lowerCAmelCase = field( default=0.0 , metadata={'''help''': '''The label smoothing epsilon to apply (if not zero).'''} ) lowerCAmelCase = field(default=snake_case_ , metadata={'''help''': '''Whether to SortishSamler or not.'''} ) lowerCAmelCase = field( default=snake_case_ , metadata={'''help''': '''Whether to use generate to calculate generative metrics (ROUGE, BLEU).'''} ) lowerCAmelCase = field(default=snake_case_ , metadata={'''help''': '''whether to use adafactor'''} ) lowerCAmelCase = field( default=snake_case_ , metadata={'''help''': '''Encoder layer dropout probability. Goes into model.config.'''} ) lowerCAmelCase = field( default=snake_case_ , metadata={'''help''': '''Decoder layer dropout probability. Goes into model.config.'''} ) lowerCAmelCase = field(default=snake_case_ , metadata={'''help''': '''Dropout probability. Goes into model.config.'''} ) lowerCAmelCase = field( default=snake_case_ , metadata={'''help''': '''Attention dropout probability. Goes into model.config.'''} ) lowerCAmelCase = field( default='''linear''' , metadata={'''help''': F'''Which lr scheduler to use. Selected in {sorted(arg_to_scheduler.keys() )}'''} , )
178
1
"""simple docstring""" import numpy as np def _a ( _SCREAMING_SNAKE_CASE ) -> np.array: return 1 / (1 + np.exp(-vector )) def _a ( _SCREAMING_SNAKE_CASE ) -> np.array: return vector * sigmoid(1.702 * vector ) if __name__ == "__main__": import doctest doctest.testmod()
364
"""simple docstring""" import secrets from random import shuffle from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation def _a ( _SCREAMING_SNAKE_CASE = 8 ) -> str: snake_case_ = ascii_letters + digits + punctuation return "".join(secrets.choice(_SCREAMING_SNAKE_CASE ) for _ in range(_SCREAMING_SNAKE_CASE ) ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: # Password Generator = full boot with random_number, random_letters, and # random_character FUNCTIONS # Put your code here... i -= len(_SCREAMING_SNAKE_CASE ) snake_case_ = i // 3 snake_case_ = i % 3 # chars = chars_incl + random_letters(ascii_letters, i / 3 + remainder) + # random_number(digits, i / 3) + random_characters(punctuation, i / 3) snake_case_ = ( chars_incl + random(_SCREAMING_SNAKE_CASE , quotient + remainder ) + random(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) + random(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) snake_case_ = list(_SCREAMING_SNAKE_CASE ) shuffle(_SCREAMING_SNAKE_CASE ) return "".join(_SCREAMING_SNAKE_CASE ) # random is a generalised function for letters, characters and numbers def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: return "".join(secrets.choice(_SCREAMING_SNAKE_CASE ) for _ in range(_SCREAMING_SNAKE_CASE ) ) def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: pass # Put your code here... def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[int]: pass # Put your code here... def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[Any]: pass # Put your code here... def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 8 ) -> bool: if len(_SCREAMING_SNAKE_CASE ) < min_length: # Your Password must be at least 8 characters long return False snake_case_ = any(char in ascii_uppercase for char in password ) snake_case_ = any(char in ascii_lowercase for char in password ) snake_case_ = any(char in digits for char in password ) snake_case_ = any(char in punctuation for char in password ) return upper and lower and num and spec_char # Passwords should contain UPPERCASE, lowerase # numbers, and special characters def _a ( ) -> Union[str, Any]: snake_case_ = int(input("""Please indicate the max length of your password: """ ).strip() ) snake_case_ = input( """Please indicate the characters that must be in your password: """ ).strip() print("""Password generated:""" , password_generator(_SCREAMING_SNAKE_CASE ) ) print( """Alternative Password generated:""" , alternative_password_generator(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) , ) print("""[If you are thinking of using this passsword, You better save it.]""" ) if __name__ == "__main__": main()
233
0
'''simple docstring''' from io import BytesIO from typing import List, Union import requests from ..utils import add_end_docstrings, is_decord_available, is_torch_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_decord_available(): import numpy as np from decord import VideoReader if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING _lowerCamelCase : Any = logging.get_logger(__name__) @add_end_docstrings(_a ) class SCREAMING_SNAKE_CASE ( _a ): """simple docstring""" def __init__( self : Any , *UpperCamelCase__ : Dict , **UpperCamelCase__ : Union[str, Any] ): """simple docstring""" super().__init__(*UpperCamelCase__ , **UpperCamelCase__ ) requires_backends(self , 'decord' ) self.check_model_type(UpperCamelCase__ ) def A ( self : Optional[int] , UpperCamelCase__ : Optional[int]=None , UpperCamelCase__ : Optional[Any]=None , UpperCamelCase__ : Optional[Any]=None ): """simple docstring""" UpperCamelCase = {} if frame_sampling_rate is not None: UpperCamelCase = frame_sampling_rate if num_frames is not None: UpperCamelCase = num_frames UpperCamelCase = {} if top_k is not None: UpperCamelCase = top_k return preprocess_params, {}, postprocess_params def __call__( self : List[str] , UpperCamelCase__ : Union[str, List[str]] , **UpperCamelCase__ : Dict ): """simple docstring""" return super().__call__(UpperCamelCase__ , **UpperCamelCase__ ) def A ( self : Tuple , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Tuple=None , UpperCamelCase__ : Tuple=1 ): """simple docstring""" if num_frames is None: UpperCamelCase = self.model.config.num_frames if video.startswith('http://' ) or video.startswith('https://' ): UpperCamelCase = BytesIO(requests.get(UpperCamelCase__ ).content ) UpperCamelCase = VideoReader(UpperCamelCase__ ) videoreader.seek(0 ) UpperCamelCase = 0 UpperCamelCase = num_frames * frame_sampling_rate - 1 UpperCamelCase = np.linspace(UpperCamelCase__ , UpperCamelCase__ , num=UpperCamelCase__ , dtype=np.intaa ) UpperCamelCase = videoreader.get_batch(UpperCamelCase__ ).asnumpy() UpperCamelCase = list(UpperCamelCase__ ) UpperCamelCase = self.image_processor(UpperCamelCase__ , return_tensors=self.framework ) return model_inputs def A ( self : Union[str, Any] , UpperCamelCase__ : List[str] ): """simple docstring""" UpperCamelCase = self.model(**UpperCamelCase__ ) return model_outputs def A ( self : int , UpperCamelCase__ : str , UpperCamelCase__ : List[Any]=5 ): """simple docstring""" if top_k > self.model.config.num_labels: UpperCamelCase = self.model.config.num_labels if self.framework == "pt": UpperCamelCase = model_outputs.logits.softmax(-1 )[0] UpperCamelCase , UpperCamelCase = probs.topk(UpperCamelCase__ ) else: raise ValueError(f"""Unsupported framework: {self.framework}""" ) UpperCamelCase = scores.tolist() UpperCamelCase = ids.tolist() return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(UpperCamelCase__ , UpperCamelCase__ )]
28
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase__ : List[str] = logging.get_logger(__name__) lowercase__ : Optional[int] = { 'MIT/ast-finetuned-audioset-10-10-0.4593': ( 'https://huggingface.co/MIT/ast-finetuned-audioset-10-10-0.4593/resolve/main/config.json' ), } class __lowerCAmelCase ( __magic_name__ ): """simple docstring""" _snake_case : int = 'audio-spectrogram-transformer' def __init__( self : Optional[Any] , lowerCAmelCase__ : List[str]=768 , lowerCAmelCase__ : Optional[Any]=12 , lowerCAmelCase__ : int=12 , lowerCAmelCase__ : int=3072 , lowerCAmelCase__ : List[str]="gelu" , lowerCAmelCase__ : List[Any]=0.0 , lowerCAmelCase__ : Optional[Any]=0.0 , lowerCAmelCase__ : int=0.02 , lowerCAmelCase__ : Union[str, Any]=1e-1_2 , lowerCAmelCase__ : Any=16 , lowerCAmelCase__ : str=True , lowerCAmelCase__ : List[str]=10 , lowerCAmelCase__ : int=10 , lowerCAmelCase__ : Dict=1024 , lowerCAmelCase__ : Optional[int]=128 , **lowerCAmelCase__ : List[Any] , ) -> Tuple: '''simple docstring''' super().__init__(**lowerCAmelCase__ ) _UpperCamelCase = hidden_size _UpperCamelCase = num_hidden_layers _UpperCamelCase = num_attention_heads _UpperCamelCase = intermediate_size _UpperCamelCase = hidden_act _UpperCamelCase = hidden_dropout_prob _UpperCamelCase = attention_probs_dropout_prob _UpperCamelCase = initializer_range _UpperCamelCase = layer_norm_eps _UpperCamelCase = patch_size _UpperCamelCase = qkv_bias _UpperCamelCase = frequency_stride _UpperCamelCase = time_stride _UpperCamelCase = max_length _UpperCamelCase = num_mel_bins
324
0
import os from distutils.util import strtobool def lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): '''simple docstring''' for e in env_keys: __UpperCamelCase :Dict = int(os.environ.get(SCREAMING_SNAKE_CASE , -1 ) ) if val >= 0: return val return default def lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=False ): '''simple docstring''' __UpperCamelCase :Union[str, Any] = os.environ.get(SCREAMING_SNAKE_CASE , str(SCREAMING_SNAKE_CASE ) ) return strtobool(SCREAMING_SNAKE_CASE ) == 1 # As its name indicates `strtobool` actually returns an int... def lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE="no" ): '''simple docstring''' __UpperCamelCase :Any = os.environ.get(SCREAMING_SNAKE_CASE , str(SCREAMING_SNAKE_CASE ) ) return value
105
from __future__ import annotations def lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): '''simple docstring''' print(f"""Vertex\tShortest Distance from vertex {src}""" ) for i, d in enumerate(SCREAMING_SNAKE_CASE ): print(f"""{i}\t\t{d}""" ) def lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): '''simple docstring''' for j in range(SCREAMING_SNAKE_CASE ): __UpperCamelCase , __UpperCamelCase , __UpperCamelCase :int = (graph[j][k] for k in ['''src''', '''dst''', '''weight''']) if distance[u] != float('''inf''' ) and distance[u] + w < distance[v]: return True return False def lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCamelCase :List[Any] = [float('''inf''' )] * vertex_count __UpperCamelCase :str = 0.0 for _ in range(vertex_count - 1 ): for j in range(SCREAMING_SNAKE_CASE ): __UpperCamelCase , __UpperCamelCase , __UpperCamelCase :Dict = (graph[j][k] for k in ['''src''', '''dst''', '''weight''']) if distance[u] != float('''inf''' ) and distance[u] + w < distance[v]: __UpperCamelCase :Any = distance[u] + w __UpperCamelCase :Tuple = check_negative_cycle(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if negative_cycle_exists: raise Exception('''Negative cycle found''' ) return distance if __name__ == "__main__": import doctest doctest.testmod() __lowercase = int(input('''Enter number of vertices: ''').strip()) __lowercase = int(input('''Enter number of edges: ''').strip()) __lowercase = [{} for _ in range(E)] for i in range(E): print('''Edge ''', i + 1) __lowercase , __lowercase , __lowercase = ( int(x) for x in input('''Enter source, destination, weight: ''').strip().split(''' ''') ) __lowercase = {'''src''': src, '''dst''': dest, '''weight''': weight} __lowercase = int(input('''\nEnter shortest path source:''').strip()) __lowercase = bellman_ford(graph, V, E, source) print_distance(shortest_distance, 0)
105
1
import unittest import numpy as np from diffusers import LMSDiscreteScheduler, OnnxStableDiffusionInpaintPipeline from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class __A( a , unittest.TestCase ): # FIXME: add fast tests pass @nightly @require_onnxruntime @require_torch_gpu class __A( unittest.TestCase ): @property def SCREAMING_SNAKE_CASE_ ( self ) -> List[str]: '''simple docstring''' return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def SCREAMING_SNAKE_CASE_ ( self ) -> Union[str, Any]: '''simple docstring''' __a = ort.SessionOptions() __a = False return options def SCREAMING_SNAKE_CASE_ ( self ) -> Optional[Any]: '''simple docstring''' __a = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/in_paint/overture-creations-5sI6fQgYIuo.png''' ) __a = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/in_paint/overture-creations-5sI6fQgYIuo_mask.png''' ) __a = OnnxStableDiffusionInpaintPipeline.from_pretrained( '''runwayml/stable-diffusion-inpainting''' , revision='''onnx''' , safety_checker=_snake_case , feature_extractor=_snake_case , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=_snake_case ) __a = '''A red cat sitting on a park bench''' __a = np.random.RandomState(0 ) __a = pipe( prompt=_snake_case , image=_snake_case , mask_image=_snake_case , guidance_scale=7.5 , num_inference_steps=10 , generator=_snake_case , output_type='''np''' , ) __a = output.images __a = images[0, 255:258, 255:258, -1] assert images.shape == (1, 512, 512, 3) __a = np.array([0.2514, 0.3007, 0.3517, 0.1790, 0.2382, 0.3167, 0.1944, 0.2273, 0.2464] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def SCREAMING_SNAKE_CASE_ ( self ) -> Tuple: '''simple docstring''' __a = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/in_paint/overture-creations-5sI6fQgYIuo.png''' ) __a = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/in_paint/overture-creations-5sI6fQgYIuo_mask.png''' ) __a = LMSDiscreteScheduler.from_pretrained( '''runwayml/stable-diffusion-inpainting''' , subfolder='''scheduler''' , revision='''onnx''' ) __a = OnnxStableDiffusionInpaintPipeline.from_pretrained( '''runwayml/stable-diffusion-inpainting''' , revision='''onnx''' , scheduler=_snake_case , safety_checker=_snake_case , feature_extractor=_snake_case , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=_snake_case ) __a = '''A red cat sitting on a park bench''' __a = np.random.RandomState(0 ) __a = pipe( prompt=_snake_case , image=_snake_case , mask_image=_snake_case , guidance_scale=7.5 , num_inference_steps=20 , generator=_snake_case , output_type='''np''' , ) __a = output.images __a = images[0, 255:258, 255:258, -1] assert images.shape == (1, 512, 512, 3) __a = np.array([0.0086, 0.0077, 0.0083, 0.0093, 0.0107, 0.0139, 0.0094, 0.0097, 0.0125] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3
6
from __future__ import annotations import time from collections.abc import Sequence from random import randint from matplotlib import pyplot as plt def __lowerCAmelCase ( a__ , a__ , a__ ) -> tuple[int | None, int | None, float]: if not arr: return None, None, 0 if low == high: return low, high, arr[low] __a = (low + high) // 2 __a , __a , __a = max_subarray(a__ , a__ , a__ ) __a , __a , __a = max_subarray(a__ , mid + 1 , a__ ) __a , __a , __a = max_cross_sum(a__ , a__ , a__ , a__ ) if left_sum >= right_sum and left_sum >= cross_sum: return left_low, left_high, left_sum elif right_sum >= left_sum and right_sum >= cross_sum: return right_low, right_high, right_sum return cross_left, cross_right, cross_sum def __lowerCAmelCase ( a__ , a__ , a__ , a__ ) -> tuple[int, int, float]: __a , __a = float('''-inf''' ), -1 __a , __a = float('''-inf''' ), -1 __a = 0 for i in range(a__ , low - 1 , -1 ): summ += arr[i] if summ > left_sum: __a = summ __a = i __a = 0 for i in range(mid + 1 , high + 1 ): summ += arr[i] if summ > right_sum: __a = summ __a = i return max_left, max_right, (left_sum + right_sum) def __lowerCAmelCase ( a__ ) -> float: __a = [randint(1 , a__ ) for _ in range(a__ )] __a = time.time() max_subarray(a__ , 0 , input_size - 1 ) __a = time.time() return end - start def __lowerCAmelCase ( ) -> None: __a = [10, 100, 1000, 1_0000, 5_0000, 10_0000, 20_0000, 30_0000, 40_0000, 50_0000] __a = [time_max_subarray(a__ ) for input_size in input_sizes] print('''No of Inputs\t\tTime Taken''' ) for input_size, runtime in zip(a__ , a__ ): print(a__ , '''\t\t''' , a__ ) plt.plot(a__ , a__ ) plt.xlabel('''Number of Inputs''' ) plt.ylabel('''Time taken in seconds''' ) plt.show() if __name__ == "__main__": from doctest import testmod testmod()
6
1
import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, UNetaDConditionModel, VideoToVideoSDPipeline, ) from diffusers.utils import floats_tensor, is_xformers_available, skip_mps from diffusers.utils.testing_utils import enable_full_determinism, slow, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class SCREAMING_SNAKE_CASE ( lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : Any = VideoToVideoSDPipeline UpperCamelCase_ : int = TEXT_GUIDED_IMAGE_VARIATION_PARAMS.union({'''video'''} ) - {'''image''', '''width''', '''height'''} UpperCamelCase_ : List[str] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'''video'''} ) - {'''image'''} UpperCamelCase_ : List[Any] = PipelineTesterMixin.required_optional_params - {'''latents'''} UpperCamelCase_ : Optional[int] = False # No `output_type`. UpperCamelCase_ : Tuple = frozenset( [ '''num_inference_steps''', '''generator''', '''latents''', '''return_dict''', '''callback''', '''callback_steps''', ] ) def _A ( self : Any ): torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[Any] = UNetaDConditionModel( block_out_channels=(32, 64, 64, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "DownBlock3D") , up_block_types=("UpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D") , cross_attention_dim=32 , attention_head_dim=4 , ) SCREAMING_SNAKE_CASE : Any = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=UpperCAmelCase_ , set_alpha_to_one=UpperCAmelCase_ , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[int] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Any = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act="gelu" , projection_dim=512 , ) SCREAMING_SNAKE_CASE : List[str] = CLIPTextModel(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) SCREAMING_SNAKE_CASE : Optional[Any] = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, } return components def _A ( self : Union[str, Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Tuple=0 ): # 3 frames SCREAMING_SNAKE_CASE : Tuple = floats_tensor((1, 3, 3, 32, 32) , rng=random.Random(UpperCAmelCase_ ) ).to(UpperCAmelCase_ ) if str(UpperCAmelCase_ ).startswith("mps" ): SCREAMING_SNAKE_CASE : Any = torch.manual_seed(UpperCAmelCase_ ) else: SCREAMING_SNAKE_CASE : Tuple = torch.Generator(device=UpperCAmelCase_ ).manual_seed(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = { "prompt": "A painting of a squirrel eating a burger", "video": video, "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "output_type": "pt", } return inputs def _A ( self : Tuple ): SCREAMING_SNAKE_CASE : Tuple = "cpu" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE : Optional[int] = self.get_dummy_components() SCREAMING_SNAKE_CASE : int = VideoToVideoSDPipeline(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = sd_pipe.to(UpperCAmelCase_ ) sd_pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = self.get_dummy_inputs(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = "np" SCREAMING_SNAKE_CASE : Any = sd_pipe(**UpperCAmelCase_ ).frames SCREAMING_SNAKE_CASE : Dict = frames[0][-3:, -3:, -1] assert frames[0].shape == (32, 32, 3) SCREAMING_SNAKE_CASE : int = np.array([106, 117, 113, 174, 137, 112, 148, 151, 131] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def _A ( self : Any ): self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=UpperCAmelCase_ , expected_max_diff=5E-3 ) @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." ) def _A ( self : str ): pass @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." ) def _A ( self : Optional[Any] ): pass @unittest.skip(reason="`num_images_per_prompt` argument is not supported for this pipeline." ) def _A ( self : str ): pass def _A ( self : Union[str, Any] ): return super().test_progress_bar() @slow @skip_mps class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _A ( self : List[str] ): SCREAMING_SNAKE_CASE : int = VideoToVideoSDPipeline.from_pretrained("cerspense/zeroscope_v2_XL" , torch_dtype=torch.floataa ) pipe.enable_model_cpu_offload() # 10 frames SCREAMING_SNAKE_CASE : List[str] = torch.Generator(device="cpu" ).manual_seed(0 ) SCREAMING_SNAKE_CASE : List[str] = torch.randn((1, 10, 3, 1024, 576) , generator=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = video.to("cuda" ) SCREAMING_SNAKE_CASE : str = "Spiderman is surfing" SCREAMING_SNAKE_CASE : Any = pipe(UpperCAmelCase_ , video=UpperCAmelCase_ , generator=UpperCAmelCase_ , num_inference_steps=3 , output_type="pt" ).frames SCREAMING_SNAKE_CASE : Optional[int] = np.array([-1.0_458_984, -1.1_279_297, -0.9_663_086, -0.91_503_906, -0.75_097_656] ) assert np.abs(video_frames.cpu().numpy()[0, 0, 0, 0, -5:] - expected_array ).sum() < 1E-2
319
import functools def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" if not isinstance(lowercase , lowercase ) or not all(isinstance(lowercase , lowercase ) for day in days ): raise ValueError("The parameter days should be a list of integers" ) if len(lowercase ) != 3 or not all(isinstance(lowercase , lowercase ) for cost in costs ): raise ValueError("The parameter costs should be a list of three integers" ) if len(lowercase ) == 0: return 0 if min(lowercase ) <= 0: raise ValueError("All days elements should be greater than 0" ) if max(lowercase ) >= 366: raise ValueError("All days elements should be less than 366" ) SCREAMING_SNAKE_CASE : Dict = set(lowercase ) @functools.cache def dynamic_programming(lowercase ) -> int: if index > 365: return 0 if index not in days_set: return dynamic_programming(index + 1 ) return min( costs[0] + dynamic_programming(index + 1 ) , costs[1] + dynamic_programming(index + 7 ) , costs[2] + dynamic_programming(index + 30 ) , ) return dynamic_programming(1 ) if __name__ == "__main__": import doctest doctest.testmod()
319
1
"""simple docstring""" def lowercase__ ( snake_case_ :int , snake_case_ :int ): if number < 0 or shift_amount < 0: raise ValueError('''both inputs must be positive integers''' ) __UpperCAmelCase = str(bin(UpperCamelCase__ ) ) binary_number += "0" * shift_amount return binary_number def lowercase__ ( snake_case_ :int , snake_case_ :int ): if number < 0 or shift_amount < 0: raise ValueError('''both inputs must be positive integers''' ) __UpperCAmelCase = str(bin(UpperCamelCase__ ) )[2:] if shift_amount >= len(UpperCamelCase__ ): return "0b0" __UpperCAmelCase = binary_number[: len(UpperCamelCase__ ) - shift_amount] return "0b" + shifted_binary_number def lowercase__ ( snake_case_ :int , snake_case_ :int ): if number >= 0: # Get binary representation of positive number __UpperCAmelCase = '''0''' + str(bin(UpperCamelCase__ ) ).strip('''-''' )[2:] else: # Get binary (2's complement) representation of negative number __UpperCAmelCase = len(bin(UpperCamelCase__ )[3:] ) # Find 2's complement of number __UpperCAmelCase = bin(abs(UpperCamelCase__ ) - (1 << binary_number_length) )[3:] __UpperCAmelCase = ( '''1''' + '''0''' * (binary_number_length - len(UpperCamelCase__ )) + binary_number ) if shift_amount >= len(UpperCamelCase__ ): return "0b" + binary_number[0] * len(UpperCamelCase__ ) return ( "0b" + binary_number[0] * shift_amount + binary_number[: len(UpperCamelCase__ ) - shift_amount] ) if __name__ == "__main__": import doctest doctest.testmod()
332
class __lowerCAmelCase : """simple docstring""" def __init__( self , lowerCamelCase__ ) -> Any: '''simple docstring''' __lowerCamelCase = n __lowerCamelCase = [None] * self.n __lowerCamelCase = 0 # index of the first element __lowerCamelCase = 0 __lowerCamelCase = 0 def __len__( self ) -> int: '''simple docstring''' return self.size def lowercase_ ( self ) -> bool: '''simple docstring''' return self.size == 0 def lowercase_ ( self ) -> str: '''simple docstring''' return False if self.is_empty() else self.array[self.front] def lowercase_ ( self , lowerCamelCase__ ) -> Optional[Any]: '''simple docstring''' if self.size >= self.n: raise Exception('QUEUE IS FULL' ) __lowerCamelCase = data __lowerCamelCase = (self.rear + 1) % self.n self.size += 1 return self def lowercase_ ( self ) -> Tuple: '''simple docstring''' if self.size == 0: raise Exception('UNDERFLOW' ) __lowerCamelCase = self.array[self.front] __lowerCamelCase = None __lowerCamelCase = (self.front + 1) % self.n self.size -= 1 return temp
90
0
from __future__ import annotations import time import numpy as np a__: Optional[Any] = [8, 5, 9, 7] a__: Dict = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] a__: List[Any] = [ [3, 2, 1, 4], [0, 2, 5, 2], [5, 1, 0, 5], [1, 5, 3, 0], [3, 0, 3, 3], ] class SCREAMING_SNAKE_CASE__ : def __init__( self,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase,): A__ = claim_vector A__ = allocated_resources_table A__ = maximum_claim_table def UpperCamelCase ( self ): return [ sum(p_item[i] for p_item in self.__allocated_resources_table ) for i in range(len(self.__allocated_resources_table[0] ) ) ] def UpperCamelCase ( self ): return np.array(self.__claim_vector ) - np.array( self.__processes_resource_summation() ) def UpperCamelCase ( self ): return [ list(np.array(self.__maximum_claim_table[i] ) - np.array(__lowerCamelCase ) ) for i, allocated_resource in enumerate(self.__allocated_resources_table ) ] def UpperCamelCase ( self ): return {self.__need().index(__lowerCamelCase ): i for i in self.__need()} def UpperCamelCase ( self,**__lowerCamelCase ): A__ = self.__need() A__ = self.__allocated_resources_table A__ = self.__available_resources() A__ = self.__need_index_manager() for kw, val in kwargs.items(): if kw and val is True: self.__pretty_data() print('''_''' * 50 + '''\n''' ) while need_list: A__ = False for each_need in need_list: A__ = True for index, need in enumerate(__lowerCamelCase ): if need > available_resources[index]: A__ = False break if execution: A__ = True # get the original index of the process from ind_ctrl db for original_need_index, need_clone in need_index_manager.items(): if each_need == need_clone: A__ = original_need_index print(f"Process {process_number + 1} is executing." ) # remove the process run from stack need_list.remove(__lowerCamelCase ) # update available/freed resources stack A__ = np.array(__lowerCamelCase ) + np.array( alloc_resources_table[process_number] ) print( '''Updated available resource stack for processes: ''' + ''' '''.join([str(__lowerCamelCase ) for x in available_resources] ) ) break if safe: print('''The process is in a safe state.\n''' ) else: print('''System in unsafe state. Aborting...\n''' ) break def UpperCamelCase ( self ): print(''' ''' * 9 + '''Allocated Resource Table''' ) for item in self.__allocated_resources_table: print( f"P{self.__allocated_resources_table.index(__lowerCamelCase ) + 1}" + ''' '''.join(f"{it:>8}" for it in item ) + '''\n''' ) print(''' ''' * 9 + '''System Resource Table''' ) for item in self.__maximum_claim_table: print( f"P{self.__maximum_claim_table.index(__lowerCamelCase ) + 1}" + ''' '''.join(f"{it:>8}" for it in item ) + '''\n''' ) print( '''Current Usage by Active Processes: ''' + ''' '''.join(str(__lowerCamelCase ) for x in self.__claim_vector ) ) print( '''Initial Available Resources: ''' + ''' '''.join(str(__lowerCamelCase ) for x in self.__available_resources() ) ) time.sleep(1 ) if __name__ == "__main__": import doctest doctest.testmod()
39
def UpperCamelCase__( UpperCamelCase__ : int = 1_00 )->int: A__ = (n * (n + 1) // 2) ** 2 A__ = n * (n + 1) * (2 * n + 1) // 6 return sum_cubes - sum_squares if __name__ == "__main__": print(F"{solution() = }")
39
1
"""simple docstring""" from __future__ import annotations from typing import Any def _UpperCAmelCase ( __lowerCamelCase : list[Any] ) -> None: create_state_space_tree(_lowerCAmelCase , [] , 0 ) def _UpperCAmelCase ( __lowerCamelCase : list[Any] , __lowerCamelCase : list[Any] , __lowerCamelCase : int ) -> None: if index == len(_lowerCAmelCase ): print(_lowerCAmelCase ) return create_state_space_tree(_lowerCAmelCase , _lowerCAmelCase , index + 1 ) current_subsequence.append(sequence[index] ) create_state_space_tree(_lowerCAmelCase , _lowerCAmelCase , index + 1 ) current_subsequence.pop() if __name__ == "__main__": UpperCAmelCase__ = [3, 1, 2, 4] generate_all_subsequences(seq) seq.clear() seq.extend(['A', 'B', 'C']) generate_all_subsequences(seq)
288
'''simple docstring''' import io import json import fsspec import pytest from datasets import Dataset, DatasetDict, Features, NamedSplit, Value from datasets.io.json import JsonDatasetReader, JsonDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def snake_case_ ( _lowerCAmelCase : List[str] , _lowerCAmelCase : Optional[Any] ) -> Optional[int]: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('''keep_in_memory''' , [False, True] ) def snake_case_ ( _lowerCAmelCase : int , _lowerCAmelCase : Dict , _lowerCAmelCase : Optional[int] ) -> Dict: UpperCAmelCase : Dict = tmp_path / '''cache''' UpperCAmelCase : List[Any] = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): UpperCAmelCase : str = JsonDatasetReader(_lowerCAmelCase , cache_dir=_lowerCAmelCase , keep_in_memory=_lowerCAmelCase ).read() _check_json_dataset(_lowerCAmelCase , _lowerCAmelCase ) @pytest.mark.parametrize( '''features''' , [ None, {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}, {'''col_1''': '''string''', '''col_2''': '''string''', '''col_3''': '''string'''}, {'''col_1''': '''int32''', '''col_2''': '''int32''', '''col_3''': '''int32'''}, {'''col_1''': '''float32''', '''col_2''': '''float32''', '''col_3''': '''float32'''}, ] , ) def snake_case_ ( _lowerCAmelCase : Optional[int] , _lowerCAmelCase : Dict , _lowerCAmelCase : int ) -> Optional[int]: UpperCAmelCase : Any = tmp_path / '''cache''' UpperCAmelCase : Tuple = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} UpperCAmelCase : Any = features.copy() if features else default_expected_features UpperCAmelCase : List[Any] = ( Features({feature: Value(_lowerCAmelCase ) for feature, dtype in features.items()} ) if features is not None else None ) UpperCAmelCase : Dict = JsonDatasetReader(_lowerCAmelCase , features=_lowerCAmelCase , cache_dir=_lowerCAmelCase ).read() _check_json_dataset(_lowerCAmelCase , _lowerCAmelCase ) @pytest.mark.parametrize( '''features''' , [ None, {'''col_3''': '''float64''', '''col_1''': '''string''', '''col_2''': '''int64'''}, ] , ) def snake_case_ ( _lowerCAmelCase : Optional[Any] , _lowerCAmelCase : List[Any] , _lowerCAmelCase : Tuple ) -> Tuple: UpperCAmelCase : Optional[Any] = tmp_path / '''cache''' UpperCAmelCase : Optional[int] = {'''col_3''': '''float64''', '''col_1''': '''string''', '''col_2''': '''int64'''} UpperCAmelCase : int = features.copy() if features else default_expected_features UpperCAmelCase : Any = ( Features({feature: Value(_lowerCAmelCase ) for feature, dtype in features.items()} ) if features is not None else None ) UpperCAmelCase : Tuple = JsonDatasetReader(_lowerCAmelCase , features=_lowerCAmelCase , cache_dir=_lowerCAmelCase ).read() assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_3", "col_1", "col_2"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype def snake_case_ ( _lowerCAmelCase : List[str] , _lowerCAmelCase : Dict ) -> Union[str, Any]: # jsonl_312_path features are {"col_3": "float64", "col_1": "string", "col_2": "int64"} UpperCAmelCase : Tuple = {'''col_2''': '''int64''', '''col_3''': '''float64''', '''col_1''': '''string'''} UpperCAmelCase : List[str] = features.copy() UpperCAmelCase : Union[str, Any] = ( Features({feature: Value(_lowerCAmelCase ) for feature, dtype in features.items()} ) if features is not None else None ) UpperCAmelCase : Tuple = tmp_path / '''cache''' UpperCAmelCase : List[str] = JsonDatasetReader(_lowerCAmelCase , features=_lowerCAmelCase , cache_dir=_lowerCAmelCase ).read() assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_2", "col_3", "col_1"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('''split''' , [None, NamedSplit('''train''' ), '''train''', '''test'''] ) def snake_case_ ( _lowerCAmelCase : Union[str, Any] , _lowerCAmelCase : Tuple , _lowerCAmelCase : List[str] ) -> Optional[Any]: UpperCAmelCase : Any = tmp_path / '''cache''' UpperCAmelCase : List[Any] = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} UpperCAmelCase : List[Any] = JsonDatasetReader(_lowerCAmelCase , cache_dir=_lowerCAmelCase , split=_lowerCAmelCase ).read() _check_json_dataset(_lowerCAmelCase , _lowerCAmelCase ) assert dataset.split == split if split else "train" @pytest.mark.parametrize('''path_type''' , [str, list] ) def snake_case_ ( _lowerCAmelCase : List[Any] , _lowerCAmelCase : str , _lowerCAmelCase : Any ) -> Dict: if issubclass(_lowerCAmelCase , _lowerCAmelCase ): UpperCAmelCase : str = jsonl_path elif issubclass(_lowerCAmelCase , _lowerCAmelCase ): UpperCAmelCase : Dict = [jsonl_path] UpperCAmelCase : int = tmp_path / '''cache''' UpperCAmelCase : Dict = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} UpperCAmelCase : Optional[int] = JsonDatasetReader(_lowerCAmelCase , cache_dir=_lowerCAmelCase ).read() _check_json_dataset(_lowerCAmelCase , _lowerCAmelCase ) def snake_case_ ( _lowerCAmelCase : List[str] , _lowerCAmelCase : Dict , _lowerCAmelCase : Dict=("train",) ) -> Union[str, Any]: assert isinstance(_lowerCAmelCase , _lowerCAmelCase ) for split in splits: UpperCAmelCase : List[str] = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('''keep_in_memory''' , [False, True] ) def snake_case_ ( _lowerCAmelCase : int , _lowerCAmelCase : Optional[Any] , _lowerCAmelCase : str ) -> Any: UpperCAmelCase : Optional[Any] = tmp_path / '''cache''' UpperCAmelCase : List[str] = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): UpperCAmelCase : Optional[int] = JsonDatasetReader({'''train''': jsonl_path} , cache_dir=_lowerCAmelCase , keep_in_memory=_lowerCAmelCase ).read() _check_json_datasetdict(_lowerCAmelCase , _lowerCAmelCase ) @pytest.mark.parametrize( '''features''' , [ None, {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}, {'''col_1''': '''string''', '''col_2''': '''string''', '''col_3''': '''string'''}, {'''col_1''': '''int32''', '''col_2''': '''int32''', '''col_3''': '''int32'''}, {'''col_1''': '''float32''', '''col_2''': '''float32''', '''col_3''': '''float32'''}, ] , ) def snake_case_ ( _lowerCAmelCase : Optional[Any] , _lowerCAmelCase : Optional[int] , _lowerCAmelCase : Union[str, Any] ) -> int: UpperCAmelCase : Dict = tmp_path / '''cache''' UpperCAmelCase : Dict = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} UpperCAmelCase : Optional[int] = features.copy() if features else default_expected_features UpperCAmelCase : Union[str, Any] = ( Features({feature: Value(_lowerCAmelCase ) for feature, dtype in features.items()} ) if features is not None else None ) UpperCAmelCase : Tuple = JsonDatasetReader({'''train''': jsonl_path} , features=_lowerCAmelCase , cache_dir=_lowerCAmelCase ).read() _check_json_datasetdict(_lowerCAmelCase , _lowerCAmelCase ) @pytest.mark.parametrize('''split''' , [None, NamedSplit('''train''' ), '''train''', '''test'''] ) def snake_case_ ( _lowerCAmelCase : Any , _lowerCAmelCase : Optional[int] , _lowerCAmelCase : Dict ) -> Union[str, Any]: if split: UpperCAmelCase : Optional[int] = {split: jsonl_path} else: UpperCAmelCase : Any = '''train''' UpperCAmelCase : Any = {'''train''': jsonl_path, '''test''': jsonl_path} UpperCAmelCase : Tuple = tmp_path / '''cache''' UpperCAmelCase : int = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} UpperCAmelCase : Optional[Any] = JsonDatasetReader(_lowerCAmelCase , cache_dir=_lowerCAmelCase ).read() _check_json_datasetdict(_lowerCAmelCase , _lowerCAmelCase , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def snake_case_ ( _lowerCAmelCase : List[str] ) -> str: return json.load(_lowerCAmelCase ) def snake_case_ ( _lowerCAmelCase : Dict ) -> str: return [json.loads(_lowerCAmelCase ) for line in buffer] class SCREAMING_SNAKE_CASE: """simple docstring""" @pytest.mark.parametrize('''lines, load_json_function''' , [(True, load_json_lines), (False, load_json)] ) def A ( self : Union[str, Any] , __snake_case : Tuple , __snake_case : Optional[Any] , __snake_case : Optional[int] ) -> Dict: with io.BytesIO() as buffer: JsonDatasetWriter(__snake_case , __snake_case , lines=__snake_case ).write() buffer.seek(0 ) UpperCAmelCase : Union[str, Any] = load_json_function(__snake_case ) assert isinstance(__snake_case , __snake_case ) assert isinstance(exported_content[0] , __snake_case ) assert len(__snake_case ) == 10 @pytest.mark.parametrize( '''orient, container, keys, len_at''' , [ ('''records''', list, {'''tokens''', '''labels''', '''answers''', '''id'''}, None), ('''split''', dict, {'''columns''', '''data'''}, '''data'''), ('''index''', dict, set('''0123456789''' ), None), ('''columns''', dict, {'''tokens''', '''labels''', '''answers''', '''id'''}, '''tokens'''), ('''values''', list, None, None), ('''table''', dict, {'''schema''', '''data'''}, '''data'''), ] , ) def A ( self : Optional[int] , __snake_case : Optional[Any] , __snake_case : str , __snake_case : Optional[Any] , __snake_case : List[str] , __snake_case : Optional[Any] ) -> List[Any]: with io.BytesIO() as buffer: JsonDatasetWriter(__snake_case , __snake_case , lines=__snake_case , orient=__snake_case ).write() buffer.seek(0 ) UpperCAmelCase : Union[str, Any] = load_json(__snake_case ) assert isinstance(__snake_case , __snake_case ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(__snake_case , '''keys''' ) and not hasattr(exported_content[0] , '''keys''' ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(__snake_case ) == 10 @pytest.mark.parametrize('''lines, load_json_function''' , [(True, load_json_lines), (False, load_json)] ) def A ( self : str , __snake_case : str , __snake_case : str , __snake_case : int ) -> Any: with io.BytesIO() as buffer: JsonDatasetWriter(__snake_case , __snake_case , lines=__snake_case , num_proc=2 ).write() buffer.seek(0 ) UpperCAmelCase : Any = load_json_function(__snake_case ) assert isinstance(__snake_case , __snake_case ) assert isinstance(exported_content[0] , __snake_case ) assert len(__snake_case ) == 10 @pytest.mark.parametrize( '''orient, container, keys, len_at''' , [ ('''records''', list, {'''tokens''', '''labels''', '''answers''', '''id'''}, None), ('''split''', dict, {'''columns''', '''data'''}, '''data'''), ('''index''', dict, set('''0123456789''' ), None), ('''columns''', dict, {'''tokens''', '''labels''', '''answers''', '''id'''}, '''tokens'''), ('''values''', list, None, None), ('''table''', dict, {'''schema''', '''data'''}, '''data'''), ] , ) def A ( self : Any , __snake_case : int , __snake_case : Union[str, Any] , __snake_case : Optional[int] , __snake_case : Optional[Any] , __snake_case : List[str] ) -> Any: with io.BytesIO() as buffer: JsonDatasetWriter(__snake_case , __snake_case , lines=__snake_case , orient=__snake_case , num_proc=2 ).write() buffer.seek(0 ) UpperCAmelCase : List[str] = load_json(__snake_case ) assert isinstance(__snake_case , __snake_case ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(__snake_case , '''keys''' ) and not hasattr(exported_content[0] , '''keys''' ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(__snake_case ) == 10 def A ( self : List[Any] , __snake_case : str ) -> Dict: with pytest.raises(__snake_case ): with io.BytesIO() as buffer: JsonDatasetWriter(__snake_case , __snake_case , num_proc=0 ) @pytest.mark.parametrize('''compression, extension''' , [('''gzip''', '''gz'''), ('''bz2''', '''bz2'''), ('''xz''', '''xz''')] ) def A ( self : Optional[int] , __snake_case : Any , __snake_case : str , __snake_case : Union[str, Any] , __snake_case : Union[str, Any] , __snake_case : Dict ) -> Union[str, Any]: UpperCAmelCase : List[str] = tmp_path_factory.mktemp('''data''' ) / F"""test.json.{extension}""" UpperCAmelCase : List[Any] = str(shared_datadir / F"""test_file.json.{extension}""" ) JsonDatasetWriter(__snake_case , __snake_case , compression=__snake_case ).write() with fsspec.open(__snake_case , '''rb''' , compression='''infer''' ) as f: UpperCAmelCase : str = f.read() with fsspec.open(__snake_case , '''rb''' , compression='''infer''' ) as f: UpperCAmelCase : Optional[int] = f.read() assert exported_content == original_content
23
0
from __future__ import annotations from collections.abc import Generator def SCREAMING_SNAKE_CASE ( ) -> Generator[int, None, None]: UpperCamelCase__ : dict[int, int] = {} UpperCamelCase__ : List[str] = 2 while True: UpperCamelCase__ : List[str] = factor_map.pop(__lowerCAmelCase , __lowerCAmelCase ) if factor: UpperCamelCase__ : Union[str, Any] = factor + prime while x in factor_map: x += factor UpperCamelCase__ : Union[str, Any] = factor else: UpperCamelCase__ : Optional[int] = prime yield prime prime += 1 def SCREAMING_SNAKE_CASE ( __lowerCAmelCase = 1E1_0 ) -> int: UpperCamelCase__ : Union[str, Any] = sieve() UpperCamelCase__ : Dict = 1 while True: UpperCamelCase__ : Any = next(__lowerCAmelCase ) if (2 * prime * n) > limit: return n # Ignore the next prime as the reminder will be 2. next(__lowerCAmelCase ) n += 2 if __name__ == "__main__": print(solution())
196
import unittest from transformers import BigBirdConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax from transformers.models.big_bird.modeling_flax_big_bird import ( FlaxBigBirdForCausalLM, FlaxBigBirdForMaskedLM, FlaxBigBirdForMultipleChoice, FlaxBigBirdForPreTraining, FlaxBigBirdForQuestionAnswering, FlaxBigBirdForSequenceClassification, FlaxBigBirdForTokenClassification, FlaxBigBirdModel, ) class __a ( unittest.TestCase ): def __init__( self : int , SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : Dict=2 , SCREAMING_SNAKE_CASE : List[Any]=56 , SCREAMING_SNAKE_CASE : List[str]=True , SCREAMING_SNAKE_CASE : str=True , SCREAMING_SNAKE_CASE : Any=True , SCREAMING_SNAKE_CASE : int=True , SCREAMING_SNAKE_CASE : List[str]=99 , SCREAMING_SNAKE_CASE : str=32 , SCREAMING_SNAKE_CASE : Optional[int]=2 , SCREAMING_SNAKE_CASE : Union[str, Any]=2 , SCREAMING_SNAKE_CASE : Dict=7 , SCREAMING_SNAKE_CASE : List[Any]="gelu_new" , SCREAMING_SNAKE_CASE : List[Any]=0.1 , SCREAMING_SNAKE_CASE : int=0.1 , SCREAMING_SNAKE_CASE : Any=5_12 , SCREAMING_SNAKE_CASE : Dict=16 , SCREAMING_SNAKE_CASE : Union[str, Any]=2 , SCREAMING_SNAKE_CASE : Any=0.0_2 , SCREAMING_SNAKE_CASE : Optional[Any]=4 , SCREAMING_SNAKE_CASE : int="block_sparse" , SCREAMING_SNAKE_CASE : int=True , SCREAMING_SNAKE_CASE : Optional[Any]=False , SCREAMING_SNAKE_CASE : Tuple=2 , SCREAMING_SNAKE_CASE : Dict=3 , ): '''simple docstring''' UpperCamelCase__ : List[str] = parent UpperCamelCase__ : Union[str, Any] = batch_size UpperCamelCase__ : Union[str, Any] = seq_length UpperCamelCase__ : Dict = is_training UpperCamelCase__ : Optional[int] = use_attention_mask UpperCamelCase__ : List[str] = use_token_type_ids UpperCamelCase__ : Dict = use_labels UpperCamelCase__ : Optional[int] = vocab_size UpperCamelCase__ : List[Any] = hidden_size UpperCamelCase__ : List[str] = num_hidden_layers UpperCamelCase__ : List[str] = num_attention_heads UpperCamelCase__ : int = intermediate_size UpperCamelCase__ : str = hidden_act UpperCamelCase__ : Tuple = hidden_dropout_prob UpperCamelCase__ : Any = attention_probs_dropout_prob UpperCamelCase__ : str = max_position_embeddings UpperCamelCase__ : Tuple = type_vocab_size UpperCamelCase__ : Dict = type_sequence_label_size UpperCamelCase__ : Optional[Any] = initializer_range UpperCamelCase__ : Any = num_choices UpperCamelCase__ : Dict = rescale_embeddings UpperCamelCase__ : Union[str, Any] = attention_type UpperCamelCase__ : int = use_bias UpperCamelCase__ : List[Any] = block_size UpperCamelCase__ : Union[str, Any] = num_random_blocks def __lowercase ( self : List[str] ): '''simple docstring''' UpperCamelCase__ : Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase__ : Any = None if self.use_attention_mask: UpperCamelCase__ : str = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase__ : Any = None if self.use_token_type_ids: UpperCamelCase__ : int = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase__ : List[Any] = BigBirdConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , attention_type=self.attention_type , block_size=self.block_size , num_random_blocks=self.num_random_blocks , use_bias=self.use_bias , rescale_embeddings=self.rescale_embeddings , ) return config, input_ids, token_type_ids, attention_mask def __lowercase ( self : Any ): '''simple docstring''' UpperCamelCase__ : int = self.prepare_config_and_inputs() UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ : Tuple = config_and_inputs UpperCamelCase__ : int = { "input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask, } return config, inputs_dict @require_flax class __a ( A__ , unittest.TestCase ): _lowerCAmelCase : Optional[Any] = ( ( FlaxBigBirdForCausalLM, FlaxBigBirdModel, FlaxBigBirdForPreTraining, FlaxBigBirdForMaskedLM, FlaxBigBirdForMultipleChoice, FlaxBigBirdForQuestionAnswering, FlaxBigBirdForSequenceClassification, FlaxBigBirdForTokenClassification, ) if is_flax_available() else () ) _lowerCAmelCase : Dict = False _lowerCAmelCase : Optional[int] = False def __lowercase ( self : Optional[Any] ): '''simple docstring''' UpperCamelCase__ : Any = FlaxBigBirdModelTester(self ) @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def __lowercase ( self : List[Any] ): '''simple docstring''' super().test_from_pretrained_save_pretrained() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def __lowercase ( self : Optional[Any] ): '''simple docstring''' super().test_from_pretrained_with_no_automatic_init() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def __lowercase ( self : List[Any] ): '''simple docstring''' super().test_no_automatic_init() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def __lowercase ( self : Union[str, Any] ): '''simple docstring''' super().test_hidden_states_output() @slow def __lowercase ( self : str ): '''simple docstring''' for model_class_name in self.all_model_classes: UpperCamelCase__ : Any = model_class_name.from_pretrained("google/bigbird-roberta-base" ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) def __lowercase ( self : Optional[int] ): '''simple docstring''' if self.test_attn_probs: super().test_attention_outputs() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def __lowercase ( self : Optional[Any] ): '''simple docstring''' UpperCamelCase__ , UpperCamelCase__ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): UpperCamelCase__ : Dict = self._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) UpperCamelCase__ : Union[str, Any] = model_class(SCREAMING_SNAKE_CASE ) @jax.jit def model_jitted(SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : List[str]=None , **SCREAMING_SNAKE_CASE : List[Any] ): return model(input_ids=SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) with self.subTest("JIT Enabled" ): UpperCamelCase__ : Tuple = model_jitted(**SCREAMING_SNAKE_CASE ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): UpperCamelCase__ : List[Any] = model_jitted(**SCREAMING_SNAKE_CASE ).to_tuple() self.assertEqual(len(SCREAMING_SNAKE_CASE ) , len(SCREAMING_SNAKE_CASE ) ) for jitted_output, output in zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): self.assertEqual(jitted_output.shape , output.shape ) def __lowercase ( self : int , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : Union[str, Any] , SCREAMING_SNAKE_CASE : Any=1e-5 , SCREAMING_SNAKE_CASE : Tuple="outputs" , SCREAMING_SNAKE_CASE : Optional[Any]=None ): '''simple docstring''' if name.startswith("outputs.attentions" ): return else: super().check_pt_flax_outputs(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
196
1
"""simple docstring""" def _UpperCAmelCase ( __lowerCamelCase : Optional[int] ) -> Union[str, Any]: return credit_card_number.startswith(('''34''', '''35''', '''37''', '''4''', '''5''', '''6''') ) def _UpperCAmelCase ( __lowerCamelCase : Union[str, Any] ) -> str: _snake_case = credit_card_number _snake_case = 0 _snake_case = len(__lowerCamelCase ) - 2 for i in range(__lowerCamelCase , -1 , -2 ): # double the value of every second digit _snake_case = int(cc_number[i] ) digit *= 2 # If doubling of a number results in a two digit number # i.e greater than 9(e.g., 6 × 2 = 12), # then add the digits of the product (e.g., 12: 1 + 2 = 3, 15: 1 + 5 = 6), # to get a single digit number. if digit > 9: digit %= 10 digit += 1 _snake_case = cc_number[:i] + str(__lowerCamelCase ) + cc_number[i + 1 :] total += digit # Sum up the remaining digits for i in range(len(__lowerCamelCase ) - 1 , -1 , -2 ): total += int(cc_number[i] ) return total % 10 == 0 def _UpperCAmelCase ( __lowerCamelCase : List[str] ) -> Dict: _snake_case = f'''{credit_card_number} is an invalid credit card number because''' if not credit_card_number.isdigit(): print(f'''{error_message} it has nonnumerical characters.''' ) return False if not 13 <= len(__lowerCamelCase ) <= 16: print(f'''{error_message} of its length.''' ) return False if not validate_initial_digits(__lowerCamelCase ): print(f'''{error_message} of its first two digits.''' ) return False if not luhn_validation(__lowerCamelCase ): print(f'''{error_message} it fails the Luhn check.''' ) return False print(f'''{credit_card_number} is a valid credit card number.''' ) return True if __name__ == "__main__": import doctest doctest.testmod() validate_credit_card_number('4111111111111111') validate_credit_card_number('32323')
288
import socket def _a ( ): """simple docstring""" lowercase__ = socket.socket(socket.AF_INET , socket.SOCK_STREAM ) lowercase__ = socket.gethostname() lowercase__ = 1_23_12 sock.connect((host, port) ) sock.send(B'''Hello server!''' ) with open('''Received_file''' , '''wb''' ) as out_file: print('''File opened''' ) print('''Receiving data...''' ) while True: lowercase__ = sock.recv(10_24 ) if not data: break out_file.write(SCREAMING_SNAKE_CASE ) print('''Successfully received the file''' ) sock.close() print('''Connection closed''' ) if __name__ == "__main__": main()
110
0
from __future__ import annotations UpperCAmelCase_ : Optional[int] = list[list[int]] # assigning initial values to the grid UpperCAmelCase_ : Matrix = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] # a grid with no solution UpperCAmelCase_ : Matrix = [ [5, 0, 6, 5, 0, 8, 4, 0, 3], [5, 2, 0, 0, 0, 0, 0, 0, 2], [1, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] def SCREAMING_SNAKE_CASE_ ( __A : Matrix , __A : int , __A : int , __A : int ) -> bool: """simple docstring""" for i in range(9 ): if grid[row][i] == n or grid[i][column] == n: return False for i in range(3 ): for j in range(3 ): if grid[(row - row % 3) + i][(column - column % 3) + j] == n: return False return True def SCREAMING_SNAKE_CASE_ ( __A : Matrix ) -> tuple[int, int] | None: """simple docstring""" for i in range(9 ): for j in range(9 ): if grid[i][j] == 0: return i, j return None def SCREAMING_SNAKE_CASE_ ( __A : Matrix ) -> Matrix | None: """simple docstring""" if location := find_empty_location(__A ): a_ : List[Any] = location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1 , 10 ): if is_safe(__A , __A , __A , __A ): a_ : Any = digit if sudoku(__A ) is not None: return grid a_ : Optional[int] = 0 return None def SCREAMING_SNAKE_CASE_ ( __A : Matrix ) -> None: """simple docstring""" for row in grid: for cell in row: print(__A , end=' ' ) print() if __name__ == "__main__": # make a copy of grid so that you can compare with the unmodified grid for example_grid in (initial_grid, no_solution): print('\nExample grid:\n' + '=' * 20) print_solution(example_grid) print('\nExample grid solution:') UpperCAmelCase_ : int = sudoku(example_grid) if solution is not None: print_solution(solution) else: print('Cannot find a solution.')
363
def SCREAMING_SNAKE_CASE_ ( __A : list ) -> list: """simple docstring""" a_ : int = len(__A ) for _ in range(__A ): for i in range(_ % 2 , arr_size - 1 , 2 ): if arr[i + 1] < arr[i]: a_ , a_ : int = arr[i + 1], arr[i] return arr if __name__ == "__main__": UpperCAmelCase_ : int = list(range(10, 0, -1)) print(F'Original: {arr}. Sorted: {odd_even_transposition(arr)}')
120
0
'''simple docstring''' import tempfile import unittest from pathlib import Path from shutil import copyfile from transformers import BatchEncoding, MarianTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import is_sentencepiece_available, is_tf_available, is_torch_available if is_sentencepiece_available(): from transformers.models.marian.tokenization_marian import VOCAB_FILES_NAMES, save_json from ...test_tokenization_common import TokenizerTesterMixin a_ : List[Any] = get_tests_dir("""fixtures/test_sentencepiece.model""") a_ : List[str] = {"""target_lang""": """fi""", """source_lang""": """en"""} a_ : Any = """>>zh<<""" a_ : List[Any] = """Helsinki-NLP/""" if is_torch_available(): a_ : List[str] = """pt""" elif is_tf_available(): a_ : List[str] = """tf""" else: a_ : Any = """jax""" @require_sentencepiece class snake_case ( lowercase , unittest.TestCase ): """simple docstring""" _lowerCamelCase = MarianTokenizer _lowerCamelCase = False _lowerCamelCase = True def snake_case ( self ): """simple docstring""" super().setUp() lowerCamelCase_ = ["</s>", "<unk>", "▁This", "▁is", "▁a", "▁t", "est", "\u0120", "<pad>"] lowerCamelCase_ = dict(zip(UpperCamelCase , range(len(UpperCamelCase ) ) ) ) lowerCamelCase_ = Path(self.tmpdirname ) save_json(UpperCamelCase , save_dir / VOCAB_FILES_NAMES["vocab"] ) save_json(UpperCamelCase , save_dir / VOCAB_FILES_NAMES["tokenizer_config_file"] ) if not (save_dir / VOCAB_FILES_NAMES["source_spm"]).exists(): copyfile(UpperCamelCase , save_dir / VOCAB_FILES_NAMES["source_spm"] ) copyfile(UpperCamelCase , save_dir / VOCAB_FILES_NAMES["target_spm"] ) lowerCamelCase_ = MarianTokenizer.from_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ) def snake_case ( self , **UpperCamelCase ): """simple docstring""" return MarianTokenizer.from_pretrained(self.tmpdirname , **UpperCamelCase ) def snake_case ( self , UpperCamelCase ): """simple docstring""" return ( "This is a test", "This is a test", ) def snake_case ( self ): """simple docstring""" lowerCamelCase_ = "</s>" lowerCamelCase_ = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCamelCase ) , UpperCamelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCamelCase ) , UpperCamelCase ) def snake_case ( self ): """simple docstring""" lowerCamelCase_ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "</s>" ) self.assertEqual(vocab_keys[1] , "<unk>" ) self.assertEqual(vocab_keys[-1] , "<pad>" ) self.assertEqual(len(UpperCamelCase ) , 9 ) def snake_case ( self ): """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 9 ) def snake_case ( self ): """simple docstring""" lowerCamelCase_ = MarianTokenizer.from_pretrained(f'''{ORG_NAME}opus-mt-en-de''' ) lowerCamelCase_ = en_de_tokenizer(["I am a small frog"] , return_tensors=UpperCamelCase ) self.assertIsInstance(UpperCamelCase , UpperCamelCase ) lowerCamelCase_ = [38, 121, 14, 697, 3_8848, 0] self.assertListEqual(UpperCamelCase , batch.input_ids[0] ) lowerCamelCase_ = tempfile.mkdtemp() en_de_tokenizer.save_pretrained(UpperCamelCase ) lowerCamelCase_ = [x.name for x in Path(UpperCamelCase ).glob("*" )] self.assertIn("source.spm" , UpperCamelCase ) MarianTokenizer.from_pretrained(UpperCamelCase ) def snake_case ( self ): """simple docstring""" lowerCamelCase_ = self.get_tokenizer() lowerCamelCase_ = tok( ["I am a small frog" * 1000, "I am a small frog"] , padding=UpperCamelCase , truncation=UpperCamelCase , return_tensors=UpperCamelCase ) self.assertIsInstance(UpperCamelCase , UpperCamelCase ) self.assertEqual(batch.input_ids.shape , (2, 512) ) def snake_case ( self ): """simple docstring""" lowerCamelCase_ = self.get_tokenizer() lowerCamelCase_ = tok(["I am a tiny frog", "I am a small frog"] , padding=UpperCamelCase , return_tensors=UpperCamelCase ) self.assertIsInstance(UpperCamelCase , UpperCamelCase ) self.assertEqual(batch_smaller.input_ids.shape , (2, 10) ) @slow def snake_case ( self ): """simple docstring""" # fmt: off lowerCamelCase_ = {"input_ids": [[4_3495, 462, 20, 4_2164, 1369, 52, 464, 132, 1703, 492, 13, 7491, 3_8999, 6, 8, 464, 132, 1703, 492, 13, 4669, 3_7867, 13, 7525, 27, 1593, 988, 13, 3_3972, 7029, 6, 20, 8251, 383, 2, 270, 5866, 3788, 2, 2353, 8251, 1_2338, 2, 1_3958, 387, 2, 3629, 6953, 188, 2900, 2, 1_3958, 8011, 1_1501, 23, 8460, 4073, 3_4009, 20, 435, 1_1439, 27, 8, 8460, 4073, 6004, 20, 9988, 375, 27, 33, 266, 1945, 1076, 1350, 3_7867, 3288, 5, 577, 1076, 4374, 8, 5082, 5, 2_6453, 257, 556, 403, 2, 242, 132, 383, 316, 492, 8, 1_0767, 6, 316, 304, 4239, 3, 0], [148, 1_5722, 19, 1839, 12, 1350, 13, 2_2327, 5082, 5418, 4_7567, 3_5938, 59, 318, 1_9552, 108, 2183, 54, 1_4976, 4835, 32, 547, 1114, 8, 315, 2417, 5, 92, 1_9088, 3, 0, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100], [36, 6395, 1_2570, 3_9147, 1_1597, 6, 266, 4, 4_5405, 7296, 3, 0, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=UpperCamelCase , model_name="Helsinki-NLP/opus-mt-en-de" , revision="1a8c2263da11e68e50938f97e10cd57820bd504c" , decode_kwargs={"use_source_tokenizer": True} , ) def snake_case ( self ): """simple docstring""" lowerCamelCase_ = MarianTokenizer.from_pretrained("hf-internal-testing/test-marian-two-vocabs" ) lowerCamelCase_ = "Tämä on testi" lowerCamelCase_ = "This is a test" lowerCamelCase_ = [76, 7, 2047, 2] lowerCamelCase_ = [69, 12, 11, 940, 2] lowerCamelCase_ = tokenizer(UpperCamelCase ).input_ids self.assertListEqual(UpperCamelCase , UpperCamelCase ) lowerCamelCase_ = tokenizer(text_target=UpperCamelCase ).input_ids self.assertListEqual(UpperCamelCase , UpperCamelCase ) lowerCamelCase_ = tokenizer.decode(UpperCamelCase , skip_special_tokens=UpperCamelCase ) self.assertEqual(UpperCamelCase , UpperCamelCase )
55
'''simple docstring''' import requests from bsa import BeautifulSoup def __lowerCamelCase ( __snake_case : str, __snake_case : dict ) -> str: """simple docstring""" A__ : Optional[Any] =BeautifulSoup(requests.get(__snake_case, params=__snake_case ).content, """html.parser""" ) A__ : List[str] =soup.find("""div""", attrs={"""class""": """gs_ri"""} ) A__ : Tuple =div.find("""div""", attrs={"""class""": """gs_fl"""} ).find_all("""a""" ) return anchors[2].get_text() if __name__ == "__main__": __snake_case : Optional[Any] = { 'title': ( 'Precisely geometry controlled microsupercapacitors for ultrahigh areal ' 'capacitance, volumetric capacitance, and energy density' ), 'journal': 'Chem. Mater.', 'volume': 30, 'pages': '3979-3990', 'year': 2018, 'hl': 'en', } print(get_citation('https://scholar.google.com/scholar_lookup', params=params))
134
0
import math from datetime import datetime, timedelta def _snake_case( SCREAMING_SNAKE_CASE__ ) -> datetime: lowercase : Any = year % 19 lowercase : Optional[int] = year % 4 lowercase : Any = year % 7 lowercase : str = math.floor(year / 100 ) lowercase : List[str] = math.floor((13 + 8 * leap_day_inhibits) / 25 ) lowercase : Tuple = leap_day_inhibits / 4 lowercase : Any = ( 15 - lunar_orbit_correction + leap_day_inhibits - leap_day_reinstall_number ) % 30 lowercase : Union[str, Any] = (4 + leap_day_inhibits - leap_day_reinstall_number) % 7 # days to be added to March 21 lowercase : str = (19 * metonic_cycle + secular_moon_shift) % 30 # PHM -> Paschal Full Moon lowercase : List[Any] = ( 2 * julian_leap_year + 4 * non_leap_year + 6 * days_to_add + century_starting_point ) % 7 if days_to_add == 29 and days_from_phm_to_sunday == 6: return datetime(SCREAMING_SNAKE_CASE__ , 4 , 19 ) elif days_to_add == 28 and days_from_phm_to_sunday == 6: return datetime(SCREAMING_SNAKE_CASE__ , 4 , 18 ) else: return datetime(SCREAMING_SNAKE_CASE__ , 3 , 22 ) + timedelta( days=int(days_to_add + days_from_phm_to_sunday ) ) if __name__ == "__main__": for year in (1994, 2000, 2010, 2021, 2023): lowercase : List[str] = """will be""" if year > datetime.now().year else """was""" print(F'''Easter in {year} {tense} {gauss_easter(year)}''')
285
def _snake_case( SCREAMING_SNAKE_CASE__ ) -> int: assert ( isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and number_of_steps > 0 ), f"number_of_steps needs to be positive integer, your input {number_of_steps}" if number_of_steps == 1: return 1 lowercase , lowercase : Tuple = 1, 1 for _ in range(number_of_steps - 1 ): lowercase , lowercase : str = current + previous, current return current if __name__ == "__main__": import doctest doctest.testmod()
285
1
"""simple docstring""" def __magic_name__ ( lowercase , lowercase , lowercase , lowercase ): # 1. Validate that path exists between current and next vertices if graph[path[curr_ind - 1]][next_ver] == 0: return False # 2. Validate that next vertex is not already in path return not any(vertex == next_ver for vertex in path ) def __magic_name__ ( lowercase , lowercase , lowercase ): # Base Case if curr_ind == len(lowercase ): # return whether path exists between current and starting vertices return graph[path[curr_ind - 1]][path[0]] == 1 # Recursive Step for next_ver in range(0 , len(lowercase ) ): if valid_connection(lowercase , lowercase , lowercase , lowercase ): # Insert current vertex into path as next transition SCREAMING_SNAKE_CASE_: int =next_ver # Validate created path if util_hamilton_cycle(lowercase , lowercase , curr_ind + 1 ): return True # Backtrack SCREAMING_SNAKE_CASE_: Optional[Any] =-1 return False def __magic_name__ ( lowercase , lowercase = 0 ): SCREAMING_SNAKE_CASE_: Tuple =[-1] * (len(lowercase ) + 1) # initialize start and end of path with starting index SCREAMING_SNAKE_CASE_: int =start_index # evaluate and if we find answer return path either return empty array return path if util_hamilton_cycle(lowercase , lowercase , 1 ) else []
173
"""simple docstring""" from maths.prime_factors import prime_factors def __magic_name__ ( lowercase ): if not isinstance(lowercase , lowercase ): SCREAMING_SNAKE_CASE_: int =f'''Input value of [number={number}] must be an integer''' raise TypeError(lowercase ) if number < 1: raise ValueError("""Input must be a positive integer""" ) return -1 if len(prime_factors(lowercase ) ) % 2 else 1 if __name__ == "__main__": import doctest doctest.testmod()
173
1
"""simple docstring""" import json import logging import os import socket import git import numpy as np import torch logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - PID: %(process)d - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO, ) _UpperCamelCase : Optional[Any] = logging.getLogger(__name__) def snake_case (A_ :str ): '''simple docstring''' a : Optional[int] = git.Repo(search_parent_directories=A_ ) a : Tuple = { 'repo_id': str(A_ ), 'repo_sha': str(repo.head.object.hexsha ), 'repo_branch': str(repo.active_branch ), } with open(os.path.join(A_ , 'git_log.json' ) , 'w' ) as f: json.dump(A_ , A_ , indent=4 ) def snake_case (A_ :List[Any] ): '''simple docstring''' if params.n_gpu <= 0: a : Optional[Any] = 0 a : str = -1 a : Optional[int] = True a : Optional[int] = False return assert torch.cuda.is_available() logger.info('Initializing GPUs' ) if params.n_gpu > 1: assert params.local_rank != -1 a : Union[str, Any] = int(os.environ['WORLD_SIZE'] ) a : Optional[Any] = int(os.environ['N_GPU_NODE'] ) a : Union[str, Any] = int(os.environ['RANK'] ) # number of nodes / node ID a : Optional[Any] = params.world_size // params.n_gpu_per_node a : Dict = params.global_rank // params.n_gpu_per_node a : Dict = True assert params.n_nodes == int(os.environ['N_NODES'] ) assert params.node_id == int(os.environ['NODE_RANK'] ) # local job (single GPU) else: assert params.local_rank == -1 a : Optional[Any] = 1 a : Any = 0 a : Union[str, Any] = 0 a : Dict = 0 a : str = 1 a : Dict = 1 a : Union[str, Any] = False # sanity checks assert params.n_nodes >= 1 assert 0 <= params.node_id < params.n_nodes assert 0 <= params.local_rank <= params.global_rank < params.world_size assert params.world_size == params.n_nodes * params.n_gpu_per_node # define whether this is the master process / if we are in multi-node distributed mode a : str = params.node_id == 0 and params.local_rank == 0 a : Optional[int] = params.n_nodes > 1 # summary a : Optional[Any] = f'''--- Global rank: {params.global_rank} - ''' logger.info(PREFIX + 'Number of nodes: %i' % params.n_nodes ) logger.info(PREFIX + 'Node ID : %i' % params.node_id ) logger.info(PREFIX + 'Local rank : %i' % params.local_rank ) logger.info(PREFIX + 'World size : %i' % params.world_size ) logger.info(PREFIX + 'GPUs per node : %i' % params.n_gpu_per_node ) logger.info(PREFIX + 'Master : %s' % str(params.is_master ) ) logger.info(PREFIX + 'Multi-node : %s' % str(params.multi_node ) ) logger.info(PREFIX + 'Multi-GPU : %s' % str(params.multi_gpu ) ) logger.info(PREFIX + 'Hostname : %s' % socket.gethostname() ) # set GPU device torch.cuda.set_device(params.local_rank ) # initialize multi-GPU if params.multi_gpu: logger.info('Initializing PyTorch distributed' ) torch.distributed.init_process_group( init_method='env://' , backend='nccl' , ) def snake_case (A_ :Optional[int] ): '''simple docstring''' np.random.seed(args.seed ) torch.manual_seed(args.seed ) if args.n_gpu > 0: torch.cuda.manual_seed_all(args.seed )
366
"""simple docstring""" import argparse import collections import json import os import re import string import sys import numpy as np _UpperCamelCase : Optional[Any] = re.compile(r'\b(a|an|the)\b', re.UNICODE) _UpperCamelCase : str = None def snake_case (): '''simple docstring''' a : Any = argparse.ArgumentParser('Official evaluation script for SQuAD version 2.0.' ) parser.add_argument('data_file' , metavar='data.json' , help='Input data JSON file.' ) parser.add_argument('pred_file' , metavar='pred.json' , help='Model predictions.' ) parser.add_argument( '--out-file' , '-o' , metavar='eval.json' , help='Write accuracy metrics to file (default is stdout).' ) parser.add_argument( '--na-prob-file' , '-n' , metavar='na_prob.json' , help='Model estimates of probability of no answer.' ) parser.add_argument( '--na-prob-thresh' , '-t' , type=A_ , default=1.0 , help='Predict "" if no-answer probability exceeds this (default = 1.0).' , ) parser.add_argument( '--out-image-dir' , '-p' , metavar='out_images' , default=A_ , help='Save precision-recall curves to directory.' ) parser.add_argument('--verbose' , '-v' , action='store_true' ) if len(sys.argv ) == 1: parser.print_help() sys.exit(1 ) return parser.parse_args() def snake_case (A_ :Optional[int] ): '''simple docstring''' a : str = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: a : Optional[int] = bool(qa['answers']['text'] ) return qid_to_has_ans def snake_case (A_ :List[Any] ): '''simple docstring''' def remove_articles(A_ :str ): return ARTICLES_REGEX.sub(' ' , A_ ) def white_space_fix(A_ :str ): return " ".join(text.split() ) def remove_punc(A_ :Dict ): a : int = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(A_ :Union[str, Any] ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(A_ ) ) ) ) def snake_case (A_ :str ): '''simple docstring''' if not s: return [] return normalize_answer(A_ ).split() def snake_case (A_ :int , A_ :Union[str, Any] ): '''simple docstring''' return int(normalize_answer(A_ ) == normalize_answer(A_ ) ) def snake_case (A_ :Optional[int] , A_ :str ): '''simple docstring''' a : int = get_tokens(A_ ) a : Tuple = get_tokens(A_ ) a : List[Any] = collections.Counter(A_ ) & collections.Counter(A_ ) a : Dict = sum(common.values() ) if len(A_ ) == 0 or len(A_ ) == 0: # If either is no-answer, then F1 is 1 if they agree, 0 otherwise return int(gold_toks == pred_toks ) if num_same == 0: return 0 a : List[Any] = 1.0 * num_same / len(A_ ) a : Optional[Any] = 1.0 * num_same / len(A_ ) a : Union[str, Any] = (2 * precision * recall) / (precision + recall) return fa def snake_case (A_ :Any , A_ :Dict ): '''simple docstring''' a : Union[str, Any] = {} a : List[Any] = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: a : str = qa['id'] a : Dict = [t for t in qa['answers']['text'] if normalize_answer(A_ )] if not gold_answers: # For unanswerable questions, only correct answer is empty string a : Dict = [''] if qid not in preds: print(f'''Missing prediction for {qid}''' ) continue a : Optional[Any] = preds[qid] # Take max over all gold answers a : str = max(compute_exact(A_ , A_ ) for a in gold_answers ) a : List[Any] = max(compute_fa(A_ , A_ ) for a in gold_answers ) return exact_scores, fa_scores def snake_case (A_ :Union[str, Any] , A_ :List[Any] , A_ :List[Any] , A_ :Dict ): '''simple docstring''' a : List[str] = {} for qid, s in scores.items(): a : Union[str, Any] = na_probs[qid] > na_prob_thresh if pred_na: a : int = float(not qid_to_has_ans[qid] ) else: a : Union[str, Any] = s return new_scores def snake_case (A_ :Tuple , A_ :int , A_ :Tuple=None ): '''simple docstring''' if not qid_list: a : Optional[int] = len(A_ ) return collections.OrderedDict( [ ('exact', 100.0 * sum(exact_scores.values() ) / total), ('f1', 100.0 * sum(fa_scores.values() ) / total), ('total', total), ] ) else: a : List[Any] = len(A_ ) return collections.OrderedDict( [ ('exact', 100.0 * sum(exact_scores[k] for k in qid_list ) / total), ('f1', 100.0 * sum(fa_scores[k] for k in qid_list ) / total), ('total', total), ] ) def snake_case (A_ :str , A_ :Dict , A_ :List[Any] ): '''simple docstring''' for k in new_eval: a : Union[str, Any] = new_eval[k] def snake_case (A_ :Optional[Any] , A_ :Any , A_ :Dict , A_ :Optional[int] ): '''simple docstring''' plt.step(A_ , A_ , color='b' , alpha=0.2 , where='post' ) plt.fill_between(A_ , A_ , step='post' , alpha=0.2 , color='b' ) plt.xlabel('Recall' ) plt.ylabel('Precision' ) plt.xlim([0.0, 1.05] ) plt.ylim([0.0, 1.05] ) plt.title(A_ ) plt.savefig(A_ ) plt.clf() def snake_case (A_ :List[str] , A_ :str , A_ :Any , A_ :Any , A_ :List[Any]=None , A_ :Union[str, Any]=None ): '''simple docstring''' a : Optional[int] = sorted(A_ , key=lambda A_ : na_probs[k] ) a : Tuple = 0.0 a : Tuple = 1.0 a : Any = 0.0 a : int = [1.0] a : int = [0.0] a : str = 0.0 for i, qid in enumerate(A_ ): if qid_to_has_ans[qid]: true_pos += scores[qid] a : Tuple = true_pos / float(i + 1 ) a : Any = true_pos / float(A_ ) if i == len(A_ ) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]: # i.e., if we can put a threshold after this point avg_prec += cur_p * (cur_r - recalls[-1]) precisions.append(A_ ) recalls.append(A_ ) if out_image: plot_pr_curve(A_ , A_ , A_ , A_ ) return {"ap": 100.0 * avg_prec} def snake_case (A_ :Optional[int] , A_ :Any , A_ :List[Any] , A_ :int , A_ :int , A_ :List[str] ): '''simple docstring''' if out_image_dir and not os.path.exists(A_ ): os.makedirs(A_ ) a : List[str] = sum(1 for v in qid_to_has_ans.values() if v ) if num_true_pos == 0: return a : List[str] = make_precision_recall_eval( A_ , A_ , A_ , A_ , out_image=os.path.join(A_ , 'pr_exact.png' ) , title='Precision-Recall curve for Exact Match score' , ) a : Optional[Any] = make_precision_recall_eval( A_ , A_ , A_ , A_ , out_image=os.path.join(A_ , 'pr_f1.png' ) , title='Precision-Recall curve for F1 score' , ) a : Any = {k: float(A_ ) for k, v in qid_to_has_ans.items()} a : Optional[int] = make_precision_recall_eval( A_ , A_ , A_ , A_ , out_image=os.path.join(A_ , 'pr_oracle.png' ) , title='Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)' , ) merge_eval(A_ , A_ , 'pr_exact' ) merge_eval(A_ , A_ , 'pr_f1' ) merge_eval(A_ , A_ , 'pr_oracle' ) def snake_case (A_ :List[str] , A_ :List[str] , A_ :List[Any] , A_ :str ): '''simple docstring''' if not qid_list: return a : List[Any] = [na_probs[k] for k in qid_list] a : List[str] = np.ones_like(A_ ) / float(len(A_ ) ) plt.hist(A_ , weights=A_ , bins=2_0 , range=(0.0, 1.0) ) plt.xlabel('Model probability of no-answer' ) plt.ylabel('Proportion of dataset' ) plt.title(f'''Histogram of no-answer probability: {name}''' ) plt.savefig(os.path.join(A_ , f'''na_prob_hist_{name}.png''' ) ) plt.clf() def snake_case (A_ :Tuple , A_ :Tuple , A_ :List[str] , A_ :List[str] ): '''simple docstring''' a : Any = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k] ) a : List[str] = num_no_ans a : List[str] = cur_score a : str = 0.0 a : Union[str, Any] = sorted(A_ , key=lambda A_ : na_probs[k] ) for i, qid in enumerate(A_ ): if qid not in scores: continue if qid_to_has_ans[qid]: a : Optional[int] = scores[qid] else: if preds[qid]: a : Dict = -1 else: a : Optional[Any] = 0 cur_score += diff if cur_score > best_score: a : List[Any] = cur_score a : str = na_probs[qid] return 100.0 * best_score / len(A_ ), best_thresh def snake_case (A_ :List[Any] , A_ :List[Any] , A_ :str , A_ :int , A_ :Optional[Any] , A_ :Union[str, Any] ): '''simple docstring''' a, a : Any = find_best_thresh(A_ , A_ , A_ , A_ ) a, a : List[Any] = find_best_thresh(A_ , A_ , A_ , A_ ) a : Union[str, Any] = best_exact a : List[Any] = exact_thresh a : List[str] = best_fa a : Any = fa_thresh def snake_case (): '''simple docstring''' with open(OPTS.data_file ) as f: a : List[str] = json.load(A_ ) a : Tuple = dataset_json['data'] with open(OPTS.pred_file ) as f: a : List[Any] = json.load(A_ ) if OPTS.na_prob_file: with open(OPTS.na_prob_file ) as f: a : int = json.load(A_ ) else: a : List[Any] = {k: 0.0 for k in preds} a : List[str] = make_qid_to_has_ans(A_ ) # maps qid to True/False a : Union[str, Any] = [k for k, v in qid_to_has_ans.items() if v] a : Dict = [k for k, v in qid_to_has_ans.items() if not v] a, a : List[Any] = get_raw_scores(A_ , A_ ) a : Any = apply_no_ans_threshold(A_ , A_ , A_ , OPTS.na_prob_thresh ) a : Any = apply_no_ans_threshold(A_ , A_ , A_ , OPTS.na_prob_thresh ) a : Union[str, Any] = make_eval_dict(A_ , A_ ) if has_ans_qids: a : Dict = make_eval_dict(A_ , A_ , qid_list=A_ ) merge_eval(A_ , A_ , 'HasAns' ) if no_ans_qids: a : Tuple = make_eval_dict(A_ , A_ , qid_list=A_ ) merge_eval(A_ , A_ , 'NoAns' ) if OPTS.na_prob_file: find_all_best_thresh(A_ , A_ , A_ , A_ , A_ , A_ ) if OPTS.na_prob_file and OPTS.out_image_dir: run_precision_recall_analysis(A_ , A_ , A_ , A_ , A_ , OPTS.out_image_dir ) histogram_na_prob(A_ , A_ , OPTS.out_image_dir , 'hasAns' ) histogram_na_prob(A_ , A_ , OPTS.out_image_dir , 'noAns' ) if OPTS.out_file: with open(OPTS.out_file , 'w' ) as f: json.dump(A_ , A_ ) else: print(json.dumps(A_ , indent=2 ) ) if __name__ == "__main__": _UpperCamelCase : Tuple = parse_args() if OPTS.out_image_dir: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt main()
186
0
import argparse import gc import json import os import shutil import warnings import torch from transformers import LlamaConfig, LlamaForCausalLM, LlamaTokenizer try: from transformers import LlamaTokenizerFast except ImportError as e: warnings.warn(e) warnings.warn( '''The converted tokenizer will be the `slow` tokenizer. To use the fast, update your `tokenizers` library and re-run the tokenizer conversion''' ) UpperCAmelCase__ = None UpperCAmelCase__ = { '''7B''': 1_1008, '''13B''': 1_3824, '''30B''': 1_7920, '''65B''': 2_2016, '''70B''': 2_8672, } UpperCAmelCase__ = { '''7B''': 1, '''7Bf''': 1, '''13B''': 2, '''13Bf''': 2, '''30B''': 4, '''65B''': 8, '''70B''': 8, '''70Bf''': 8, } def UpperCAmelCase_ ( __snake_case , __snake_case=1 , __snake_case=256 ) -> Optional[int]: """simple docstring""" return multiple_of * ((int(ffn_dim_multiplier * int(8 * n / 3 ) ) + multiple_of - 1) // multiple_of) def UpperCAmelCase_ ( __snake_case ) -> str: """simple docstring""" with open(__snake_case , '''r''' ) as f: return json.load(__snake_case ) def UpperCAmelCase_ ( __snake_case , __snake_case ) -> List[str]: """simple docstring""" with open(__snake_case , '''w''' ) as f: json.dump(__snake_case , __snake_case ) def UpperCAmelCase_ ( __snake_case , __snake_case , __snake_case , __snake_case=True ) -> Optional[int]: """simple docstring""" os.makedirs(__snake_case , exist_ok=__snake_case ) _lowercase =os.path.join(__snake_case , '''tmp''' ) os.makedirs(__snake_case , exist_ok=__snake_case ) _lowercase =read_json(os.path.join(__snake_case , '''params.json''' ) ) _lowercase =NUM_SHARDS[model_size] _lowercase =params['''n_layers'''] _lowercase =params['''n_heads'''] _lowercase =n_heads // num_shards _lowercase =params['''dim'''] _lowercase =dim // n_heads _lowercase =1_00_00.0 _lowercase =1.0 / (base ** (torch.arange(0 , __snake_case , 2 ).float() / dims_per_head)) if "n_kv_heads" in params: _lowercase =params['''n_kv_heads'''] # for GQA / MQA _lowercase =n_heads_per_shard // num_key_value_heads _lowercase =dim // num_key_value_heads else: # compatibility with other checkpoints _lowercase =n_heads _lowercase =n_heads_per_shard _lowercase =dim # permute for sliced rotary def permute(__snake_case , __snake_case=n_heads , __snake_case=dim , __snake_case=dim ): return w.view(__snake_case , dima // n_heads // 2 , 2 , __snake_case ).transpose(1 , 2 ).reshape(__snake_case , __snake_case ) print(F"Fetching all parameters from the checkpoint at {input_base_path}." ) # Load weights if model_size == "7B": # Not sharded # (The sharded implementation would also work, but this is simpler.) _lowercase =torch.load(os.path.join(__snake_case , '''consolidated.00.pth''' ) , map_location='''cpu''' ) else: # Sharded _lowercase =[ torch.load(os.path.join(__snake_case , F"consolidated.{i:02d}.pth" ) , map_location='''cpu''' ) for i in range(__snake_case ) ] _lowercase =0 _lowercase ={'''weight_map''': {}} for layer_i in range(__snake_case ): _lowercase =F"pytorch_model-{layer_i + 1}-of-{n_layers + 1}.bin" if model_size == "7B": # Unsharded _lowercase ={ F"model.layers.{layer_i}.self_attn.q_proj.weight": permute( loaded[F"layers.{layer_i}.attention.wq.weight"] ), F"model.layers.{layer_i}.self_attn.k_proj.weight": permute( loaded[F"layers.{layer_i}.attention.wk.weight"] ), F"model.layers.{layer_i}.self_attn.v_proj.weight": loaded[F"layers.{layer_i}.attention.wv.weight"], F"model.layers.{layer_i}.self_attn.o_proj.weight": loaded[F"layers.{layer_i}.attention.wo.weight"], F"model.layers.{layer_i}.mlp.gate_proj.weight": loaded[F"layers.{layer_i}.feed_forward.w1.weight"], F"model.layers.{layer_i}.mlp.down_proj.weight": loaded[F"layers.{layer_i}.feed_forward.w2.weight"], F"model.layers.{layer_i}.mlp.up_proj.weight": loaded[F"layers.{layer_i}.feed_forward.w3.weight"], F"model.layers.{layer_i}.input_layernorm.weight": loaded[F"layers.{layer_i}.attention_norm.weight"], F"model.layers.{layer_i}.post_attention_layernorm.weight": loaded[F"layers.{layer_i}.ffn_norm.weight"], } else: # Sharded # Note that attention.w{q,k,v,o}, feed_fordward.w[1,2,3], attention_norm.weight and ffn_norm.weight share # the same storage object, saving attention_norm and ffn_norm will save other weights too, which is # redundant as other weights will be stitched from multiple shards. To avoid that, they are cloned. _lowercase ={ F"model.layers.{layer_i}.input_layernorm.weight": loaded[0][ F"layers.{layer_i}.attention_norm.weight" ].clone(), F"model.layers.{layer_i}.post_attention_layernorm.weight": loaded[0][ F"layers.{layer_i}.ffn_norm.weight" ].clone(), } _lowercase =permute( torch.cat( [ loaded[i][F"layers.{layer_i}.attention.wq.weight"].view(__snake_case , __snake_case , __snake_case ) for i in range(__snake_case ) ] , dim=0 , ).reshape(__snake_case , __snake_case ) ) _lowercase =permute( torch.cat( [ loaded[i][F"layers.{layer_i}.attention.wk.weight"].view( __snake_case , __snake_case , __snake_case ) for i in range(__snake_case ) ] , dim=0 , ).reshape(__snake_case , __snake_case ) , __snake_case , __snake_case , __snake_case , ) _lowercase =torch.cat( [ loaded[i][F"layers.{layer_i}.attention.wv.weight"].view( __snake_case , __snake_case , __snake_case ) for i in range(__snake_case ) ] , dim=0 , ).reshape(__snake_case , __snake_case ) _lowercase =torch.cat( [loaded[i][F"layers.{layer_i}.attention.wo.weight"] for i in range(__snake_case )] , dim=1 ) _lowercase =torch.cat( [loaded[i][F"layers.{layer_i}.feed_forward.w1.weight"] for i in range(__snake_case )] , dim=0 ) _lowercase =torch.cat( [loaded[i][F"layers.{layer_i}.feed_forward.w2.weight"] for i in range(__snake_case )] , dim=1 ) _lowercase =torch.cat( [loaded[i][F"layers.{layer_i}.feed_forward.w3.weight"] for i in range(__snake_case )] , dim=0 ) _lowercase =inv_freq for k, v in state_dict.items(): _lowercase =filename param_count += v.numel() torch.save(__snake_case , os.path.join(__snake_case , __snake_case ) ) _lowercase =F"pytorch_model-{n_layers + 1}-of-{n_layers + 1}.bin" if model_size == "7B": # Unsharded _lowercase ={ '''model.embed_tokens.weight''': loaded['''tok_embeddings.weight'''], '''model.norm.weight''': loaded['''norm.weight'''], '''lm_head.weight''': loaded['''output.weight'''], } else: _lowercase ={ '''model.norm.weight''': loaded[0]['''norm.weight'''], '''model.embed_tokens.weight''': torch.cat( [loaded[i]['''tok_embeddings.weight'''] for i in range(__snake_case )] , dim=1 ), '''lm_head.weight''': torch.cat([loaded[i]['''output.weight'''] for i in range(__snake_case )] , dim=0 ), } for k, v in state_dict.items(): _lowercase =filename param_count += v.numel() torch.save(__snake_case , os.path.join(__snake_case , __snake_case ) ) # Write configs _lowercase ={'''total_size''': param_count * 2} write_json(__snake_case , os.path.join(__snake_case , '''pytorch_model.bin.index.json''' ) ) _lowercase =params['''ffn_dim_multiplier'''] if '''ffn_dim_multiplier''' in params else 1 _lowercase =params['''multiple_of'''] if '''multiple_of''' in params else 256 _lowercase =LlamaConfig( hidden_size=__snake_case , intermediate_size=compute_intermediate_size(__snake_case , __snake_case , __snake_case ) , num_attention_heads=params['''n_heads'''] , num_hidden_layers=params['''n_layers'''] , rms_norm_eps=params['''norm_eps'''] , num_key_value_heads=__snake_case , ) config.save_pretrained(__snake_case ) # Make space so we can load the model properly now. del state_dict del loaded gc.collect() print('''Loading the checkpoint in a Llama model.''' ) _lowercase =LlamaForCausalLM.from_pretrained(__snake_case , torch_dtype=torch.floataa , low_cpu_mem_usage=__snake_case ) # Avoid saving this as part of the config. del model.config._name_or_path print('''Saving in the Transformers format.''' ) model.save_pretrained(__snake_case , safe_serialization=__snake_case ) shutil.rmtree(__snake_case ) def UpperCAmelCase_ ( __snake_case , __snake_case ) -> List[str]: """simple docstring""" _lowercase =LlamaTokenizer if LlamaTokenizerFast is None else LlamaTokenizerFast print(F"Saving a {tokenizer_class.__name__} to {tokenizer_path}." ) _lowercase =tokenizer_class(__snake_case ) tokenizer.save_pretrained(__snake_case ) def UpperCAmelCase_ ( ) -> Tuple: """simple docstring""" _lowercase =argparse.ArgumentParser() parser.add_argument( '''--input_dir''' , help='''Location of LLaMA weights, which contains tokenizer.model and model folders''' , ) parser.add_argument( '''--model_size''' , choices=['''7B''', '''7Bf''', '''13B''', '''13Bf''', '''30B''', '''65B''', '''70B''', '''70Bf''', '''tokenizer_only'''] , ) parser.add_argument( '''--output_dir''' , help='''Location to write HF model and tokenizer''' , ) parser.add_argument('''--safe_serialization''' , type=__snake_case , help='''Whether or not to save using `safetensors`.''' ) _lowercase =parser.parse_args() if args.model_size != "tokenizer_only": write_model( model_path=args.output_dir , input_base_path=os.path.join(args.input_dir , args.model_size ) , model_size=args.model_size , safe_serialization=args.safe_serialization , ) _lowercase =os.path.join(args.input_dir , '''tokenizer.model''' ) write_tokenizer(args.output_dir , __snake_case ) if __name__ == "__main__": main()
5
import warnings from ...utils import logging from .image_processing_perceiver import PerceiverImageProcessor lowercase = logging.get_logger(__name__) class UpperCamelCase_ ( snake_case_ ): '''simple docstring''' def __init__( self , *a , **a ) -> None: warnings.warn( 'The class PerceiverFeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use PerceiverImageProcessor instead.' , a , ) super().__init__(*a , **a )
178
0
'''simple docstring''' import unittest from transformers import XLMConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMWithLMHeadModel, ) from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCamelCase : """simple docstring""" def __init__( self : Union[str, Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[int]=1_3 , UpperCAmelCase_ : Dict=7 , UpperCAmelCase_ : int=True , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : List[Any]=True , UpperCAmelCase_ : List[Any]=True , UpperCAmelCase_ : List[Any]=False , UpperCAmelCase_ : List[Any]=False , UpperCAmelCase_ : Union[str, Any]=False , UpperCAmelCase_ : Union[str, Any]=2 , UpperCAmelCase_ : Optional[Any]=9_9 , UpperCAmelCase_ : str=0 , UpperCAmelCase_ : int=3_2 , UpperCAmelCase_ : Tuple=5 , UpperCAmelCase_ : Any=4 , UpperCAmelCase_ : Tuple=0.1 , UpperCAmelCase_ : int=0.1 , UpperCAmelCase_ : Optional[int]=5_1_2 , UpperCAmelCase_ : str=2 , UpperCAmelCase_ : Any=0.02 , UpperCAmelCase_ : str=2 , UpperCAmelCase_ : Optional[int]=4 , UpperCAmelCase_ : int="last" , UpperCAmelCase_ : Union[str, Any]=True , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : List[str]=0 , ): """simple docstring""" a : Tuple = parent a : Optional[Any] = batch_size a : Tuple = seq_length a : Union[str, Any] = is_training a : List[str] = use_input_lengths a : Union[str, Any] = use_token_type_ids a : Optional[int] = use_labels a : int = gelu_activation a : Dict = sinusoidal_embeddings a : Any = causal a : Optional[int] = asm a : int = n_langs a : List[str] = vocab_size a : List[str] = n_special a : List[str] = hidden_size a : Any = num_hidden_layers a : Union[str, Any] = num_attention_heads a : Optional[Any] = hidden_dropout_prob a : str = attention_probs_dropout_prob a : Dict = max_position_embeddings a : Union[str, Any] = type_sequence_label_size a : str = initializer_range a : List[Any] = num_labels a : Union[str, Any] = num_choices a : Optional[Any] = summary_type a : Optional[Any] = use_proj a : Optional[Any] = scope a : Dict = bos_token_id def SCREAMING_SNAKE_CASE_ ( self : int): """simple docstring""" a : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) a : List[Any] = random_attention_mask([self.batch_size, self.seq_length]) a : Optional[int] = None if self.use_input_lengths: a : Optional[int] = ( ids_tensor([self.batch_size] , vocab_size=2) + self.seq_length - 2 ) # small variation of seq_length a : int = None if self.use_token_type_ids: a : str = ids_tensor([self.batch_size, self.seq_length] , self.n_langs) a : Optional[Any] = None a : Tuple = None a : Optional[Any] = None if self.use_labels: a : Optional[int] = ids_tensor([self.batch_size] , self.type_sequence_label_size) a : int = ids_tensor([self.batch_size, self.seq_length] , self.num_labels) a : Optional[Any] = ids_tensor([self.batch_size] , 2).float() a : Dict = ids_tensor([self.batch_size] , self.num_choices) a : Any = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def SCREAMING_SNAKE_CASE_ ( self : str): """simple docstring""" return XLMConfig( vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , num_labels=self.num_labels , bos_token_id=self.bos_token_id , ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , UpperCAmelCase_ : str , UpperCAmelCase_ : Any , UpperCAmelCase_ : Dict , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[Any] , ): """simple docstring""" a : Any = XLMModel(config=UpperCAmelCase_) model.to(UpperCAmelCase_) model.eval() a : int = model(UpperCAmelCase_ , lengths=UpperCAmelCase_ , langs=UpperCAmelCase_) a : str = model(UpperCAmelCase_ , langs=UpperCAmelCase_) a : int = model(UpperCAmelCase_) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : str , UpperCAmelCase_ : int , UpperCAmelCase_ : Dict , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Any , UpperCAmelCase_ : Any , UpperCAmelCase_ : List[Any] , ): """simple docstring""" a : Optional[Any] = XLMWithLMHeadModel(UpperCAmelCase_) model.to(UpperCAmelCase_) model.eval() a : List[str] = model(UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_) self.parent.assertEqual(result.loss.shape , ()) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def SCREAMING_SNAKE_CASE_ ( self : Tuple , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[Any] , ): """simple docstring""" a : Union[str, Any] = XLMForQuestionAnsweringSimple(UpperCAmelCase_) model.to(UpperCAmelCase_) model.eval() a : List[str] = model(UpperCAmelCase_) a : Tuple = model(UpperCAmelCase_ , start_positions=UpperCAmelCase_ , end_positions=UpperCAmelCase_) a : Any = outputs self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length)) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length)) def SCREAMING_SNAKE_CASE_ ( self : Dict , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Any , UpperCAmelCase_ : Any , ): """simple docstring""" a : Any = XLMForQuestionAnswering(UpperCAmelCase_) model.to(UpperCAmelCase_) model.eval() a : int = model(UpperCAmelCase_) a : Dict = model( UpperCAmelCase_ , start_positions=UpperCAmelCase_ , end_positions=UpperCAmelCase_ , cls_index=UpperCAmelCase_ , is_impossible=UpperCAmelCase_ , p_mask=UpperCAmelCase_ , ) a : int = model( UpperCAmelCase_ , start_positions=UpperCAmelCase_ , end_positions=UpperCAmelCase_ , cls_index=UpperCAmelCase_ , is_impossible=UpperCAmelCase_ , ) ((a) , ) : Union[str, Any] = result_with_labels.to_tuple() a : int = model(UpperCAmelCase_ , start_positions=UpperCAmelCase_ , end_positions=UpperCAmelCase_) ((a) , ) : Union[str, Any] = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape , ()) self.parent.assertEqual(result.start_top_log_probs.shape , (self.batch_size, model.config.start_n_top)) self.parent.assertEqual(result.start_top_index.shape , (self.batch_size, model.config.start_n_top)) self.parent.assertEqual( result.end_top_log_probs.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top)) self.parent.assertEqual( result.end_top_index.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top)) self.parent.assertEqual(result.cls_logits.shape , (self.batch_size,)) def SCREAMING_SNAKE_CASE_ ( self : str , UpperCAmelCase_ : int , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : str , ): """simple docstring""" a : Dict = XLMForSequenceClassification(UpperCAmelCase_) model.to(UpperCAmelCase_) model.eval() a : Union[str, Any] = model(UpperCAmelCase_) a : Union[str, Any] = model(UpperCAmelCase_ , labels=UpperCAmelCase_) self.parent.assertEqual(result.loss.shape , ()) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size)) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : Dict , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : str , UpperCAmelCase_ : Any , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Any , ): """simple docstring""" a : Dict = self.num_labels a : int = XLMForTokenClassification(UpperCAmelCase_) model.to(UpperCAmelCase_) model.eval() a : Optional[Any] = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , labels=UpperCAmelCase_) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels)) def SCREAMING_SNAKE_CASE_ ( self : str , UpperCAmelCase_ : Dict , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Any , UpperCAmelCase_ : str , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Dict , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Dict , ): """simple docstring""" a : str = self.num_choices a : Dict = XLMForMultipleChoice(config=UpperCAmelCase_) model.to(UpperCAmelCase_) model.eval() a : Union[str, Any] = input_ids.unsqueeze(1).expand(-1 , self.num_choices , -1).contiguous() a : str = token_type_ids.unsqueeze(1).expand(-1 , self.num_choices , -1).contiguous() a : Optional[int] = input_mask.unsqueeze(1).expand(-1 , self.num_choices , -1).contiguous() a : Any = model( UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices)) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any]): """simple docstring""" a : int = self.prepare_config_and_inputs() ( ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ) : Union[str, Any] = config_and_inputs a : Optional[int] = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'lengths': input_lengths} return config, inputs_dict @require_torch class UpperCamelCase ( a_ , a_ , a_ , unittest.TestCase ): """simple docstring""" A : int = ( ( XLMModel, XLMWithLMHeadModel, XLMForQuestionAnswering, XLMForSequenceClassification, XLMForQuestionAnsweringSimple, XLMForTokenClassification, XLMForMultipleChoice, ) if is_torch_available() else () ) A : List[str] = ( (XLMWithLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable A : Optional[Any] = ( { "feature-extraction": XLMModel, "fill-mask": XLMWithLMHeadModel, "question-answering": XLMForQuestionAnsweringSimple, "text-classification": XLMForSequenceClassification, "text-generation": XLMWithLMHeadModel, "token-classification": XLMForTokenClassification, "zero-shot": XLMForSequenceClassification, } if is_torch_available() else {} ) def SCREAMING_SNAKE_CASE_ ( self : Dict , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Any , UpperCAmelCase_ : Any): """simple docstring""" if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith('Fast') ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : int , UpperCAmelCase_ : Dict=False): """simple docstring""" a : List[Any] = super()._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ , return_labels=UpperCAmelCase_) if return_labels: if model_class.__name__ == "XLMForQuestionAnswering": a : Optional[int] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=UpperCAmelCase_) a : str = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=UpperCAmelCase_) return inputs_dict def SCREAMING_SNAKE_CASE_ ( self : Optional[int]): """simple docstring""" a : List[Any] = XLMModelTester(self) a : Tuple = ConfigTester(self , config_class=UpperCAmelCase_ , emb_dim=3_7) def SCREAMING_SNAKE_CASE_ ( self : List[str]): """simple docstring""" self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE_ ( self : Any): """simple docstring""" a : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_model(*UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ ( self : Dict): """simple docstring""" a : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_lm_head(*UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ ( self : int): """simple docstring""" a : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_simple_qa(*UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ ( self : Any): """simple docstring""" a : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_qa(*UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ ( self : Any): """simple docstring""" a : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_sequence_classif(*UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ ( self : Optional[int]): """simple docstring""" a : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_token_classif(*UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ ( self : List[str]): """simple docstring""" a : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_for_multiple_choice(*UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ ( self : int , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Any=False , UpperCAmelCase_ : Optional[Any]=1): """simple docstring""" self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_) self.assertListEqual( [isinstance(UpperCAmelCase_ , UpperCAmelCase_) for iter_attentions in attentions] , [True] * len(UpperCAmelCase_)) self.assertEqual(len(UpperCAmelCase_) , (max_length - min_length) * num_beam_groups) for idx, iter_attentions in enumerate(UpperCAmelCase_): # adds PAD dummy token a : List[str] = min_length + idx + 1 a : Optional[Any] = min_length + idx + 1 a : Optional[int] = ( batch_size * num_beam_groups, config.num_attention_heads, tgt_len, src_len, ) # check attn size self.assertListEqual( [layer_attention.shape for layer_attention in iter_attentions] , [expected_shape] * len(UpperCAmelCase_)) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : str=False , UpperCAmelCase_ : Union[str, Any]=1): """simple docstring""" self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_) self.assertListEqual( [isinstance(UpperCAmelCase_ , UpperCAmelCase_) for iter_hidden_states in hidden_states] , [True] * len(UpperCAmelCase_) , ) self.assertEqual(len(UpperCAmelCase_) , (max_length - min_length) * num_beam_groups) for idx, iter_hidden_states in enumerate(UpperCAmelCase_): # adds PAD dummy token a : int = min_length + idx + 1 a : Any = (batch_size * num_beam_groups, seq_len, config.hidden_size) # check hidden size self.assertListEqual( [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states] , [expected_shape] * len(UpperCAmelCase_) , ) pass @slow def SCREAMING_SNAKE_CASE_ ( self : Dict): """simple docstring""" for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a : Union[str, Any] = XLMModel.from_pretrained(UpperCAmelCase_) self.assertIsNotNone(UpperCAmelCase_) @require_torch class UpperCamelCase ( unittest.TestCase ): """simple docstring""" @slow def SCREAMING_SNAKE_CASE_ ( self : Tuple): """simple docstring""" a : Dict = XLMWithLMHeadModel.from_pretrained('xlm-mlm-en-2048') model.to(UpperCAmelCase_) a : List[Any] = torch.tensor([[1_4, 4_4_7]] , dtype=torch.long , device=UpperCAmelCase_) # the president a : Dict = [ 1_4, 4_4_7, 1_4, 4_4_7, 1_4, 4_4_7, 1_4, 4_4_7, 1_4, 4_4_7, 1_4, 4_4_7, 1_4, 4_4_7, 1_4, 4_4_7, 1_4, 4_4_7, 1_4, 4_4_7, ] # the president the president the president the president the president the president the president the president the president the president # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference a : Optional[Any] = model.generate(UpperCAmelCase_ , do_sample=UpperCAmelCase_) self.assertListEqual(output_ids[0].cpu().numpy().tolist() , UpperCAmelCase_)
345
'''simple docstring''' def SCREAMING_SNAKE_CASE__ ( snake_case : int , snake_case : int ) -> bool: """simple docstring""" return numa ^ numa < 0 if __name__ == "__main__": import doctest doctest.testmod()
345
1
import logging from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import arg_to_scheduler from transformers import TrainingArguments a__ = logging.getLogger(__name__) @dataclass class UpperCAmelCase_ ( __snake_case ): """simple docstring""" UpperCAmelCase__ : List[str] = field( default=0.0 , metadata={"help": "The label smoothing epsilon to apply (if not zero)."} ) UpperCAmelCase__ : Tuple = field(default=__snake_case , metadata={"help": "Whether to SortishSamler or not."} ) UpperCAmelCase__ : List[Any] = field( default=__snake_case , metadata={"help": "Whether to use generate to calculate generative metrics (ROUGE, BLEU)."} ) UpperCAmelCase__ : int = field(default=__snake_case , metadata={"help": "whether to use adafactor"} ) UpperCAmelCase__ : Union[str, Any] = field( default=__snake_case , metadata={"help": "Encoder layer dropout probability. Goes into model.config."} ) UpperCAmelCase__ : Union[str, Any] = field( default=__snake_case , metadata={"help": "Decoder layer dropout probability. Goes into model.config."} ) UpperCAmelCase__ : str = field(default=__snake_case , metadata={"help": "Dropout probability. Goes into model.config."} ) UpperCAmelCase__ : Optional[Any] = field( default=__snake_case , metadata={"help": "Attention dropout probability. Goes into model.config."} ) UpperCAmelCase__ : Dict = field( default="linear" , metadata={"help": F'''Which lr scheduler to use. Selected in {sorted(arg_to_scheduler.keys() )}'''} , )
235
'''simple docstring''' class _lowerCAmelCase : '''simple docstring''' def __init__(self , UpperCAmelCase , UpperCAmelCase=None , UpperCAmelCase=None ) -> int: _snake_case = data _snake_case = previous _snake_case = next_node def __str__(self ) -> str: return f"""{self.data}""" def lowercase (self ) -> int: return self.data def lowercase (self ) -> Dict: return self.next def lowercase (self ) -> Union[str, Any]: return self.previous class _lowerCAmelCase : '''simple docstring''' def __init__(self , UpperCAmelCase ) -> List[str]: _snake_case = head def __iter__(self ) -> Optional[Any]: return self def lowercase (self ) -> str: if not self.current: raise StopIteration else: _snake_case = self.current.get_data() _snake_case = self.current.get_next() return value class _lowerCAmelCase : '''simple docstring''' def __init__(self ) -> Optional[int]: _snake_case = None # First node in list _snake_case = None # Last node in list def __str__(self ) -> Optional[int]: _snake_case = self.head _snake_case = [] while current is not None: nodes.append(current.get_data() ) _snake_case = current.get_next() return " ".join(str(UpperCAmelCase ) for node in nodes ) def __contains__(self , UpperCAmelCase ) -> int: _snake_case = self.head while current: if current.get_data() == value: return True _snake_case = current.get_next() return False def __iter__(self ) -> Union[str, Any]: return LinkedListIterator(self.head ) def lowercase (self ) -> str: if self.head: return self.head.get_data() return None def lowercase (self ) -> List[Any]: if self.tail: return self.tail.get_data() return None def lowercase (self , UpperCAmelCase ) -> None: if self.head is None: _snake_case = node _snake_case = node else: self.insert_before_node(self.head , UpperCAmelCase ) def lowercase (self , UpperCAmelCase ) -> None: if self.head is None: self.set_head(UpperCAmelCase ) else: self.insert_after_node(self.tail , UpperCAmelCase ) def lowercase (self , UpperCAmelCase ) -> None: _snake_case = Node(UpperCAmelCase ) if self.head is None: self.set_head(UpperCAmelCase ) else: self.set_tail(UpperCAmelCase ) def lowercase (self , UpperCAmelCase , UpperCAmelCase ) -> None: _snake_case = node _snake_case = node.previous if node.get_previous() is None: _snake_case = node_to_insert else: _snake_case = node_to_insert _snake_case = node_to_insert def lowercase (self , UpperCAmelCase , UpperCAmelCase ) -> None: _snake_case = node _snake_case = node.next if node.get_next() is None: _snake_case = node_to_insert else: _snake_case = node_to_insert _snake_case = node_to_insert def lowercase (self , UpperCAmelCase , UpperCAmelCase ) -> None: _snake_case = 1 _snake_case = Node(UpperCAmelCase ) _snake_case = self.head while node: if current_position == position: self.insert_before_node(UpperCAmelCase , UpperCAmelCase ) return current_position += 1 _snake_case = node.next self.insert_after_node(self.tail , UpperCAmelCase ) def lowercase (self , UpperCAmelCase ) -> Node: _snake_case = self.head while node: if node.get_data() == item: return node _snake_case = node.get_next() raise Exception("""Node not found""" ) def lowercase (self , UpperCAmelCase ) -> Optional[int]: if (node := self.get_node(UpperCAmelCase )) is not None: if node == self.head: _snake_case = self.head.get_next() if node == self.tail: _snake_case = self.tail.get_previous() self.remove_node_pointers(UpperCAmelCase ) @staticmethod def lowercase (UpperCAmelCase ) -> None: if node.get_next(): _snake_case = node.previous if node.get_previous(): _snake_case = node.next _snake_case = None _snake_case = None def lowercase (self ) -> Dict: return self.head is None def __SCREAMING_SNAKE_CASE ( ): pass if __name__ == "__main__": import doctest doctest.testmod()
341
0
import enum import os from hashlib import shaaaa from typing import Optional from .. import config from .logging import get_logger __A = get_logger(__name__) class __lowerCAmelCase ( enum.Enum ): """simple docstring""" snake_case_ = '''all_checks''' snake_case_ = '''basic_checks''' snake_case_ = '''no_checks''' class __lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" pass class __lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" pass class __lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" pass class __lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" pass def lowerCamelCase_ ( UpperCamelCase__ : int , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Tuple=None ) -> str: """simple docstring""" if expected_checksums is None: logger.info('Unable to verify checksums.' ) return if len(set(_UpperCAmelCase ) - set(_UpperCAmelCase ) ) > 0: raise ExpectedMoreDownloadedFiles(str(set(_UpperCAmelCase ) - set(_UpperCAmelCase ) ) ) if len(set(_UpperCAmelCase ) - set(_UpperCAmelCase ) ) > 0: raise UnexpectedDownloadedFile(str(set(_UpperCAmelCase ) - set(_UpperCAmelCase ) ) ) __lowerCamelCase = [url for url in expected_checksums if expected_checksums[url] != recorded_checksums[url]] __lowerCamelCase = ' for ' + verification_name if verification_name is not None else '' if len(_UpperCAmelCase ) > 0: raise NonMatchingChecksumError( F"""Checksums didn't match{for_verification_name}:\n""" F"""{bad_urls}\n""" 'Set `verification_mode=\'no_checks\'` to skip checksums verification and ignore this error' ) logger.info('All the checksums matched successfully' + for_verification_name ) class __lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" pass class __lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" pass class __lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" pass class __lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" pass def lowerCamelCase_ ( UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Optional[Any] ) -> List[str]: """simple docstring""" if expected_splits is None: logger.info('Unable to verify splits sizes.' ) return if len(set(_UpperCAmelCase ) - set(_UpperCAmelCase ) ) > 0: raise ExpectedMoreSplits(str(set(_UpperCAmelCase ) - set(_UpperCAmelCase ) ) ) if len(set(_UpperCAmelCase ) - set(_UpperCAmelCase ) ) > 0: raise UnexpectedSplits(str(set(_UpperCAmelCase ) - set(_UpperCAmelCase ) ) ) __lowerCamelCase = [ {'expected': expected_splits[name], 'recorded': recorded_splits[name]} for name in expected_splits if expected_splits[name].num_examples != recorded_splits[name].num_examples ] if len(_UpperCAmelCase ) > 0: raise NonMatchingSplitsSizesError(str(_UpperCAmelCase ) ) logger.info('All the splits matched successfully.' ) def lowerCamelCase_ ( UpperCamelCase__ : Tuple , UpperCamelCase__ : Any = True ) -> dict: """simple docstring""" if record_checksum: __lowerCamelCase = shaaaa() with open(_UpperCAmelCase , 'rb' ) as f: for chunk in iter(lambda: f.read(1 << 20 ) , b'' ): m.update(_UpperCAmelCase ) __lowerCamelCase = m.hexdigest() else: __lowerCamelCase = None return {"num_bytes": os.path.getsize(_UpperCAmelCase ), "checksum": checksum} def lowerCamelCase_ ( UpperCamelCase__ : Tuple ) -> Optional[int]: """simple docstring""" if dataset_size and config.IN_MEMORY_MAX_SIZE: return dataset_size < config.IN_MEMORY_MAX_SIZE else: return False
351
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxSeqaSeqConfigWithPast from ...utils import logging if TYPE_CHECKING: from ...feature_extraction_utils import FeatureExtractionMixin from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import TensorType __A = logging.get_logger(__name__) __A = { "openai/whisper-base": "https://huggingface.co/openai/whisper-base/resolve/main/config.json", } # fmt: off __A = [ 1, 2, 7, 8, 9, 10, 14, 25, 26, 27, 28, 29, 31, 58, 59, 60, 61, 62, 63, 90, 91, 92, 93, 3_57, 3_66, 4_38, 5_32, 6_85, 7_05, 7_96, 9_30, 10_58, 12_20, 12_67, 12_79, 13_03, 13_43, 13_77, 13_91, 16_35, 17_82, 18_75, 21_62, 23_61, 24_88, 34_67, 40_08, 42_11, 46_00, 48_08, 52_99, 58_55, 63_29, 72_03, 96_09, 99_59, 1_05_63, 1_07_86, 1_14_20, 1_17_09, 1_19_07, 1_31_63, 1_36_97, 1_37_00, 1_48_08, 1_53_06, 1_64_10, 1_67_91, 1_79_92, 1_92_03, 1_95_10, 2_07_24, 2_23_05, 2_29_35, 2_70_07, 3_01_09, 3_04_20, 3_34_09, 3_49_49, 4_02_83, 4_04_93, 4_05_49, 4_72_82, 4_91_46, 5_02_57, 5_03_59, 5_03_60, 5_03_61 ] __A = [ 1, 2, 7, 8, 9, 10, 14, 25, 26, 27, 28, 29, 31, 58, 59, 60, 61, 62, 63, 90, 91, 92, 93, 3_59, 5_03, 5_22, 5_42, 8_73, 8_93, 9_02, 9_18, 9_22, 9_31, 13_50, 18_53, 19_82, 24_60, 26_27, 32_46, 32_53, 32_68, 35_36, 38_46, 39_61, 41_83, 46_67, 65_85, 66_47, 72_73, 90_61, 93_83, 1_04_28, 1_09_29, 1_19_38, 1_20_33, 1_23_31, 1_25_62, 1_37_93, 1_41_57, 1_46_35, 1_52_65, 1_56_18, 1_65_53, 1_66_04, 1_83_62, 1_89_56, 2_00_75, 2_16_75, 2_25_20, 2_61_30, 2_61_61, 2_64_35, 2_82_79, 2_94_64, 3_16_50, 3_23_02, 3_24_70, 3_68_65, 4_28_63, 4_74_25, 4_98_70, 5_02_54, 5_02_58, 5_03_60, 5_03_61, 5_03_62 ] class __lowerCAmelCase ( __magic_name__ ): """simple docstring""" snake_case_ = '''whisper''' snake_case_ = ['''past_key_values'''] snake_case_ = {'''num_attention_heads''': '''encoder_attention_heads''', '''hidden_size''': '''d_model'''} def __init__( self , lowerCamelCase__=51_865 , lowerCamelCase__=80 , lowerCamelCase__=6 , lowerCamelCase__=4 , lowerCamelCase__=6 , lowerCamelCase__=4 , lowerCamelCase__=1_536 , lowerCamelCase__=1_536 , lowerCamelCase__=0.0 , lowerCamelCase__=0.0 , lowerCamelCase__=50_257 , lowerCamelCase__=True , lowerCamelCase__=True , lowerCamelCase__="gelu" , lowerCamelCase__=256 , lowerCamelCase__=0.0 , lowerCamelCase__=0.0 , lowerCamelCase__=0.0 , lowerCamelCase__=0.02 , lowerCamelCase__=False , lowerCamelCase__=1_500 , lowerCamelCase__=448 , lowerCamelCase__=50_256 , lowerCamelCase__=50_256 , lowerCamelCase__=50_256 , lowerCamelCase__=None , lowerCamelCase__=[220, 50_256] , lowerCamelCase__=False , lowerCamelCase__=256 , lowerCamelCase__=False , lowerCamelCase__=0.05 , lowerCamelCase__=10 , lowerCamelCase__=2 , lowerCamelCase__=0.0 , lowerCamelCase__=10 , lowerCamelCase__=0 , lowerCamelCase__=7 , **lowerCamelCase__ , ) -> str: '''simple docstring''' __lowerCamelCase = vocab_size __lowerCamelCase = num_mel_bins __lowerCamelCase = d_model __lowerCamelCase = encoder_layers __lowerCamelCase = encoder_attention_heads __lowerCamelCase = decoder_layers __lowerCamelCase = decoder_attention_heads __lowerCamelCase = decoder_ffn_dim __lowerCamelCase = encoder_ffn_dim __lowerCamelCase = dropout __lowerCamelCase = attention_dropout __lowerCamelCase = activation_dropout __lowerCamelCase = activation_function __lowerCamelCase = init_std __lowerCamelCase = encoder_layerdrop __lowerCamelCase = decoder_layerdrop __lowerCamelCase = use_cache __lowerCamelCase = encoder_layers __lowerCamelCase = scale_embedding # scale factor will be sqrt(d_model) if True __lowerCamelCase = max_source_positions __lowerCamelCase = max_target_positions # Audio Classification-specific parameters. Feel free to ignore for other classes. __lowerCamelCase = classifier_proj_size __lowerCamelCase = use_weighted_layer_sum # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 __lowerCamelCase = apply_spec_augment __lowerCamelCase = mask_time_prob __lowerCamelCase = mask_time_length __lowerCamelCase = mask_time_min_masks __lowerCamelCase = mask_feature_prob __lowerCamelCase = mask_feature_length __lowerCamelCase = mask_feature_min_masks __lowerCamelCase = median_filter_width super().__init__( pad_token_id=lowerCamelCase__ , bos_token_id=lowerCamelCase__ , eos_token_id=lowerCamelCase__ , is_encoder_decoder=lowerCamelCase__ , decoder_start_token_id=lowerCamelCase__ , suppress_tokens=lowerCamelCase__ , begin_suppress_tokens=lowerCamelCase__ , **lowerCamelCase__ , ) class __lowerCAmelCase ( __magic_name__ ): """simple docstring""" @property def lowercase_ ( self ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' __lowerCamelCase = OrderedDict( [ ('input_features', {0: 'batch', 1: 'feature_size', 2: 'encoder_sequence'}), ] ) if self.use_past: __lowerCamelCase = {0: 'batch'} else: __lowerCamelCase = {0: 'batch', 1: 'decoder_sequence'} if self.use_past: self.fill_with_past_key_values_(lowerCamelCase__ , direction='inputs' ) return common_inputs def lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__ = -1 , lowerCamelCase__ = -1 , lowerCamelCase__ = False , lowerCamelCase__ = None , lowerCamelCase__ = 22_050 , lowerCamelCase__ = 5.0 , lowerCamelCase__ = 220 , ) -> Mapping[str, Any]: '''simple docstring''' __lowerCamelCase = OrderedDict() __lowerCamelCase = OnnxConfig.generate_dummy_inputs( self , preprocessor=preprocessor.feature_extractor , batch_size=lowerCamelCase__ , framework=lowerCamelCase__ , sampling_rate=lowerCamelCase__ , time_duration=lowerCamelCase__ , frequency=lowerCamelCase__ , ) __lowerCamelCase = encoder_inputs['input_features'].shape[2] __lowerCamelCase = encoder_sequence_length // 2 if self.use_past else seq_length __lowerCamelCase = super().generate_dummy_inputs( preprocessor.tokenizer , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase = encoder_inputs.pop('input_features' ) __lowerCamelCase = decoder_inputs.pop('decoder_input_ids' ) if "past_key_values" in decoder_inputs: __lowerCamelCase = decoder_inputs.pop('past_key_values' ) return dummy_inputs @property def lowercase_ ( self ) -> float: '''simple docstring''' return 1e-3
348
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) UpperCamelCase = { '''configuration_efficientformer''': [ '''EFFICIENTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''EfficientFormerConfig''', ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = ['''EfficientFormerImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = [ '''EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''EfficientFormerForImageClassification''', '''EfficientFormerForImageClassificationWithTeacher''', '''EfficientFormerModel''', '''EfficientFormerPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = [ '''TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFEfficientFormerForImageClassification''', '''TFEfficientFormerForImageClassificationWithTeacher''', '''TFEfficientFormerModel''', '''TFEfficientFormerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_efficientformer import EFFICIENTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, EfficientFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_efficientformer import EfficientFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_efficientformer import ( EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, EfficientFormerForImageClassification, EfficientFormerForImageClassificationWithTeacher, EfficientFormerModel, EfficientFormerPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_efficientformer import ( TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFEfficientFormerForImageClassification, TFEfficientFormerForImageClassificationWithTeacher, TFEfficientFormerModel, TFEfficientFormerPreTrainedModel, ) else: import sys UpperCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
87
"""simple docstring""" import requests from bsa import BeautifulSoup def _lowerCAmelCase ( UpperCamelCase_ = "AAPL" ): __SCREAMING_SNAKE_CASE = f"https://in.finance.yahoo.com/quote/{symbol}?s={symbol}" __SCREAMING_SNAKE_CASE = BeautifulSoup(requests.get(UpperCamelCase_ ).text , """html.parser""" ) __SCREAMING_SNAKE_CASE = """My(6px) Pos(r) smartphone_Mt(6px)""" return soup.find("""div""" , class_=class_ ).find("""span""" ).text if __name__ == "__main__": for symbol in "AAPL AMZN IBM GOOG MSFT ORCL".split(): print(F"""Current {symbol:<4} stock price is {stock_price(symbol):>8}""")
100
0
"""simple docstring""" import logging import sys from dataclasses import dataclass, field from typing import Any, Dict, List, Optional, Union import librosa import torch from datasets import DatasetDict, load_dataset from packaging import version from torch import nn from transformers import ( HfArgumentParser, Trainer, TrainingArguments, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaForPreTraining, is_apex_available, trainer_utils, ) from transformers.models.wavaveca.modeling_wavaveca import _compute_mask_indices if is_apex_available(): from apex import amp if version.parse(version.parse(torch.__version__).base_version) >= version.parse("1.6"): __magic_name__ = True from torch.cuda.amp import autocast __magic_name__ = logging.getLogger(__name__) @dataclass class lowercase : '''simple docstring''' __SCREAMING_SNAKE_CASE = field( metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""} ) __SCREAMING_SNAKE_CASE = field( default=A__ , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} , ) __SCREAMING_SNAKE_CASE = field( default=A__ , metadata={"""help""": """Whether to freeze the feature extractor layers of the model."""} ) __SCREAMING_SNAKE_CASE = field( default=A__ , metadata={"""help""": """Whether to log verbose messages or not."""} , ) __SCREAMING_SNAKE_CASE = field( default=2.0 , metadata={"""help""": """Maximum temperature for gumbel softmax."""} ) __SCREAMING_SNAKE_CASE = field( default=0.5 , metadata={"""help""": """Minimum temperature for gumbel softmax."""} ) __SCREAMING_SNAKE_CASE = field( default=0.99_99_95 , metadata={"""help""": """Decay of gumbel temperature during training."""} ) def _lowerCAmelCase ( A__: ModelArguments , A__: TrainingArguments ): '''simple docstring''' logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , handlers=[logging.StreamHandler(sys.stdout )] , ) UpperCAmelCase = logging.WARNING if model_args.verbose_logging: UpperCAmelCase = logging.DEBUG elif trainer_utils.is_main_process(training_args.local_rank ): UpperCAmelCase = logging.INFO logger.setLevel(A__ ) @dataclass class lowercase : '''simple docstring''' __SCREAMING_SNAKE_CASE = field( default=A__ , metadata={"""help""": """The name of the dataset to use (via the datasets library)."""} ) __SCREAMING_SNAKE_CASE = field( default=A__ , metadata={"""help""": """The configuration name of the dataset to use (via the datasets library)."""} ) __SCREAMING_SNAKE_CASE = field( default="""train""" , metadata={ """help""": """The name of the training data set split to use (via the datasets library). Defaults to 'train'""" } , ) __SCREAMING_SNAKE_CASE = field( default="""validation""" , metadata={ """help""": ( """The name of the validation data set split to use (via the datasets library). Defaults to 'validation'""" ) } , ) __SCREAMING_SNAKE_CASE = field( default="""file""" , metadata={"""help""": """Column in the dataset that contains speech file path. Defaults to 'file'"""} , ) __SCREAMING_SNAKE_CASE = field( default=A__ , metadata={"""help""": """Overwrite the cached preprocessed datasets or not."""} ) __SCREAMING_SNAKE_CASE = field( default=1 , metadata={ """help""": """The percentage of the train set used as validation set in case there's no validation split""" } , ) __SCREAMING_SNAKE_CASE = field( default=A__ , metadata={"""help""": """The number of processes to use for the preprocessing."""} , ) __SCREAMING_SNAKE_CASE = field( default=20.0 , metadata={"""help""": """Filter audio files that are longer than `max_duration_in_seconds` seconds"""} ) @dataclass class lowercase : '''simple docstring''' __SCREAMING_SNAKE_CASE = 42 __SCREAMING_SNAKE_CASE = 42 __SCREAMING_SNAKE_CASE = """longest""" __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None def __call__( self , _snake_case ) -> Dict[str, torch.Tensor]: """simple docstring""" UpperCAmelCase = self.feature_extractor.pad( _snake_case , max_length=self.max_length , padding=self.padding , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors='''pt''' , ) UpperCAmelCase = self.model._get_feat_extract_output_lengths(batch['''input_values'''].shape[-1] ) UpperCAmelCase = batch['''input_values'''].shape[0] # make sure that no loss is computed on padded inputs if batch["attention_mask"] is not None: # compute real output lengths according to convolution formula UpperCAmelCase = self.model._get_feat_extract_output_lengths(batch['''attention_mask'''].sum(-1 ) ).to( torch.long ) UpperCAmelCase = torch.zeros( (batch_size, mask_indices_seq_length) , dtype=torch.long , device=batch['''input_values'''].device ) # these two operations makes sure that all values # before the output lengths indices are attended to UpperCAmelCase = 1 UpperCAmelCase = attention_mask.flip([-1] ).cumsum(-1 ).flip([-1] ).bool() # sample randomly masked indices UpperCAmelCase = _compute_mask_indices( (batch_size, mask_indices_seq_length) , self.model.config.mask_time_prob , self.model.config.mask_time_length , attention_mask=_snake_case , min_masks=2 , ) return batch class lowercase ( A__ ): '''simple docstring''' def __init__( self , *_snake_case , _snake_case=1 , _snake_case=0 , _snake_case=1.0 , **_snake_case ) -> int: """simple docstring""" super().__init__(*_snake_case , **_snake_case ) UpperCAmelCase = 0 UpperCAmelCase = max_gumbel_temp UpperCAmelCase = min_gumbel_temp UpperCAmelCase = gumbel_temp_decay def snake_case_ ( self , _snake_case , _snake_case ) -> torch.Tensor: """simple docstring""" model.train() UpperCAmelCase = self._prepare_inputs(_snake_case ) if self.use_amp: with autocast(): UpperCAmelCase = self.compute_loss(_snake_case , _snake_case ) else: UpperCAmelCase = self.compute_loss(_snake_case , _snake_case ) if self.args.n_gpu > 1 or self.deepspeed: if model.module.config.ctc_loss_reduction == "mean": UpperCAmelCase = loss.mean() elif model.module.config.ctc_loss_reduction == "sum": UpperCAmelCase = loss.sum() / (inputs['''mask_time_indices''']).sum() else: raise ValueError(f"""{model.config.ctc_loss_reduction} is not valid. Choose one of ['mean', 'sum']""" ) if self.args.gradient_accumulation_steps > 1: UpperCAmelCase = loss / self.args.gradient_accumulation_steps if self.use_amp: self.scaler.scale(_snake_case ).backward() elif self.use_apex: with amp.scale_loss(_snake_case , self.optimizer ) as scaled_loss: scaled_loss.backward() elif self.deepspeed: self.deepspeed.backward(_snake_case ) else: loss.backward() self.num_update_step += 1 # make sure gumbel softmax temperature is decayed if self.args.n_gpu > 1 or self.deepspeed: model.module.set_gumbel_temperature( max(self.max_gumbel_temp * self.gumbel_temp_decay**self.num_update_step , self.min_gumbel_temp ) ) else: model.set_gumbel_temperature( max(self.max_gumbel_temp * self.gumbel_temp_decay**self.num_update_step , self.min_gumbel_temp ) ) return loss.detach() def _lowerCAmelCase ( ): '''simple docstring''' UpperCAmelCase = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = parser.parse_args_into_dataclasses() configure_logger(A__ , A__ ) # Downloading and loading a dataset from the hub. UpperCAmelCase = load_dataset(data_args.dataset_name , data_args.dataset_config_name , cache_dir=model_args.cache_dir ) if "validation" not in datasets.keys(): # make sure only "validation" and "train" keys remain" UpperCAmelCase = DatasetDict() UpperCAmelCase = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=F"""{data_args.train_split_name}[:{data_args.validation_split_percentage}%]""" , cache_dir=model_args.cache_dir , ) UpperCAmelCase = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=F"""{data_args.train_split_name}[{data_args.validation_split_percentage}%:]""" , cache_dir=model_args.cache_dir , ) else: # make sure only "validation" and "train" keys remain" UpperCAmelCase = DatasetDict() UpperCAmelCase = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split='''validation''' , cache_dir=model_args.cache_dir , ) UpperCAmelCase = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=F"""{data_args.train_split_name}""" , cache_dir=model_args.cache_dir , ) # only normalized-inputs-training is supported UpperCAmelCase = WavaVecaFeatureExtractor.from_pretrained( model_args.model_name_or_path , cache_dir=model_args.cache_dir , do_normalize=A__ ) def prepare_dataset(A__: Tuple ): # check that all files have the correct sampling rate UpperCAmelCase , UpperCAmelCase = librosa.load(batch[data_args.speech_file_column] , sr=feature_extractor.sampling_rate ) return batch # load audio files into numpy arrays UpperCAmelCase = datasets.map( A__ , num_proc=data_args.preprocessing_num_workers , remove_columns=datasets['''train'''].column_names ) # filter audio files that are too long UpperCAmelCase = vectorized_datasets.filter( lambda A__ : len(data['''speech'''] ) < int(data_args.max_duration_in_seconds * feature_extractor.sampling_rate ) ) def normalize(A__: str ): return feature_extractor(batch['''speech'''] , sampling_rate=feature_extractor.sampling_rate ) # normalize and transform to `BatchFeatures` UpperCAmelCase = vectorized_datasets.map( A__ , batched=A__ , num_proc=data_args.preprocessing_num_workers , load_from_cache_file=not data_args.overwrite_cache , remove_columns=vectorized_datasets['''train'''].column_names , ) # pretraining is only supported for "newer" stable layer norm architecture # apply_spec_augment has to be True, mask_feature_prob has to be 0.0 UpperCAmelCase = WavaVecaConfig.from_pretrained( model_args.model_name_or_path , cache_dir=model_args.cache_dir , gradient_checkpointing=training_args.gradient_checkpointing , ) if not config.do_stable_layer_norm or config.feat_extract_norm != "layer": raise ValueError( '''PreTraining is only supported for ``config.do_stable_layer_norm=True`` and''' ''' ``config.feat_extract_norm=\'layer\'''' ) UpperCAmelCase = WavaVecaForPreTraining(A__ ) UpperCAmelCase = DataCollatorForWavaVecaPretraining(model=A__ , feature_extractor=A__ ) UpperCAmelCase = WavaVecaPreTrainer( model=A__ , data_collator=A__ , args=A__ , train_dataset=vectorized_datasets['''train'''] , eval_dataset=vectorized_datasets['''validation'''] , tokenizer=A__ , max_gumbel_temp=model_args.max_gumbel_temperature , min_gumbel_temp=model_args.min_gumbel_temperature , gumbel_temp_decay=model_args.gumbel_temperature_decay , ) trainer.train() if __name__ == "__main__": main()
367
import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin __magic_name__ = get_tests_dir("fixtures/test_sentencepiece_no_bos.model") @require_sentencepiece @require_tokenizers class lowercase ( A__ , unittest.TestCase ): '''simple docstring''' __SCREAMING_SNAKE_CASE = PegasusTokenizer __SCREAMING_SNAKE_CASE = PegasusTokenizerFast __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = True def snake_case_ ( self ) -> Optional[Any]: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing UpperCAmelCase = PegasusTokenizer(_snake_case ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def snake_case_ ( self ) -> Dict: """simple docstring""" return PegasusTokenizer.from_pretrained('''google/pegasus-large''' ) def snake_case_ ( self , **_snake_case ) -> PegasusTokenizer: """simple docstring""" return PegasusTokenizer.from_pretrained(self.tmpdirname , **_snake_case ) def snake_case_ ( self , _snake_case ) -> Any: """simple docstring""" return ("This is a test", "This is a test") def snake_case_ ( self ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase = '''</s>''' UpperCAmelCase = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_snake_case ) , _snake_case ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_snake_case ) , _snake_case ) def snake_case_ ( self ) -> str: """simple docstring""" UpperCAmelCase = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<pad>''' ) self.assertEqual(vocab_keys[1] , '''</s>''' ) self.assertEqual(vocab_keys[-1] , '''v''' ) self.assertEqual(len(_snake_case ) , 1103 ) def snake_case_ ( self ) -> Union[str, Any]: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1103 ) def snake_case_ ( self ) -> List[str]: """simple docstring""" UpperCAmelCase = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) UpperCAmelCase = self.tokenizer_class.from_pretrained(self.tmpdirname ) UpperCAmelCase = ( '''Let\'s see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important''' ''' </s> <pad> <pad> <pad>''' ) UpperCAmelCase = rust_tokenizer([raw_input_str] , return_tensors=_snake_case , add_special_tokens=_snake_case ).input_ids[0] UpperCAmelCase = py_tokenizer([raw_input_str] , return_tensors=_snake_case , add_special_tokens=_snake_case ).input_ids[0] self.assertListEqual(_snake_case , _snake_case ) def snake_case_ ( self ) -> Tuple: """simple docstring""" UpperCAmelCase = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word UpperCAmelCase = '''<mask_1> To ensure a <mask_2> flow of bank resolutions.''' UpperCAmelCase = [2, 413, 615, 114, 3, 1971, 113, 1679, 1_0710, 107, 1] UpperCAmelCase = tokenizer([raw_input_str] , return_tensors=_snake_case ).input_ids[0] self.assertListEqual(_snake_case , _snake_case ) def snake_case_ ( self ) -> List[str]: """simple docstring""" UpperCAmelCase = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 9_6103 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 103 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 105 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 1024 UpperCAmelCase = '''To ensure a smooth flow of bank resolutions.''' UpperCAmelCase = [413, 615, 114, 2291, 1971, 113, 1679, 1_0710, 107, 1] UpperCAmelCase = tokenizer([raw_input_str] , return_tensors=_snake_case ).input_ids[0] self.assertListEqual(_snake_case , _snake_case ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def snake_case_ ( self ) -> List[str]: """simple docstring""" UpperCAmelCase = ['''This is going to be way too long.''' * 150, '''short example'''] UpperCAmelCase = ['''not super long but more than 5 tokens''', '''tiny'''] UpperCAmelCase = self._large_tokenizer(_snake_case , padding=_snake_case , truncation=_snake_case , return_tensors='''pt''' ) UpperCAmelCase = self._large_tokenizer( text_target=_snake_case , max_length=5 , padding=_snake_case , truncation=_snake_case , return_tensors='''pt''' ) assert batch.input_ids.shape == (2, 1024) assert batch.attention_mask.shape == (2, 1024) assert targets["input_ids"].shape == (2, 5) assert len(_snake_case ) == 2 # input_ids, attention_mask. @slow def snake_case_ ( self ) -> List[str]: """simple docstring""" # fmt: off UpperCAmelCase = {'''input_ids''': [[3_8979, 143, 1_8485, 606, 130, 2_6669, 8_7686, 121, 5_4189, 1129, 111, 2_6669, 8_7686, 121, 9114, 1_4787, 121, 1_3249, 158, 592, 956, 121, 1_4621, 3_1576, 143, 6_2613, 108, 9688, 930, 4_3430, 1_1562, 6_2613, 304, 108, 1_1443, 897, 108, 9314, 1_7415, 6_3399, 108, 1_1443, 7614, 1_8316, 118, 4284, 7148, 1_2430, 143, 1400, 2_5703, 158, 111, 4284, 7148, 1_1772, 143, 2_1297, 1064, 158, 122, 204, 3506, 1754, 1133, 1_4787, 1581, 115, 3_3224, 4482, 111, 1355, 110, 2_9173, 317, 5_0833, 108, 2_0147, 9_4665, 111, 7_7198, 107, 1], [110, 6_2613, 117, 638, 112, 1133, 121, 2_0098, 1355, 7_9050, 1_3872, 135, 1596, 5_3541, 1352, 141, 1_3039, 5542, 124, 302, 518, 111, 268, 2956, 115, 149, 4427, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [139, 1235, 2799, 1_8289, 1_7780, 204, 109, 9474, 1296, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=_snake_case , model_name='''google/bigbird-pegasus-large-arxiv''' , revision='''ba85d0851d708441f91440d509690f1ab6353415''' , ) @require_sentencepiece @require_tokenizers class lowercase ( A__ , unittest.TestCase ): '''simple docstring''' __SCREAMING_SNAKE_CASE = PegasusTokenizer __SCREAMING_SNAKE_CASE = PegasusTokenizerFast __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = True def snake_case_ ( self ) -> int: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing UpperCAmelCase = PegasusTokenizer(_snake_case , offset=0 , mask_token_sent=_snake_case , mask_token='''[MASK]''' ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def snake_case_ ( self ) -> Dict: """simple docstring""" return PegasusTokenizer.from_pretrained('''google/bigbird-pegasus-large-arxiv''' ) def snake_case_ ( self , **_snake_case ) -> PegasusTokenizer: """simple docstring""" return PegasusTokenizer.from_pretrained(self.tmpdirname , **_snake_case ) def snake_case_ ( self , _snake_case ) -> List[str]: """simple docstring""" return ("This is a test", "This is a test") def snake_case_ ( self ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) UpperCAmelCase = self.tokenizer_class.from_pretrained(self.tmpdirname ) UpperCAmelCase = ( '''Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>''' ''' <pad> <pad> <pad>''' ) UpperCAmelCase = rust_tokenizer([raw_input_str] , return_tensors=_snake_case , add_special_tokens=_snake_case ).input_ids[0] UpperCAmelCase = py_tokenizer([raw_input_str] , return_tensors=_snake_case , add_special_tokens=_snake_case ).input_ids[0] self.assertListEqual(_snake_case , _snake_case ) @require_torch def snake_case_ ( self ) -> Optional[Any]: """simple docstring""" UpperCAmelCase = ['''This is going to be way too long.''' * 1000, '''short example'''] UpperCAmelCase = ['''not super long but more than 5 tokens''', '''tiny'''] UpperCAmelCase = self._large_tokenizer(_snake_case , padding=_snake_case , truncation=_snake_case , return_tensors='''pt''' ) UpperCAmelCase = self._large_tokenizer( text_target=_snake_case , max_length=5 , padding=_snake_case , truncation=_snake_case , return_tensors='''pt''' ) assert batch.input_ids.shape == (2, 4096) assert batch.attention_mask.shape == (2, 4096) assert targets["input_ids"].shape == (2, 5) assert len(_snake_case ) == 2 # input_ids, attention_mask. def snake_case_ ( self ) -> Any: """simple docstring""" UpperCAmelCase = ( '''This is an example string that is used to test the original TF implementation against the HF''' ''' implementation''' ) UpperCAmelCase = self._large_tokenizer(_snake_case ).input_ids self.assertListEqual( _snake_case , [182, 117, 142, 587, 4211, 120, 117, 263, 112, 804, 109, 856, 2_5016, 3137, 464, 109, 2_6955, 3137, 1] , )
152
0
'''simple docstring''' from argparse import ArgumentParser, Namespace from typing import Any, List, Optional from ..pipelines import Pipeline, get_supported_tasks, pipeline from ..utils import logging from . import BaseTransformersCLICommand try: from fastapi import Body, FastAPI, HTTPException from fastapi.routing import APIRoute from pydantic import BaseModel from starlette.responses import JSONResponse from uvicorn import run UpperCAmelCase = True except (ImportError, AttributeError): UpperCAmelCase = object def __UpperCamelCase ( *lowercase__ : List[str], **lowercase__ : List[str] ): '''simple docstring''' pass UpperCAmelCase = False UpperCAmelCase = logging.get_logger('''transformers-cli/serving''') def __UpperCamelCase ( lowercase__ : Namespace ): '''simple docstring''' __lowercase =pipeline( task=args.task, model=args.model if args.model else None, config=args.config, tokenizer=args.tokenizer, device=args.device, ) return ServeCommand(lowercase__, args.host, args.port, args.workers ) class lowerCAmelCase ( A ): lowerCAmelCase_ = 42 class lowerCAmelCase ( A ): lowerCAmelCase_ = 42 lowerCAmelCase_ = 42 class lowerCAmelCase ( A ): lowerCAmelCase_ = 42 class lowerCAmelCase ( A ): lowerCAmelCase_ = 42 class lowerCAmelCase ( A ): @staticmethod def snake_case ( __lowercase : ArgumentParser ): """simple docstring""" __lowercase =parser.add_parser( 'serve' , help='CLI tool to run inference requests through REST and GraphQL endpoints.' ) serve_parser.add_argument( '--task' , type=__lowercase , choices=get_supported_tasks() , help='The task to run the pipeline on' , ) serve_parser.add_argument('--host' , type=__lowercase , default='localhost' , help='Interface the server will listen on.' ) serve_parser.add_argument('--port' , type=__lowercase , default=8888 , help='Port the serving will listen to.' ) serve_parser.add_argument('--workers' , type=__lowercase , default=1 , help='Number of http workers' ) serve_parser.add_argument('--model' , type=__lowercase , help='Model\'s name or path to stored model.' ) serve_parser.add_argument('--config' , type=__lowercase , help='Model\'s config name or path to stored model.' ) serve_parser.add_argument('--tokenizer' , type=__lowercase , help='Tokenizer name to use.' ) serve_parser.add_argument( '--device' , type=__lowercase , default=-1 , help='Indicate the device to run onto, -1 indicates CPU, >= 0 indicates GPU (default: -1)' , ) serve_parser.set_defaults(func=__lowercase ) def __init__( self : str , __lowercase : Pipeline , __lowercase : str , __lowercase : int , __lowercase : int ): """simple docstring""" __lowercase =pipeline __lowercase =host __lowercase =port __lowercase =workers if not _serve_dependencies_installed: raise RuntimeError( 'Using serve command requires FastAPI and uvicorn. ' 'Please install transformers with [serving]: pip install "transformers[serving]".' 'Or install FastAPI and uvicorn separately.' ) else: logger.info(f'''Serving model over {host}:{port}''' ) __lowercase =FastAPI( routes=[ APIRoute( '/' , self.model_info , response_model=__lowercase , response_class=__lowercase , methods=['GET'] , ), APIRoute( '/tokenize' , self.tokenize , response_model=__lowercase , response_class=__lowercase , methods=['POST'] , ), APIRoute( '/detokenize' , self.detokenize , response_model=__lowercase , response_class=__lowercase , methods=['POST'] , ), APIRoute( '/forward' , self.forward , response_model=__lowercase , response_class=__lowercase , methods=['POST'] , ), ] , timeout=600 , ) def snake_case ( self : Any ): """simple docstring""" run(self._app , host=self.host , port=self.port , workers=self.workers ) def snake_case ( self : Tuple ): """simple docstring""" return ServeModelInfoResult(infos=vars(self._pipeline.model.config ) ) def snake_case ( self : Any , __lowercase : str = Body(__lowercase , embed=__lowercase ) , __lowercase : bool = Body(__lowercase , embed=__lowercase ) ): """simple docstring""" try: __lowercase =self._pipeline.tokenizer.tokenize(__lowercase ) if return_ids: __lowercase =self._pipeline.tokenizer.convert_tokens_to_ids(__lowercase ) return ServeTokenizeResult(tokens=__lowercase , tokens_ids=__lowercase ) else: return ServeTokenizeResult(tokens=__lowercase ) except Exception as e: raise HTTPException(status_code=500 , detail={'model': '', 'error': str(__lowercase )} ) def snake_case ( self : Optional[int] , __lowercase : List[int] = Body(__lowercase , embed=__lowercase ) , __lowercase : bool = Body(__lowercase , embed=__lowercase ) , __lowercase : bool = Body(__lowercase , embed=__lowercase ) , ): """simple docstring""" try: __lowercase =self._pipeline.tokenizer.decode(__lowercase , __lowercase , __lowercase ) return ServeDeTokenizeResult(model='' , text=__lowercase ) except Exception as e: raise HTTPException(status_code=500 , detail={'model': '', 'error': str(__lowercase )} ) async def snake_case ( self : Any , __lowercase : Optional[Any]=Body(__lowercase , embed=__lowercase ) ): """simple docstring""" if len(__lowercase ) == 0: return ServeForwardResult(output=[] , attention=[] ) try: # Forward through the model __lowercase =self._pipeline(__lowercase ) return ServeForwardResult(output=__lowercase ) except Exception as e: raise HTTPException(500 , {'error': str(__lowercase )} )
141
'''simple docstring''' import heapq def __UpperCamelCase ( lowercase__ : dict ): '''simple docstring''' __lowercase =[] # for each node and his adjacency list add them and the rank of the node to queue # using heapq module the queue will be filled like a Priority Queue # heapq works with a min priority queue, so I used -1*len(v) to build it for key, value in graph.items(): # O(log(n)) heapq.heappush(lowercase__, [-1 * len(lowercase__ ), (key, value)] ) # chosen_vertices = set of chosen vertices __lowercase =set() # while queue isn't empty and there are still edges # (queue[0][0] is the rank of the node with max rank) while queue and queue[0][0] != 0: # extract vertex with max rank from queue and add it to chosen_vertices __lowercase =heapq.heappop(lowercase__ )[1][0] chosen_vertices.add(lowercase__ ) # Remove all arcs adjacent to argmax for elem in queue: # if v haven't adjacent node, skip if elem[0] == 0: continue # if argmax is reachable from elem # remove argmax from elem's adjacent list and update his rank if argmax in elem[1][1]: __lowercase =elem[1][1].index(lowercase__ ) del elem[1][1][index] elem[0] += 1 # re-order the queue heapq.heapify(lowercase__ ) return chosen_vertices if __name__ == "__main__": import doctest doctest.testmod() UpperCAmelCase = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} print(F'''Minimum vertex cover:\n{greedy_min_vertex_cover(graph)}''')
141
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowercase_ = { "configuration_rag": ["RagConfig"], "retrieval_rag": ["RagRetriever"], "tokenization_rag": ["RagTokenizer"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "RagModel", "RagPreTrainedModel", "RagSequenceForGeneration", "RagTokenForGeneration", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ "TFRagModel", "TFRagPreTrainedModel", "TFRagSequenceForGeneration", "TFRagTokenForGeneration", ] if TYPE_CHECKING: from .configuration_rag import RagConfig from .retrieval_rag import RagRetriever from .tokenization_rag import RagTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rag import ( TFRagModel, TFRagPreTrainedModel, TFRagSequenceForGeneration, TFRagTokenForGeneration, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
282
from collections.abc import Sequence def _snake_case( SCREAMING_SNAKE_CASE__ : Sequence[int] | None = None ) -> int: '''simple docstring''' if nums is None or not nums: raise ValueError('Input sequence should not be empty' ) A__ = nums[0] for i in range(1 , len(SCREAMING_SNAKE_CASE__ ) ): A__ = nums[i] A__ = max(SCREAMING_SNAKE_CASE__ , ans + num , SCREAMING_SNAKE_CASE__ ) return ans if __name__ == "__main__": import doctest doctest.testmod() # Try on a sample input from the user lowercase_ = int(input("Enter number of elements : ").strip()) lowercase_ = list(map(int, input("\nEnter the numbers : ").strip().split()))[:n] print(max_subsequence_sum(array))
282
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) lowercase__ : List[Any] = {"configuration_fnet": ["FNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "FNetConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ : List[str] = ["FNetTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ : Dict = ["FNetTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ : Dict = [ "FNET_PRETRAINED_MODEL_ARCHIVE_LIST", "FNetForMaskedLM", "FNetForMultipleChoice", "FNetForNextSentencePrediction", "FNetForPreTraining", "FNetForQuestionAnswering", "FNetForSequenceClassification", "FNetForTokenClassification", "FNetLayer", "FNetModel", "FNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_fnet import FNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet import FNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet_fast import FNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_fnet import ( FNET_PRETRAINED_MODEL_ARCHIVE_LIST, FNetForMaskedLM, FNetForMultipleChoice, FNetForNextSentencePrediction, FNetForPreTraining, FNetForQuestionAnswering, FNetForSequenceClassification, FNetForTokenClassification, FNetLayer, FNetModel, FNetPreTrainedModel, ) else: import sys lowercase__ : Optional[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
187
from __future__ import annotations import inspect import unittest from transformers import ViTConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFViTForImageClassification, TFViTModel if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class A : """simple docstring""" def __init__( self : Union[str, Any],lowercase_ : Any,lowercase_ : Union[str, Any]=1_3,lowercase_ : Tuple=3_0,lowercase_ : List[Any]=2,lowercase_ : Optional[int]=3,lowercase_ : Union[str, Any]=True,lowercase_ : Tuple=True,lowercase_ : Any=3_2,lowercase_ : List[str]=2,lowercase_ : Optional[int]=4,lowercase_ : Union[str, Any]=3_7,lowercase_ : Tuple="gelu",lowercase_ : str=0.1,lowercase_ : Tuple=0.1,lowercase_ : Union[str, Any]=1_0,lowercase_ : int=0.02,lowercase_ : List[Any]=3,lowercase_ : Any=None,)-> Dict: '''simple docstring''' A__ = parent A__ = batch_size A__ = image_size A__ = patch_size A__ = num_channels A__ = is_training A__ = use_labels A__ = hidden_size A__ = num_hidden_layers A__ = num_attention_heads A__ = intermediate_size A__ = hidden_act A__ = hidden_dropout_prob A__ = attention_probs_dropout_prob A__ = type_sequence_label_size A__ = initializer_range A__ = scope # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) A__ = (image_size // patch_size) ** 2 A__ = num_patches + 1 def snake_case__ ( self : int )-> List[str]: '''simple docstring''' A__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) A__ = None if self.use_labels: A__ = ids_tensor([self.batch_size],self.type_sequence_label_size ) A__ = self.get_config() return config, pixel_values, labels def snake_case__ ( self : Tuple )-> List[Any]: '''simple docstring''' return ViTConfig( image_size=self.image_size,patch_size=self.patch_size,num_channels=self.num_channels,hidden_size=self.hidden_size,num_hidden_layers=self.num_hidden_layers,num_attention_heads=self.num_attention_heads,intermediate_size=self.intermediate_size,hidden_act=self.hidden_act,hidden_dropout_prob=self.hidden_dropout_prob,attention_probs_dropout_prob=self.attention_probs_dropout_prob,is_decoder=lowercase_,initializer_range=self.initializer_range,) def snake_case__ ( self : List[str],lowercase_ : int,lowercase_ : Union[str, Any],lowercase_ : Tuple )-> Optional[Any]: '''simple docstring''' A__ = TFViTModel(config=lowercase_ ) A__ = model(lowercase_,training=lowercase_ ) self.parent.assertEqual(result.last_hidden_state.shape,(self.batch_size, self.seq_length, self.hidden_size) ) # Test with an image with different size than the one specified in config. A__ = self.image_size // 2 A__ = pixel_values[:, :, :image_size, :image_size] A__ = model(lowercase_,interpolate_pos_encoding=lowercase_,training=lowercase_ ) A__ = (image_size // self.patch_size) ** 2 + 1 self.parent.assertEqual(result.last_hidden_state.shape,(self.batch_size, seq_length, self.hidden_size) ) def snake_case__ ( self : List[Any],lowercase_ : List[Any],lowercase_ : List[Any],lowercase_ : List[Any] )-> Dict: '''simple docstring''' A__ = self.type_sequence_label_size A__ = TFViTForImageClassification(lowercase_ ) A__ = model(lowercase_,labels=lowercase_,training=lowercase_ ) self.parent.assertEqual(result.logits.shape,(self.batch_size, self.type_sequence_label_size) ) # Test with an image with different size than the one specified in config. A__ = self.image_size // 2 A__ = pixel_values[:, :, :image_size, :image_size] A__ = model(lowercase_,interpolate_pos_encoding=lowercase_,training=lowercase_ ) self.parent.assertEqual(result.logits.shape,(self.batch_size, self.type_sequence_label_size) ) # test greyscale images A__ = 1 A__ = TFViTForImageClassification(lowercase_ ) A__ = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) A__ = model(lowercase_ ) self.parent.assertEqual(result.logits.shape,(self.batch_size, self.type_sequence_label_size) ) def snake_case__ ( self : Any )-> Optional[Any]: '''simple docstring''' A__ = self.prepare_config_and_inputs() A__ , A__ , A__ = config_and_inputs A__ = {'pixel_values': pixel_values} return config, inputs_dict @require_tf class A ( _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): """simple docstring""" lowerCamelCase = (TFViTModel, TFViTForImageClassification) if is_tf_available() else () lowerCamelCase = ( {'feature-extraction': TFViTModel, 'image-classification': TFViTForImageClassification} if is_tf_available() else {} ) lowerCamelCase = False lowerCamelCase = False lowerCamelCase = False def snake_case__ ( self : int )-> List[Any]: '''simple docstring''' A__ = TFViTModelTester(self ) A__ = ConfigTester(self,config_class=lowercase_,has_text_modality=lowercase_,hidden_size=3_7 ) def snake_case__ ( self : Any )-> Optional[Any]: '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason='ViT does not use inputs_embeds' ) def snake_case__ ( self : Optional[Any] )-> str: '''simple docstring''' pass @unittest.skip(reason='ViT does not use inputs_embeds' ) def snake_case__ ( self : Any )-> int: '''simple docstring''' pass def snake_case__ ( self : str )-> Dict: '''simple docstring''' A__ , A__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A__ = model_class(lowercase_ ) self.assertIsInstance(model.get_input_embeddings(),(tf.keras.layers.Layer) ) A__ = model.get_output_embeddings() self.assertTrue(x is None or isinstance(lowercase_,tf.keras.layers.Layer ) ) def snake_case__ ( self : int )-> List[str]: '''simple docstring''' A__ , A__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A__ = model_class(lowercase_ ) 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],lowercase_ ) def snake_case__ ( self : Union[str, Any] )-> Optional[Any]: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase_ ) def snake_case__ ( self : Optional[Any] )-> Optional[Any]: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowercase_ ) @slow def snake_case__ ( self : Union[str, Any] )-> Union[str, Any]: '''simple docstring''' A__ = TFViTModel.from_pretrained('google/vit-base-patch16-224' ) self.assertIsNotNone(lowercase_ ) def _snake_case( ) -> str: '''simple docstring''' A__ = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf @require_vision class A ( unittest.TestCase ): """simple docstring""" @cached_property def snake_case__ ( self : List[Any] )-> str: '''simple docstring''' return ViTImageProcessor.from_pretrained('google/vit-base-patch16-224' ) if is_vision_available() else None @slow def snake_case__ ( self : Any )-> Dict: '''simple docstring''' A__ = TFViTForImageClassification.from_pretrained('google/vit-base-patch16-224' ) A__ = self.default_image_processor A__ = prepare_img() A__ = image_processor(images=lowercase_,return_tensors='tf' ) # forward pass A__ = model(**lowercase_ ) # verify the logits A__ = tf.TensorShape((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape,lowercase_ ) A__ = tf.constant([-0.2_744, 0.8_215, -0.0_836] ) tf.debugging.assert_near(outputs.logits[0, :3],lowercase_,atol=1E-4 )
7
0
import dataclasses import re import string from typing import Any, Dict, Iterator, List, Mapping, Optional, Sequence, Tuple import numpy as np from . import residue_constants snake_case__ : Union[str, Any] = Mapping[str, np.ndarray] snake_case__ : List[str] = Mapping[str, Any] # Is a nested dict. snake_case__ : Optional[Any] = 0.01 @dataclasses.dataclass(frozen=_lowerCamelCase ) class A_ : lowerCAmelCase__ = 42 # [num_res, num_atom_type, 3] # Amino-acid type for each residue represented as an integer between 0 and # 20, where 20 is 'X'. lowerCAmelCase__ = 42 # [num_res] # Binary float mask to indicate presence of a particular atom. 1.0 if an atom # is present and 0.0 if not. This should be used for loss masking. lowerCAmelCase__ = 42 # [num_res, num_atom_type] # Residue index as used in PDB. It is not necessarily continuous or 0-indexed. lowerCAmelCase__ = 42 # [num_res] # B-factors, or temperature factors, of each residue (in sq. angstroms units), # representing the displacement of the residue from its ground truth mean # value. lowerCAmelCase__ = 42 # [num_res, num_atom_type] # Chain indices for multi-chain predictions lowerCAmelCase__ = None # Optional remark about the protein. Included as a comment in output PDB # files lowerCAmelCase__ = None # Templates used to generate this protein (prediction-only) lowerCAmelCase__ = None # Chain corresponding to each parent lowerCAmelCase__ = None def _a ( lowerCamelCase: str ) -> Protein: '''simple docstring''' __A = r'''(\[[A-Z]+\]\n)''' __A = [tag.strip() for tag in re.split(lowerCamelCase , lowerCamelCase ) if len(lowerCamelCase ) > 0] __A = zip(tags[0::2] , [l.split('''\n''' ) for l in tags[1::2]] ) __A = ["N", "CA", "C"] __A = None __A = None __A = None for g in groups: if "[PRIMARY]" == g[0]: __A = g[1][0].strip() for i in range(len(lowerCamelCase ) ): if seq[i] not in residue_constants.restypes: __A = '''X''' # FIXME: strings are immutable __A = np.array( [residue_constants.restype_order.get(lowerCamelCase , residue_constants.restype_num ) for res_symbol in seq] ) elif "[TERTIARY]" == g[0]: __A = [] for axis in range(3 ): tertiary.append(list(map(lowerCamelCase , g[1][axis].split() ) ) ) __A = np.array(lowerCamelCase ) __A = np.zeros((len(tertiary[0] ) // 3, residue_constants.atom_type_num, 3) ).astype(np.floataa ) for i, atom in enumerate(lowerCamelCase ): __A = np.transpose(tertiary_np[:, i::3] ) atom_positions *= PICO_TO_ANGSTROM elif "[MASK]" == g[0]: __A = np.array(list(map({'''-''': 0, '''+''': 1}.get , g[1][0].strip() ) ) ) __A = np.zeros( ( len(lowerCamelCase ), residue_constants.atom_type_num, ) ).astype(np.floataa ) for i, atom in enumerate(lowerCamelCase ): __A = 1 atom_mask *= mask[..., None] assert aatype is not None return Protein( atom_positions=lowerCamelCase , atom_mask=lowerCamelCase , aatype=lowerCamelCase , residue_index=np.arange(len(lowerCamelCase ) ) , b_factors=lowerCamelCase , ) def _a ( lowerCamelCase: Protein , lowerCamelCase: int = 0 ) -> List[str]: '''simple docstring''' __A = [] __A = prot.remark if remark is not None: pdb_headers.append(F"""REMARK {remark}""" ) __A = prot.parents __A = prot.parents_chain_index if parents is not None and parents_chain_index is not None: __A = [p for i, p in zip(lowerCamelCase , lowerCamelCase ) if i == chain_id] if parents is None or len(lowerCamelCase ) == 0: __A = ['''N/A'''] pdb_headers.append(F"""PARENT {' '.join(lowerCamelCase )}""" ) return pdb_headers def _a ( lowerCamelCase: Protein , lowerCamelCase: str ) -> str: '''simple docstring''' __A = [] __A = pdb_str.split('''\n''' ) __A = prot.remark if remark is not None: out_pdb_lines.append(F"""REMARK {remark}""" ) __A = 42 if prot.parents is not None and len(prot.parents ) > 0: __A = [] if prot.parents_chain_index is not None: __A = {} for p, i in zip(prot.parents , prot.parents_chain_index ): parent_dict.setdefault(str(lowerCamelCase ) , [] ) parent_dict[str(lowerCamelCase )].append(lowerCamelCase ) __A = max([int(lowerCamelCase ) for chain_idx in parent_dict] ) for i in range(max_idx + 1 ): __A = parent_dict.get(str(lowerCamelCase ) , ['''N/A'''] ) parents_per_chain.append(lowerCamelCase ) else: parents_per_chain.append(list(prot.parents ) ) else: __A = [['''N/A''']] def make_parent_line(lowerCamelCase: Sequence[str] ) -> str: return F"""PARENT {' '.join(lowerCamelCase )}""" out_pdb_lines.append(make_parent_line(parents_per_chain[0] ) ) __A = 0 for i, l in enumerate(lowerCamelCase ): if "PARENT" not in l and "REMARK" not in l: out_pdb_lines.append(lowerCamelCase ) if "TER" in l and "END" not in lines[i + 1]: chain_counter += 1 if not chain_counter >= len(lowerCamelCase ): __A = parents_per_chain[chain_counter] else: __A = ['''N/A'''] out_pdb_lines.append(make_parent_line(lowerCamelCase ) ) return "\n".join(lowerCamelCase ) def _a ( lowerCamelCase: Protein ) -> str: '''simple docstring''' __A = residue_constants.restypes + ['''X'''] def res_atoa(lowerCamelCase: int ) -> str: return residue_constants.restype_atoa.get(restypes[r] , '''UNK''' ) __A = residue_constants.atom_types __A = [] __A = prot.atom_mask __A = prot.aatype __A = prot.atom_positions __A = prot.residue_index.astype(np.intaa ) __A = prot.b_factors __A = prot.chain_index if np.any(aatype > residue_constants.restype_num ): raise ValueError('''Invalid aatypes.''' ) __A = get_pdb_headers(lowerCamelCase ) if len(lowerCamelCase ) > 0: pdb_lines.extend(lowerCamelCase ) __A = aatype.shape[0] __A = 1 __A = 0 __A = string.ascii_uppercase __A = None # Add all atom sites. for i in range(lowerCamelCase ): __A = res_atoa(aatype[i] ) for atom_name, pos, mask, b_factor in zip(lowerCamelCase , atom_positions[i] , atom_mask[i] , b_factors[i] ): if mask < 0.5: continue __A = '''ATOM''' __A = atom_name if len(lowerCamelCase ) == 4 else F""" {atom_name}""" __A = '''''' __A = '''''' __A = 1.00 __A = atom_name[0] # Protein supports only C, N, O, S, this works. __A = '''''' __A = '''A''' if chain_index is not None: __A = chain_tags[chain_index[i]] # PDB is a columnar format, every space matters here! __A = ( F"""{record_type:<6}{atom_index:>5} {name:<4}{alt_loc:>1}""" F"""{res_name_a:>3} {chain_tag:>1}""" F"""{residue_index[i]:>4}{insertion_code:>1} """ F"""{pos[0]:>8.3f}{pos[1]:>8.3f}{pos[2]:>8.3f}""" F"""{occupancy:>6.2f}{b_factor:>6.2f} """ F"""{element:>2}{charge:>2}""" ) pdb_lines.append(lowerCamelCase ) atom_index += 1 __A = i == n - 1 if chain_index is not None: if i != n - 1 and chain_index[i + 1] != prev_chain_index: __A = True __A = chain_index[i + 1] if should_terminate: # Close the chain. __A = '''TER''' __A = ( F"""{chain_end:<6}{atom_index:>5} {res_atoa(aatype[i] ):>3} {chain_tag:>1}{residue_index[i]:>4}""" ) pdb_lines.append(lowerCamelCase ) atom_index += 1 if i != n - 1: # "prev" is a misnomer here. This happens at the beginning of # each new chain. pdb_lines.extend(get_pdb_headers(lowerCamelCase , lowerCamelCase ) ) pdb_lines.append('''END''' ) pdb_lines.append('''''' ) return "\n".join(lowerCamelCase ) def _a ( lowerCamelCase: Protein ) -> np.ndarray: '''simple docstring''' return residue_constants.STANDARD_ATOM_MASK[prot.aatype] def _a ( lowerCamelCase: FeatureDict , lowerCamelCase: ModelOutput , lowerCamelCase: Optional[np.ndarray] = None , lowerCamelCase: Optional[np.ndarray] = None , lowerCamelCase: Optional[str] = None , lowerCamelCase: Optional[Sequence[str]] = None , lowerCamelCase: Optional[Sequence[int]] = None , ) -> Protein: '''simple docstring''' return Protein( aatype=features['''aatype'''] , atom_positions=result['''final_atom_positions'''] , atom_mask=result['''final_atom_mask'''] , residue_index=features['''residue_index'''] + 1 , b_factors=b_factors if b_factors is not None else np.zeros_like(result['''final_atom_mask'''] ) , chain_index=lowerCamelCase , remark=lowerCamelCase , parents=lowerCamelCase , parents_chain_index=lowerCamelCase , )
250
def _a ( lowerCamelCase: 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_54 for octet in octets ) if __name__ == "__main__": snake_case__ : Union[str, Any] = input().strip() snake_case__ : Any = 'valid' if is_ip_va_address_valid(ip) else 'invalid' print(f'{ip} is a {valid_or_invalid} IP v4 address.')
250
1
import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def _lowercase ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE__ = BertConfig.from_json_file(UpperCamelCase_ ) print(F'Building PyTorch model from configuration: {config}' ) SCREAMING_SNAKE_CASE__ = BertForPreTraining(UpperCamelCase_ ) # Load weights from tf checkpoint load_tf_weights_in_bert(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) # Save pytorch-model print(F'Save PyTorch model to {pytorch_dump_path}' ) torch.save(model.state_dict() , UpperCamelCase_ ) if __name__ == "__main__": __snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument( """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--bert_config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained BERT model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) __snake_case = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
176
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 __snake_case = logging.get_logger(__name__) __snake_case = {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_file""": """tokenizer.json"""} # See all BART models at https://huggingface.co/models?filter=bart __snake_case = { """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""", }, } __snake_case = { """facebook/bart-base""": 10_24, """facebook/bart-large""": 10_24, """facebook/bart-large-mnli""": 10_24, """facebook/bart-large-cnn""": 10_24, """facebook/bart-large-xsum""": 10_24, """yjernite/bart_eli5""": 10_24, } class lowercase__ ( _UpperCAmelCase ): A__ : Tuple =VOCAB_FILES_NAMES A__ : Any =PRETRAINED_VOCAB_FILES_MAP A__ : str =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A__ : Tuple =["""input_ids""", """attention_mask"""] A__ : Optional[int] =BartTokenizer def __init__( self : str , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : int=None , UpperCAmelCase_ : str=None , UpperCAmelCase_ : Optional[Any]="replace" , UpperCAmelCase_ : int="<s>" , UpperCAmelCase_ : List[Any]="</s>" , UpperCAmelCase_ : int="</s>" , UpperCAmelCase_ : Tuple="<s>" , UpperCAmelCase_ : Any="<unk>" , UpperCAmelCase_ : Any="<pad>" , UpperCAmelCase_ : Optional[Any]="<mask>" , UpperCAmelCase_ : Optional[int]=False , UpperCAmelCase_ : List[str]=True , **UpperCAmelCase_ : List[Any] , ): 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_ , ) SCREAMING_SNAKE_CASE__ = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get('add_prefix_space' , UpperCAmelCase_ ) != add_prefix_space: SCREAMING_SNAKE_CASE__ = getattr(UpperCAmelCase_ , pre_tok_state.pop('type' ) ) SCREAMING_SNAKE_CASE__ = add_prefix_space SCREAMING_SNAKE_CASE__ = pre_tok_class(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE__ = add_prefix_space # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__` SCREAMING_SNAKE_CASE__ = 'post_processor' SCREAMING_SNAKE_CASE__ = getattr(self.backend_tokenizer , UpperCAmelCase_ , UpperCAmelCase_ ) if tokenizer_component_instance: SCREAMING_SNAKE_CASE__ = 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: SCREAMING_SNAKE_CASE__ = tuple(state['sep'] ) if "cls" in state: SCREAMING_SNAKE_CASE__ = tuple(state['cls'] ) SCREAMING_SNAKE_CASE__ = False if state.get('add_prefix_space' , UpperCAmelCase_ ) != add_prefix_space: SCREAMING_SNAKE_CASE__ = add_prefix_space SCREAMING_SNAKE_CASE__ = True if state.get('trim_offsets' , UpperCAmelCase_ ) != trim_offsets: SCREAMING_SNAKE_CASE__ = trim_offsets SCREAMING_SNAKE_CASE__ = True if changes_to_apply: SCREAMING_SNAKE_CASE__ = getattr(UpperCAmelCase_ , state.pop('type' ) ) SCREAMING_SNAKE_CASE__ = component_class(**UpperCAmelCase_ ) setattr(self.backend_tokenizer , UpperCAmelCase_ , UpperCAmelCase_ ) @property def A_ ( self : Tuple ): 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 A_ ( self : Any , UpperCAmelCase_ : List[Any] ): SCREAMING_SNAKE_CASE__ = AddedToken(UpperCAmelCase_ , lstrip=UpperCAmelCase_ , rstrip=UpperCAmelCase_ ) if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) else value SCREAMING_SNAKE_CASE__ = value def A_ ( self : List[str] , *UpperCAmelCase_ : Tuple , **UpperCAmelCase_ : str ): SCREAMING_SNAKE_CASE__ = 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 A_ ( self : List[str] , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : int ): SCREAMING_SNAKE_CASE__ = 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 A_ ( self : List[str] , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None ): SCREAMING_SNAKE_CASE__ = self._tokenizer.model.save(UpperCAmelCase_ , name=UpperCAmelCase_ ) return tuple(UpperCAmelCase_ ) def A_ ( self : Optional[Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Union[str, Any]=None ): SCREAMING_SNAKE_CASE__ = [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 A_ ( self : str , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ): SCREAMING_SNAKE_CASE__ = [self.sep_token_id] SCREAMING_SNAKE_CASE__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
176
1
'''simple docstring''' import unittest from transformers import DonutProcessor __UpperCAmelCase :Tuple = '''naver-clova-ix/donut-base''' class a ( unittest.TestCase ): """simple docstring""" def lowerCamelCase__ ( self : Any ) -> Dict: __UpperCAmelCase : Optional[int] = DonutProcessor.from_pretrained(snake_case ) def lowerCamelCase__ ( self : str ) -> str: __UpperCAmelCase : Optional[int] = { "name": "John Doe", "age": "99", "city": "Atlanta", "state": "GA", "zip": "30301", "phone": "123-4567", "nicknames": [{"nickname": "Johnny"}, {"nickname": "JD"}], } __UpperCAmelCase : List[str] = ( "<s_name>John Doe</s_name><s_age>99</s_age><s_city>Atlanta</s_city>" "<s_state>GA</s_state><s_zip>30301</s_zip><s_phone>123-4567</s_phone>" "<s_nicknames><s_nickname>Johnny</s_nickname>" "<sep/><s_nickname>JD</s_nickname></s_nicknames>" ) __UpperCAmelCase : Dict = self.processor.tokenajson(snake_case ) self.assertDictEqual(snake_case , snake_case )
354
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) __UpperCAmelCase :List[Any] = { "configuration_lxmert": ["LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "LxmertConfig"], "tokenization_lxmert": ["LxmertTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase :List[Any] = ["LxmertTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase :List[Any] = [ "LxmertEncoder", "LxmertForPreTraining", "LxmertForQuestionAnswering", "LxmertModel", "LxmertPreTrainedModel", "LxmertVisualFeatureEncoder", "LxmertXLayer", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase :List[str] = [ "TF_LXMERT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFLxmertForPreTraining", "TFLxmertMainLayer", "TFLxmertModel", "TFLxmertPreTrainedModel", "TFLxmertVisualFeatureEncoder", ] if TYPE_CHECKING: from .configuration_lxmert import LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, LxmertConfig from .tokenization_lxmert import LxmertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_lxmert_fast import LxmertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_lxmert import ( LxmertEncoder, LxmertForPreTraining, LxmertForQuestionAnswering, LxmertModel, LxmertPreTrainedModel, LxmertVisualFeatureEncoder, LxmertXLayer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_lxmert import ( TF_LXMERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFLxmertForPreTraining, TFLxmertMainLayer, TFLxmertModel, TFLxmertPreTrainedModel, TFLxmertVisualFeatureEncoder, ) else: import sys __UpperCAmelCase :int = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
240
0
"""simple docstring""" from typing import Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging 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(): from ..models.auto.modeling_auto import MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING _a = logging.get_logger(__name__) @add_end_docstrings(lowerCAmelCase_ ) class A_ (lowerCAmelCase_ ): '''simple docstring''' def __init__( self , *lowercase_ , **lowercase_ ): """simple docstring""" super().__init__(*lowerCamelCase__ , **lowerCamelCase__ ) self.check_model_type(lowerCamelCase__ ) def UpperCamelCase__ ( self , lowercase_=None , lowercase_=None , lowercase_=None , **lowercase_ ): """simple docstring""" UpperCAmelCase_ , UpperCAmelCase_ : List[Any] = {}, {} if padding is not None: UpperCAmelCase_ : int = padding if truncation is not None: UpperCAmelCase_ : List[Any] = truncation if top_k is not None: UpperCAmelCase_ : int = top_k return preprocess_params, {}, postprocess_params def __call__( self , lowercase_ , lowercase_ = None , **lowercase_ ): """simple docstring""" if isinstance(lowerCamelCase__ , (Image.Image, str) ) and isinstance(lowerCamelCase__ , lowerCamelCase__ ): UpperCAmelCase_ : Optional[int] = {"image": image, "question": question} else: UpperCAmelCase_ : Tuple = image UpperCAmelCase_ : Tuple = super().__call__(lowerCamelCase__ , **lowerCamelCase__ ) return results def UpperCamelCase__ ( self , lowercase_ , lowercase_=False , lowercase_=False ): """simple docstring""" UpperCAmelCase_ : Optional[Any] = load_image(inputs["image"] ) UpperCAmelCase_ : Tuple = self.tokenizer( inputs["question"] , return_tensors=self.framework , padding=lowerCamelCase__ , truncation=lowerCamelCase__ ) UpperCAmelCase_ : Union[str, Any] = self.image_processor(images=lowerCamelCase__ , return_tensors=self.framework ) model_inputs.update(lowerCamelCase__ ) return model_inputs def UpperCamelCase__ ( self , lowercase_ ): """simple docstring""" UpperCAmelCase_ : Tuple = self.model(**lowerCamelCase__ ) return model_outputs def UpperCamelCase__ ( self , lowercase_ , lowercase_=5 ): """simple docstring""" if top_k > self.model.config.num_labels: UpperCAmelCase_ : int = self.model.config.num_labels if self.framework == "pt": UpperCAmelCase_ : List[Any] = model_outputs.logits.sigmoid()[0] UpperCAmelCase_ , UpperCAmelCase_ : Union[str, Any] = probs.topk(lowerCamelCase__ ) else: raise ValueError(F"""Unsupported framework: {self.framework}""" ) UpperCAmelCase_ : Union[str, Any] = scores.tolist() UpperCAmelCase_ : List[str] = ids.tolist() return [{"score": score, "answer": self.model.config.idalabel[_id]} for score, _id in zip(lowerCamelCase__ , lowerCamelCase__ )]
61
import argparse import json import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinConfig, SwinForImageClassification def __lowercase ( _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = SwinConfig() SCREAMING_SNAKE_CASE = swin_name.split("""_""" ) SCREAMING_SNAKE_CASE = name_split[1] SCREAMING_SNAKE_CASE = int(name_split[4] ) SCREAMING_SNAKE_CASE = int(name_split[3][-1] ) if model_size == "tiny": SCREAMING_SNAKE_CASE = 96 SCREAMING_SNAKE_CASE = (2, 2, 6, 2) SCREAMING_SNAKE_CASE = (3, 6, 12, 24) elif model_size == "small": SCREAMING_SNAKE_CASE = 96 SCREAMING_SNAKE_CASE = (2, 2, 18, 2) SCREAMING_SNAKE_CASE = (3, 6, 12, 24) elif model_size == "base": SCREAMING_SNAKE_CASE = 1_28 SCREAMING_SNAKE_CASE = (2, 2, 18, 2) SCREAMING_SNAKE_CASE = (4, 8, 16, 32) else: SCREAMING_SNAKE_CASE = 1_92 SCREAMING_SNAKE_CASE = (2, 2, 18, 2) SCREAMING_SNAKE_CASE = (6, 12, 24, 48) if "in22k" in swin_name: SCREAMING_SNAKE_CASE = 2_18_41 else: SCREAMING_SNAKE_CASE = 10_00 SCREAMING_SNAKE_CASE = """huggingface/label-files""" SCREAMING_SNAKE_CASE = """imagenet-1k-id2label.json""" SCREAMING_SNAKE_CASE = json.load(open(hf_hub_download(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , repo_type="""dataset""" ) , """r""" ) ) SCREAMING_SNAKE_CASE = {int(_SCREAMING_SNAKE_CASE ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE = idalabel SCREAMING_SNAKE_CASE = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE = img_size SCREAMING_SNAKE_CASE = num_classes SCREAMING_SNAKE_CASE = embed_dim SCREAMING_SNAKE_CASE = depths SCREAMING_SNAKE_CASE = num_heads SCREAMING_SNAKE_CASE = window_size return config def __lowercase ( _SCREAMING_SNAKE_CASE ) -> Dict: '''simple docstring''' if "patch_embed.proj" in name: SCREAMING_SNAKE_CASE = name.replace("""patch_embed.proj""" , """embeddings.patch_embeddings.projection""" ) if "patch_embed.norm" in name: SCREAMING_SNAKE_CASE = name.replace("""patch_embed.norm""" , """embeddings.norm""" ) if "layers" in name: SCREAMING_SNAKE_CASE = """encoder.""" + name if "attn.proj" in name: SCREAMING_SNAKE_CASE = name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name: SCREAMING_SNAKE_CASE = name.replace("""attn""" , """attention.self""" ) if "norm1" in name: SCREAMING_SNAKE_CASE = name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: SCREAMING_SNAKE_CASE = name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: SCREAMING_SNAKE_CASE = name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: SCREAMING_SNAKE_CASE = name.replace("""mlp.fc2""" , """output.dense""" ) if name == "norm.weight": SCREAMING_SNAKE_CASE = """layernorm.weight""" if name == "norm.bias": SCREAMING_SNAKE_CASE = """layernorm.bias""" if "head" in name: SCREAMING_SNAKE_CASE = name.replace("""head""" , """classifier""" ) else: SCREAMING_SNAKE_CASE = """swin.""" + name return name def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: '''simple docstring''' for key in orig_state_dict.copy().keys(): SCREAMING_SNAKE_CASE = orig_state_dict.pop(_SCREAMING_SNAKE_CASE ) if "mask" in key: continue elif "qkv" in key: SCREAMING_SNAKE_CASE = key.split(""".""" ) SCREAMING_SNAKE_CASE = int(key_split[1] ) SCREAMING_SNAKE_CASE = int(key_split[3] ) SCREAMING_SNAKE_CASE = model.swin.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: SCREAMING_SNAKE_CASE = val[:dim, :] SCREAMING_SNAKE_CASE = val[ dim : dim * 2, : ] SCREAMING_SNAKE_CASE = val[-dim:, :] else: SCREAMING_SNAKE_CASE = val[ :dim ] SCREAMING_SNAKE_CASE = val[ dim : dim * 2 ] SCREAMING_SNAKE_CASE = val[ -dim: ] else: SCREAMING_SNAKE_CASE = val return orig_state_dict def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE = timm.create_model(_SCREAMING_SNAKE_CASE , pretrained=_SCREAMING_SNAKE_CASE ) timm_model.eval() SCREAMING_SNAKE_CASE = get_swin_config(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = SwinForImageClassification(_SCREAMING_SNAKE_CASE ) model.eval() SCREAMING_SNAKE_CASE = convert_state_dict(timm_model.state_dict() , _SCREAMING_SNAKE_CASE ) model.load_state_dict(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = """http://images.cocodataset.org/val2017/000000039769.jpg""" SCREAMING_SNAKE_CASE = AutoImageProcessor.from_pretrained("""microsoft/{}""".format(swin_name.replace("""_""" , """-""" ) ) ) SCREAMING_SNAKE_CASE = Image.open(requests.get(_SCREAMING_SNAKE_CASE , stream=_SCREAMING_SNAKE_CASE ).raw ) SCREAMING_SNAKE_CASE = image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors="""pt""" ) SCREAMING_SNAKE_CASE = timm_model(inputs["""pixel_values"""] ) SCREAMING_SNAKE_CASE = model(**_SCREAMING_SNAKE_CASE ).logits assert torch.allclose(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , atol=1E-3 ) print(F"""Saving model {swin_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) print(F"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--swin_name""", default="""swin_tiny_patch4_window7_224""", type=str, help="""Name of the Swin timm model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) SCREAMING_SNAKE_CASE_ = parser.parse_args() convert_swin_checkpoint(args.swin_name, args.pytorch_dump_folder_path)
296
0
'''simple docstring''' def lowerCAmelCase__ ( lowerCamelCase : int ): _A : Dict = 0 while num > 0: digit_sum += num % 10 num //= 10 return digit_sum def lowerCAmelCase__ ( lowerCamelCase : int = 100 ): _A : Dict = 1 _A : Union[str, Any] = 2 for i in range(2 ,max_n + 1 ): _A : List[Any] = pre_numerator _A : Dict = 2 * i // 3 if i % 3 == 0 else 1 _A : Any = cur_numerator _A : str = e_cont * pre_numerator + temp return sum_digits(lowercase__ ) if __name__ == "__main__": print(f"""{solution() = }""")
351
'''simple docstring''' from collections import OrderedDict from typing import TYPE_CHECKING, Any, List, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import TensorType, logging if TYPE_CHECKING: from ...onnx.config import PatchingSpec from ...tokenization_utils_base import PreTrainedTokenizerBase A : Tuple = logging.get_logger(__name__) A : Tuple = { '''allenai/longformer-base-4096''': '''https://huggingface.co/allenai/longformer-base-4096/resolve/main/config.json''', '''allenai/longformer-large-4096''': '''https://huggingface.co/allenai/longformer-large-4096/resolve/main/config.json''', '''allenai/longformer-large-4096-finetuned-triviaqa''': ( '''https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/config.json''' ), '''allenai/longformer-base-4096-extra.pos.embd.only''': ( '''https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/config.json''' ), '''allenai/longformer-large-4096-extra.pos.embd.only''': ( '''https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/config.json''' ), } class __lowerCamelCase ( a_ ): """simple docstring""" a = "longformer" def __init__( self : Any , SCREAMING_SNAKE_CASE : Union[List[int], int] = 512 , SCREAMING_SNAKE_CASE : int = 2 , SCREAMING_SNAKE_CASE : int = 1 , SCREAMING_SNAKE_CASE : int = 0 , SCREAMING_SNAKE_CASE : int = 2 , SCREAMING_SNAKE_CASE : int = 30522 , SCREAMING_SNAKE_CASE : int = 768 , SCREAMING_SNAKE_CASE : int = 12 , SCREAMING_SNAKE_CASE : int = 12 , SCREAMING_SNAKE_CASE : int = 3072 , SCREAMING_SNAKE_CASE : str = "gelu" , SCREAMING_SNAKE_CASE : float = 0.1 , SCREAMING_SNAKE_CASE : float = 0.1 , SCREAMING_SNAKE_CASE : int = 512 , SCREAMING_SNAKE_CASE : int = 2 , SCREAMING_SNAKE_CASE : float = 0.02 , SCREAMING_SNAKE_CASE : float = 1e-12 , SCREAMING_SNAKE_CASE : bool = False , **SCREAMING_SNAKE_CASE : List[Any] , ): super().__init__(pad_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) _A : List[Any] = attention_window _A : int = sep_token_id _A : Tuple = bos_token_id _A : Any = eos_token_id _A : List[str] = vocab_size _A : Any = hidden_size _A : Optional[int] = num_hidden_layers _A : int = num_attention_heads _A : Dict = hidden_act _A : List[Any] = intermediate_size _A : int = hidden_dropout_prob _A : Optional[int] = attention_probs_dropout_prob _A : int = max_position_embeddings _A : Any = type_vocab_size _A : Dict = initializer_range _A : Any = layer_norm_eps _A : List[Any] = onnx_export class __lowerCamelCase ( a_ ): """simple docstring""" def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE : "PretrainedConfig" , SCREAMING_SNAKE_CASE : str = "default" , SCREAMING_SNAKE_CASE : "List[PatchingSpec]" = None): super().__init__(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) _A : Optional[Any] = True @property def A ( self : List[str]): if self.task == "multiple-choice": _A : Tuple = {0: 'batch', 1: 'choice', 2: 'sequence'} else: _A : List[Any] = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ('global_attention_mask', dynamic_axis), ]) @property def A ( self : str): _A : int = super().outputs if self.task == "default": _A : str = {0: 'batch'} return outputs @property def A ( self : List[Any]): return 1e-4 @property def A ( self : Dict): # needs to be >= 14 to support tril operator return max(super().default_onnx_opset , 14) def A ( self : str , SCREAMING_SNAKE_CASE : "PreTrainedTokenizerBase" , SCREAMING_SNAKE_CASE : int = -1 , SCREAMING_SNAKE_CASE : int = -1 , SCREAMING_SNAKE_CASE : bool = False , SCREAMING_SNAKE_CASE : Optional[TensorType] = None , ): _A : Union[str, Any] = super().generate_dummy_inputs( preprocessor=SCREAMING_SNAKE_CASE , batch_size=SCREAMING_SNAKE_CASE , seq_length=SCREAMING_SNAKE_CASE , is_pair=SCREAMING_SNAKE_CASE , framework=SCREAMING_SNAKE_CASE) import torch # for some reason, replacing this code by inputs["global_attention_mask"] = torch.randint(2, inputs["input_ids"].shape, dtype=torch.int64) # makes the export fail randomly _A : Tuple = torch.zeros_like(inputs['input_ids']) # make every second token global _A : Dict = 1 return inputs
227
0
"""simple docstring""" from __future__ import annotations from typing import Any class lowerCamelCase__ : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = 0 ): """simple docstring""" snake_case , snake_case : str = row, column snake_case : List[Any] = [[default_value for c in range(SCREAMING_SNAKE_CASE )] for r in range(SCREAMING_SNAKE_CASE )] def __str__( self ): """simple docstring""" snake_case : Dict = F'''Matrix consist of {self.row} rows and {self.column} columns\n''' # Make string identifier snake_case : Optional[Any] = 0 for row_vector in self.array: for obj in row_vector: snake_case : Tuple = max(SCREAMING_SNAKE_CASE , len(str(SCREAMING_SNAKE_CASE ) ) ) snake_case : Union[str, Any] = F'''%{max_element_length}s''' # Make string and return def single_line(SCREAMING_SNAKE_CASE ) -> str: nonlocal string_format_identifier snake_case : List[Any] = "[" line += ", ".join(string_format_identifier % (obj,) for obj in row_vector ) line += "]" return line s += "\n".join(single_line(SCREAMING_SNAKE_CASE ) for row_vector in self.array ) return s def __repr__( self ): """simple docstring""" return str(self ) def lowerCamelCase_ ( self , SCREAMING_SNAKE_CASE ): """simple docstring""" if not (isinstance(SCREAMING_SNAKE_CASE , (list, tuple) ) and len(SCREAMING_SNAKE_CASE ) == 2): return False elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column): return False else: return True def __getitem__( self , SCREAMING_SNAKE_CASE ): """simple docstring""" assert self.validate_indicies(SCREAMING_SNAKE_CASE ) return self.array[loc[0]][loc[1]] def __setitem__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): """simple docstring""" assert self.validate_indicies(SCREAMING_SNAKE_CASE ) snake_case : Dict = value def __add__( self , SCREAMING_SNAKE_CASE ): """simple docstring""" assert isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) assert self.row == another.row and self.column == another.column # Add snake_case : List[str] = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): snake_case : Optional[int] = self[r, c] + another[r, c] return result def __neg__( self ): """simple docstring""" snake_case : Optional[Any] = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): snake_case : List[Any] = -self[r, c] return result def __sub__( self , SCREAMING_SNAKE_CASE ): """simple docstring""" return self + (-another) def __mul__( self , SCREAMING_SNAKE_CASE ): """simple docstring""" if isinstance(SCREAMING_SNAKE_CASE , (int, float) ): # Scalar multiplication snake_case : Optional[Any] = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): snake_case : int = self[r, c] * another return result elif isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): # Matrix multiplication assert self.column == another.row snake_case : List[Any] = Matrix(self.row , another.column ) for r in range(self.row ): for c in range(another.column ): for i in range(self.column ): result[r, c] += self[r, i] * another[i, c] return result else: snake_case : str = F'''Unsupported type given for another ({type(SCREAMING_SNAKE_CASE )})''' raise TypeError(SCREAMING_SNAKE_CASE ) def lowerCamelCase_ ( self ): """simple docstring""" snake_case : Dict = Matrix(self.column , self.row ) for r in range(self.row ): for c in range(self.column ): snake_case : Dict = self[r, c] return result def lowerCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): """simple docstring""" assert isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) and isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) assert self.row == self.column == u.row == v.row # u, v should be column vector assert u.column == v.column == 1 # u, v should be column vector # Calculate snake_case : List[Any] = v.transpose() snake_case : str = (v_t * self * u)[0, 0] + 1 if numerator_factor == 0: return None # It's not invertable return self - ((self * u) * (v_t * self) * (1.0 / numerator_factor)) # Testing if __name__ == "__main__": def UpperCamelCase__ ( ): # a^(-1) snake_case : int = Matrix(3 , 3 , 0 ) for i in range(3 ): snake_case : int = 1 print(F'''a^(-1) is {ainv}''' ) # u, v snake_case : Dict = Matrix(3 , 1 , 0 ) snake_case , snake_case , snake_case : List[Any] = 1, 2, -3 snake_case : Union[str, Any] = Matrix(3 , 1 , 0 ) snake_case , snake_case , snake_case : int = 4, -2, 5 print(F'''u is {u}''' ) print(F'''v is {v}''' ) print(F'''uv^T is {u * v.transpose()}''' ) # Sherman Morrison print(F'''(a + uv^T)^(-1) is {ainv.sherman_morrison(lowercase__ , lowercase__ )}''' ) def UpperCamelCase__ ( ): import doctest doctest.testmod() testa()
148
"""simple docstring""" # Algorithm for the pigeonhole sorting def UpperCamelCase__ ( lowercase__ : List[str] ): snake_case : Tuple = min(lowercase__ ) # min() finds the minimum value snake_case : int = max(lowercase__ ) # max() finds the maximum value snake_case : List[Any] = max_val - min_val + 1 # size is difference of max and min values plus one # list of pigeonholes of size equal to the variable size snake_case : List[Any] = [0] * size # Populate the pigeonholes. for x in a: assert isinstance(lowercase__ , lowercase__ ), "integers only please" holes[x - min_val] += 1 # Putting the elements back into the array in an order. snake_case : Optional[Any] = 0 for count in range(lowercase__ ): while holes[count] > 0: holes[count] -= 1 snake_case : List[str] = count + min_val i += 1 def UpperCamelCase__ ( ): snake_case : Dict = [8, 3, 2, 7, 4, 6, 8] pigeonhole_sort(lowercase__ ) print("Sorted order is:" , " ".join(lowercase__ ) ) if __name__ == "__main__": main()
148
1
import argparse from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection from diffusers import UnCLIPImageVariationPipeline, UnCLIPPipeline if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() parser.add_argument("--dump_path", default=None, type=str, required=True, help="Path to the output model.") parser.add_argument( "--txt2img_unclip", default="kakaobrain/karlo-v1-alpha", type=str, required=False, help="The pretrained txt2img unclip.", ) lowercase_ = parser.parse_args() lowercase_ = UnCLIPPipeline.from_pretrained(args.txtaimg_unclip) lowercase_ = CLIPImageProcessor() lowercase_ = CLIPVisionModelWithProjection.from_pretrained("openai/clip-vit-large-patch14") lowercase_ = UnCLIPImageVariationPipeline( decoder=txtaimg.decoder, text_encoder=txtaimg.text_encoder, tokenizer=txtaimg.tokenizer, text_proj=txtaimg.text_proj, feature_extractor=feature_extractor, image_encoder=image_encoder, super_res_first=txtaimg.super_res_first, super_res_last=txtaimg.super_res_last, decoder_scheduler=txtaimg.decoder_scheduler, super_res_scheduler=txtaimg.super_res_scheduler, ) imgaimg.save_pretrained(args.dump_path)
20
import os import sys import warnings from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen from ..table import array_cast from ..utils.file_utils import is_local_path from ..utils.py_utils import first_non_null_value, no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: import PIL.Image from .features import FeatureType lowercase_ = None lowercase_ = "<" if sys.byteorder == "little" else ">" # Origin: https://github.com/python-pillow/Pillow/blob/698951e19e19972aeed56df686868f1329981c12/src/PIL/Image.py#L3126 minus "|i1" which values are not preserved correctly when saving and loading an image lowercase_ = [ np.dtype("|b1"), np.dtype("|u1"), np.dtype("<u2"), np.dtype(">u2"), np.dtype("<i2"), np.dtype(">i2"), np.dtype("<u4"), np.dtype(">u4"), np.dtype("<i4"), np.dtype(">i4"), np.dtype("<f4"), np.dtype(">f4"), np.dtype("<f8"), np.dtype(">f8"), ] @dataclass class SCREAMING_SNAKE_CASE__ : A : bool = True A : Optional[str] = None # Automatically constructed A : ClassVar[str] = "PIL.Image.Image" A : ClassVar[Any] = pa.struct({"bytes": pa.binary(), "path": pa.string()} ) A : str = field(default="Image" , init=__UpperCamelCase , repr=__UpperCamelCase ) def __call__( self : Any ): return self.pa_type def snake_case__ ( self : List[Any] , _lowerCAmelCase : Union[str, bytes, dict, np.ndarray, "PIL.Image.Image"] ): if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("""To support encoding images, please install 'Pillow'.""" ) if isinstance(_lowerCAmelCase , _lowerCAmelCase ): __snake_case : str = np.array(_lowerCAmelCase ) if isinstance(_lowerCAmelCase , _lowerCAmelCase ): return {"path": value, "bytes": None} elif isinstance(_lowerCAmelCase , _lowerCAmelCase ): return {"path": None, "bytes": value} elif isinstance(_lowerCAmelCase , np.ndarray ): # convert the image array to PNG/TIFF bytes return encode_np_array(_lowerCAmelCase ) elif isinstance(_lowerCAmelCase , PIL.Image.Image ): # convert the PIL image to bytes (default format is PNG/TIFF) return encode_pil_image(_lowerCAmelCase ) elif value.get("""path""" ) is not None and os.path.isfile(value["""path"""] ): # we set "bytes": None to not duplicate the data if they're already available locally return {"bytes": None, "path": value.get("""path""" )} elif value.get("""bytes""" ) is not None or value.get("""path""" ) is not None: # store the image bytes, and path is used to infer the image format using the file extension return {"bytes": value.get("""bytes""" ), "path": value.get("""path""" )} else: raise ValueError( f'''An image sample should have one of \'path\' or \'bytes\' but they are missing or None in {value}.''' ) def snake_case__ ( self : List[str] , _lowerCAmelCase : dict , _lowerCAmelCase : Dict=None ): if not self.decode: raise RuntimeError("""Decoding is disabled for this feature. Please use Image(decode=True) instead.""" ) if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("""To support decoding images, please install 'Pillow'.""" ) if token_per_repo_id is None: __snake_case : Tuple = {} __snake_case , __snake_case : str = value["""path"""], value["""bytes"""] if bytes_ is None: if path is None: raise ValueError(f'''An image should have one of \'path\' or \'bytes\' but both are None in {value}.''' ) else: if is_local_path(_lowerCAmelCase ): __snake_case : str = PIL.Image.open(_lowerCAmelCase ) else: __snake_case : List[str] = path.split("""::""" )[-1] try: __snake_case : Dict = string_to_dict(_lowerCAmelCase , config.HUB_DATASETS_URL )["""repo_id"""] __snake_case : int = token_per_repo_id.get(_lowerCAmelCase ) except ValueError: __snake_case : List[Any] = None with xopen(_lowerCAmelCase , """rb""" , use_auth_token=_lowerCAmelCase ) as f: __snake_case : Union[str, Any] = BytesIO(f.read() ) __snake_case : Dict = PIL.Image.open(bytes_ ) else: __snake_case : Optional[Any] = PIL.Image.open(BytesIO(bytes_ ) ) image.load() # to avoid "Too many open files" errors return image def snake_case__ ( self : Union[str, Any] ): from .features import Value return ( self if self.decode else { "bytes": Value("""binary""" ), "path": Value("""string""" ), } ) def snake_case__ ( self : Optional[int] , _lowerCAmelCase : Union[pa.StringArray, pa.StructArray, pa.ListArray] ): if pa.types.is_string(storage.type ): __snake_case : Optional[Any] = pa.array([None] * len(_lowerCAmelCase ) , type=pa.binary() ) __snake_case : Any = pa.StructArray.from_arrays([bytes_array, storage] , ["""bytes""", """path"""] , mask=storage.is_null() ) elif pa.types.is_binary(storage.type ): __snake_case : Optional[Any] = pa.array([None] * len(_lowerCAmelCase ) , type=pa.string() ) __snake_case : List[str] = pa.StructArray.from_arrays([storage, path_array] , ["""bytes""", """path"""] , mask=storage.is_null() ) elif pa.types.is_struct(storage.type ): if storage.type.get_field_index("""bytes""" ) >= 0: __snake_case : List[str] = storage.field("""bytes""" ) else: __snake_case : List[Any] = pa.array([None] * len(_lowerCAmelCase ) , type=pa.binary() ) if storage.type.get_field_index("""path""" ) >= 0: __snake_case : Optional[int] = storage.field("""path""" ) else: __snake_case : int = pa.array([None] * len(_lowerCAmelCase ) , type=pa.string() ) __snake_case : Tuple = pa.StructArray.from_arrays([bytes_array, path_array] , ["""bytes""", """path"""] , mask=storage.is_null() ) elif pa.types.is_list(storage.type ): __snake_case : Optional[Any] = pa.array( [encode_np_array(np.array(_lowerCAmelCase ) )["""bytes"""] if arr is not None else None for arr in storage.to_pylist()] , type=pa.binary() , ) __snake_case : Optional[int] = pa.array([None] * len(_lowerCAmelCase ) , type=pa.string() ) __snake_case : List[str] = pa.StructArray.from_arrays( [bytes_array, path_array] , ["""bytes""", """path"""] , mask=bytes_array.is_null() ) return array_cast(_lowerCAmelCase , self.pa_type ) def snake_case__ ( self : Union[str, Any] , _lowerCAmelCase : pa.StructArray ): @no_op_if_value_is_null def path_to_bytes(_lowerCAmelCase : Tuple ): with xopen(_lowerCAmelCase , """rb""" ) as f: __snake_case : Optional[int] = f.read() return bytes_ __snake_case : Tuple = pa.array( [ (path_to_bytes(x["""path"""] ) if x["""bytes"""] is None else x["""bytes"""]) if x is not None else None for x in storage.to_pylist() ] , type=pa.binary() , ) __snake_case : Optional[Any] = pa.array( [os.path.basename(_lowerCAmelCase ) if path is not None else None for path in storage.field("""path""" ).to_pylist()] , type=pa.string() , ) __snake_case : Any = pa.StructArray.from_arrays([bytes_array, path_array] , ["""bytes""", """path"""] , mask=bytes_array.is_null() ) return array_cast(_lowerCAmelCase , self.pa_type ) def __lowerCAmelCase ( ): '''simple docstring''' if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("""To support encoding images, please install 'Pillow'.""" ) global _IMAGE_COMPRESSION_FORMATS if _IMAGE_COMPRESSION_FORMATS is None: PIL.Image.init() __snake_case : Optional[Any] = list(set(PIL.Image.OPEN.keys() ) & set(PIL.Image.SAVE.keys() ) ) return _IMAGE_COMPRESSION_FORMATS def __lowerCAmelCase ( __SCREAMING_SNAKE_CASE : "PIL.Image.Image" ): '''simple docstring''' __snake_case : List[Any] = BytesIO() if image.format in list_image_compression_formats(): __snake_case : Union[str, Any] = image.format else: __snake_case : List[Any] = """PNG""" if image.mode in ["""1""", """L""", """LA""", """RGB""", """RGBA"""] else """TIFF""" image.save(__SCREAMING_SNAKE_CASE , format=__SCREAMING_SNAKE_CASE ) return buffer.getvalue() def __lowerCAmelCase ( __SCREAMING_SNAKE_CASE : "PIL.Image.Image" ): '''simple docstring''' if hasattr(__SCREAMING_SNAKE_CASE , """filename""" ) and image.filename != "": return {"path": image.filename, "bytes": None} else: return {"path": None, "bytes": image_to_bytes(__SCREAMING_SNAKE_CASE )} def __lowerCAmelCase ( __SCREAMING_SNAKE_CASE : np.ndarray ): '''simple docstring''' if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("""To support encoding images, please install 'Pillow'.""" ) __snake_case : List[Any] = array.dtype __snake_case : List[Any] = dtype.byteorder if dtype.byteorder != """=""" else _NATIVE_BYTEORDER __snake_case : Dict = dtype.kind __snake_case : Union[str, Any] = dtype.itemsize __snake_case : Tuple = None # Multi-channel array case (only np.dtype("|u1") is allowed) if array.shape[2:]: __snake_case : int = np.dtype("""|u1""" ) if dtype_kind not in ["u", "i"]: raise TypeError( F'''Unsupported array dtype {dtype} for image encoding. Only {dest_dtype} is supported for multi-channel arrays.''' ) if dtype is not dest_dtype: warnings.warn(F'''Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\'''' ) # Exact match elif dtype in _VALID_IMAGE_ARRAY_DTPYES: __snake_case : List[str] = dtype else: # Downcast the type within the kind (np.can_cast(from_type, to_type, casting="same_kind") doesn't behave as expected, so do it manually) while dtype_itemsize >= 1: __snake_case : int = dtype_byteorder + dtype_kind + str(__SCREAMING_SNAKE_CASE ) __snake_case : Any = np.dtype(__SCREAMING_SNAKE_CASE ) if dest_dtype in _VALID_IMAGE_ARRAY_DTPYES: warnings.warn(F'''Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\'''' ) break else: dtype_itemsize //= 2 if dest_dtype is None: raise TypeError( F'''Cannot convert dtype {dtype} to a valid image dtype. Valid image dtypes: {_VALID_IMAGE_ARRAY_DTPYES}''' ) __snake_case : Optional[int] = PIL.Image.fromarray(array.astype(__SCREAMING_SNAKE_CASE ) ) return {"path": None, "bytes": image_to_bytes(__SCREAMING_SNAKE_CASE )} def __lowerCAmelCase ( __SCREAMING_SNAKE_CASE : Union[List[str], List[dict], List[np.ndarray], List["PIL.Image.Image"]] ): '''simple docstring''' if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("""To support encoding images, please install 'Pillow'.""" ) if objs: __snake_case , __snake_case : Any = first_non_null_value(__SCREAMING_SNAKE_CASE ) if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): return [{"path": obj, "bytes": None} if obj is not None else None for obj in objs] if isinstance(__SCREAMING_SNAKE_CASE , np.ndarray ): __snake_case : int = no_op_if_value_is_null(__SCREAMING_SNAKE_CASE ) return [obj_to_image_dict_func(__SCREAMING_SNAKE_CASE ) for obj in objs] elif isinstance(__SCREAMING_SNAKE_CASE , PIL.Image.Image ): __snake_case : List[str] = no_op_if_value_is_null(__SCREAMING_SNAKE_CASE ) return [obj_to_image_dict_func(__SCREAMING_SNAKE_CASE ) for obj in objs] else: return objs else: return objs
20
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __SCREAMING_SNAKE_CASE :str = logging.get_logger(__name__) class A_ ( lowerCAmelCase_ ): _lowerCamelCase : Tuple = """timm_backbone""" def __init__( self : List[str] , snake_case_ : Union[str, Any]=None , snake_case_ : List[str]=3 , snake_case_ : str=True , snake_case_ : Dict=True , snake_case_ : Union[str, Any]=None , **snake_case_ : Dict , ): super().__init__(**snake_case_ ) _UpperCAmelCase = backbone _UpperCAmelCase = num_channels _UpperCAmelCase = features_only _UpperCAmelCase = use_pretrained_backbone _UpperCAmelCase = True _UpperCAmelCase = out_indices if out_indices is not None else (-1,)
22
"""simple docstring""" import numpy as np def __lowerCAmelCase (_UpperCamelCase ): return 1 / (1 + np.exp(-vector )) def __lowerCAmelCase (_UpperCamelCase ): return vector * sigmoid(_UpperCamelCase ) if __name__ == "__main__": import doctest doctest.testmod()
86
0
import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler __lowerCamelCase : str = 16 __lowerCamelCase : Union[str, Any] = 32 def A_ ( _lowerCAmelCase , _lowerCAmelCase = 16 , _lowerCAmelCase = "bert-base-cased" ) -> Union[str, Any]: UpperCamelCase : Tuple = AutoTokenizer.from_pretrained(_lowerCAmelCase ) UpperCamelCase : Dict = load_dataset("glue" , "mrpc" ) def tokenize_function(_lowerCAmelCase ): # max_length=None => use the model max length (it's actually the default) UpperCamelCase : Any = 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 UpperCamelCase : Any = 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 UpperCamelCase : List[str] = tokenized_datasets.rename_column("label" , "labels" ) def collate_fn(_lowerCAmelCase ): # 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=128 , return_tensors="pt" ) return tokenizer.pad(_lowerCAmelCase , padding="longest" , return_tensors="pt" ) # Instantiate dataloaders. UpperCamelCase : List[str] = DataLoader( tokenized_datasets["train"] , shuffle=_lowerCAmelCase , collate_fn=_lowerCAmelCase , batch_size=_lowerCAmelCase ) UpperCamelCase : List[Any] = DataLoader( tokenized_datasets["validation"] , shuffle=_lowerCAmelCase , collate_fn=_lowerCAmelCase , batch_size=_lowerCAmelCase ) return train_dataloader, eval_dataloader def A_ ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> List[Any]: model.eval() UpperCamelCase : Any = 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(): UpperCamelCase : List[Any] = model(**_lowerCAmelCase ) UpperCamelCase : Union[str, Any] = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times UpperCamelCase , UpperCamelCase : List[str] = 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: UpperCamelCase : Union[str, Any] = predictions[: len(eval_dataloader.dataset ) - samples_seen] UpperCamelCase : Tuple = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=_lowerCAmelCase , references=_lowerCAmelCase , ) UpperCamelCase : List[str] = metric.compute() return eval_metric["accuracy"] def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> Union[str, Any]: # Initialize accelerator UpperCamelCase : List[Any] = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs UpperCamelCase : List[str] = config["lr"] UpperCamelCase : Union[str, Any] = int(config["num_epochs"] ) UpperCamelCase : int = int(config["seed"] ) UpperCamelCase : Tuple = int(config["batch_size"] ) UpperCamelCase : Tuple = args.model_name_or_path set_seed(_lowerCAmelCase ) UpperCamelCase , UpperCamelCase : Union[str, Any] = get_dataloaders(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) UpperCamelCase : int = AutoModelForSequenceClassification.from_pretrained(_lowerCAmelCase , return_dict=_lowerCAmelCase ) # Instantiate optimizer UpperCamelCase : List[str] = ( AdamW if accelerator.state.deepspeed_plugin is None or "optimizer" not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) UpperCamelCase : Tuple = optimizer_cls(params=model.parameters() , lr=_lowerCAmelCase ) if accelerator.state.deepspeed_plugin is not None: UpperCamelCase : Any = accelerator.state.deepspeed_plugin.deepspeed_config[ "gradient_accumulation_steps" ] else: UpperCamelCase : List[Any] = 1 UpperCamelCase : Union[str, Any] = (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 ): UpperCamelCase : Dict = get_linear_schedule_with_warmup( optimizer=_lowerCAmelCase , num_warmup_steps=0 , num_training_steps=_lowerCAmelCase , ) else: UpperCamelCase : Optional[int] = 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. UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase : Union[str, Any] = accelerator.prepare( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) # We need to keep track of how many total steps we have iterated over UpperCamelCase : int = 0 # We also need to keep track of the stating epoch so files are named properly UpperCamelCase : Optional[Any] = 0 UpperCamelCase : int = evaluate.load("glue" , "mrpc" ) UpperCamelCase : List[str] = num_epochs if args.partial_train_epoch is not None: UpperCamelCase : Any = args.partial_train_epoch if args.resume_from_checkpoint: accelerator.load_state(args.resume_from_checkpoint ) UpperCamelCase : List[str] = args.resume_from_checkpoint.split("epoch_" )[1] UpperCamelCase : List[str] = "" for char in epoch_string: if char.isdigit(): state_epoch_num += char else: break UpperCamelCase : List[Any] = int(_lowerCAmelCase ) + 1 UpperCamelCase : List[Any] = evaluation_loop(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) accelerator.print("resumed checkpoint performance:" , _lowerCAmelCase ) accelerator.print("resumed checkpoint's scheduler's lr:" , lr_scheduler.get_lr()[0] ) accelerator.print("resumed optimizers's lr:" , optimizer.param_groups[0]["lr"] ) with open(os.path.join(args.output_dir , F"""state_{starting_epoch-1}.json""" ) , "r" ) as f: UpperCamelCase : Union[str, Any] = json.load(_lowerCAmelCase ) assert resumed_state["accuracy"] == accuracy, "Accuracy mismatch, loading from checkpoint failed" assert ( resumed_state["lr"] == lr_scheduler.get_lr()[0] ), "Scheduler learning rate mismatch, loading from checkpoint failed" assert ( resumed_state["optimizer_lr"] == optimizer.param_groups[0]["lr"] ), "Optimizer learning rate mismatch, loading from checkpoint failed" assert resumed_state["epoch"] == starting_epoch - 1, "Epoch mismatch, loading from checkpoint failed" return # Now we train the model UpperCamelCase : List[Any] = {} for epoch in range(_lowerCAmelCase , _lowerCAmelCase ): model.train() for step, batch in enumerate(_lowerCAmelCase ): UpperCamelCase : Tuple = model(**_lowerCAmelCase ) UpperCamelCase : List[str] = outputs.loss UpperCamelCase : Optional[Any] = loss / gradient_accumulation_steps accelerator.backward(_lowerCAmelCase ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 UpperCamelCase : Dict = F"""epoch_{epoch}""" UpperCamelCase : Union[str, Any] = os.path.join(args.output_dir , _lowerCAmelCase ) accelerator.save_state(_lowerCAmelCase ) UpperCamelCase : List[Any] = evaluation_loop(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) UpperCamelCase : str = accuracy UpperCamelCase : Optional[int] = lr_scheduler.get_lr()[0] UpperCamelCase : Dict = optimizer.param_groups[0]["lr"] UpperCamelCase : Optional[Any] = epoch UpperCamelCase : Optional[Any] = overall_step accelerator.print(F"""epoch {epoch}:""" , _lowerCAmelCase ) accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , F"""state_{epoch}.json""" ) , "w" ) as f: json.dump(_lowerCAmelCase , _lowerCAmelCase ) def A_ ( ) -> str: UpperCamelCase : Dict = 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( "--resume_from_checkpoint" , type=_lowerCAmelCase , default=_lowerCAmelCase , help="If the training should continue from a checkpoint folder." , ) parser.add_argument( "--partial_train_epoch" , type=_lowerCAmelCase , default=_lowerCAmelCase , help="If passed, the training will stop after this number of epochs." , ) parser.add_argument( "--num_epochs" , type=_lowerCAmelCase , default=2 , help="Number of train epochs." , ) UpperCamelCase : Optional[int] = parser.parse_args() UpperCamelCase : str = {"lr": 2e-5, "num_epochs": args.num_epochs, "seed": 42, "batch_size": 16} training_function(_lowerCAmelCase , _lowerCAmelCase ) if __name__ == "__main__": main()
140
import collections import gzip import os import urllib import numpy from tensorflow.python.framework import dtypes, random_seed from tensorflow.python.platform import gfile from tensorflow.python.util.deprecation import deprecated __lowerCamelCase : Any = collections.namedtuple("""_Datasets""", ["""train""", """validation""", """test"""]) # CVDF mirror of http://yann.lecun.com/exdb/mnist/ __lowerCamelCase : str = """https://storage.googleapis.com/cvdf-datasets/mnist/""" def A_ ( _lowerCAmelCase ) -> Optional[Any]: UpperCamelCase : Tuple = numpy.dtype(numpy.uintaa ).newbyteorder(">" ) return numpy.frombuffer(bytestream.read(4 ) , dtype=_lowerCAmelCase )[0] @deprecated(_lowerCAmelCase , "Please use tf.data to implement this functionality." ) def A_ ( _lowerCAmelCase ) -> int: print("Extracting" , f.name ) with gzip.GzipFile(fileobj=_lowerCAmelCase ) as bytestream: UpperCamelCase : Dict = _readaa(_lowerCAmelCase ) if magic != 2051: raise ValueError( "Invalid magic number %d in MNIST image file: %s" % (magic, f.name) ) UpperCamelCase : Optional[int] = _readaa(_lowerCAmelCase ) UpperCamelCase : int = _readaa(_lowerCAmelCase ) UpperCamelCase : Union[str, Any] = _readaa(_lowerCAmelCase ) UpperCamelCase : List[Any] = bytestream.read(rows * cols * num_images ) UpperCamelCase : List[str] = numpy.frombuffer(_lowerCAmelCase , dtype=numpy.uinta ) UpperCamelCase : Optional[Any] = data.reshape(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , 1 ) return data @deprecated(_lowerCAmelCase , "Please use tf.one_hot on tensors." ) def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> Dict: UpperCamelCase : List[str] = labels_dense.shape[0] UpperCamelCase : str = numpy.arange(_lowerCAmelCase ) * num_classes UpperCamelCase : Optional[Any] = numpy.zeros((num_labels, num_classes) ) UpperCamelCase : Dict = 1 return labels_one_hot @deprecated(_lowerCAmelCase , "Please use tf.data to implement this functionality." ) def A_ ( _lowerCAmelCase , _lowerCAmelCase=False , _lowerCAmelCase=10 ) -> str: print("Extracting" , f.name ) with gzip.GzipFile(fileobj=_lowerCAmelCase ) as bytestream: UpperCamelCase : int = _readaa(_lowerCAmelCase ) if magic != 2049: raise ValueError( "Invalid magic number %d in MNIST label file: %s" % (magic, f.name) ) UpperCamelCase : List[str] = _readaa(_lowerCAmelCase ) UpperCamelCase : List[Any] = bytestream.read(_lowerCAmelCase ) UpperCamelCase : List[str] = numpy.frombuffer(_lowerCAmelCase , dtype=numpy.uinta ) if one_hot: return _dense_to_one_hot(_lowerCAmelCase , _lowerCAmelCase ) return labels class A__ : @deprecated( A_ , "Please use alternatives such as official/mnist/_DataSet.py" " from tensorflow/models." , ) def __init__( self , A_ , A_ , A_=False , A_=False , A_=dtypes.floataa , A_=True , A_=None , ): '''simple docstring''' UpperCamelCase , UpperCamelCase : int = random_seed.get_seed(A_ ) # If op level seed is not set, use whatever graph level seed is returned numpy.random.seed(seeda if seed is None else seeda ) UpperCamelCase : Optional[Any] = dtypes.as_dtype(A_ ).base_dtype if dtype not in (dtypes.uinta, dtypes.floataa): raise TypeError("Invalid image dtype %r, expected uint8 or float32" % dtype ) if fake_data: UpperCamelCase : List[str] = 1_0000 UpperCamelCase : int = one_hot else: assert ( images.shape[0] == labels.shape[0] ), F"""images.shape: {images.shape} labels.shape: {labels.shape}""" UpperCamelCase : Optional[Any] = images.shape[0] # Convert shape from [num examples, rows, columns, depth] # to [num examples, rows*columns] (assuming depth == 1) if reshape: assert images.shape[3] == 1 UpperCamelCase : int = images.reshape( images.shape[0] , images.shape[1] * images.shape[2] ) if dtype == dtypes.floataa: # Convert from [0, 255] -> [0.0, 1.0]. UpperCamelCase : str = images.astype(numpy.floataa ) UpperCamelCase : str = numpy.multiply(A_ , 1.0 / 2_55.0 ) UpperCamelCase : Optional[int] = images UpperCamelCase : str = labels UpperCamelCase : Optional[Any] = 0 UpperCamelCase : Optional[int] = 0 @property def __UpperCamelCase( self ): '''simple docstring''' return self._images @property def __UpperCamelCase( self ): '''simple docstring''' return self._labels @property def __UpperCamelCase( self ): '''simple docstring''' return self._num_examples @property def __UpperCamelCase( self ): '''simple docstring''' return self._epochs_completed def __UpperCamelCase( self , A_ , A_=False , A_=True ): '''simple docstring''' if fake_data: UpperCamelCase : Optional[int] = [1] * 784 UpperCamelCase : Optional[Any] = [1] + [0] * 9 if self.one_hot else 0 return ( [fake_image for _ in range(A_ )], [fake_label for _ in range(A_ )], ) UpperCamelCase : Optional[Any] = self._index_in_epoch # Shuffle for the first epoch if self._epochs_completed == 0 and start == 0 and shuffle: UpperCamelCase : Optional[Any] = numpy.arange(self._num_examples ) numpy.random.shuffle(A_ ) UpperCamelCase : int = self.images[perma] UpperCamelCase : Any = self.labels[perma] # Go to the next epoch if start + batch_size > self._num_examples: # Finished epoch self._epochs_completed += 1 # Get the rest examples in this epoch UpperCamelCase : List[Any] = self._num_examples - start UpperCamelCase : Union[str, Any] = self._images[start : self._num_examples] UpperCamelCase : str = self._labels[start : self._num_examples] # Shuffle the data if shuffle: UpperCamelCase : Union[str, Any] = numpy.arange(self._num_examples ) numpy.random.shuffle(A_ ) UpperCamelCase : Union[str, Any] = self.images[perm] UpperCamelCase : Union[str, Any] = self.labels[perm] # Start next epoch UpperCamelCase : Tuple = 0 UpperCamelCase : Tuple = batch_size - rest_num_examples UpperCamelCase : List[str] = self._index_in_epoch UpperCamelCase : Dict = self._images[start:end] UpperCamelCase : int = self._labels[start:end] return ( numpy.concatenate((images_rest_part, images_new_part) , axis=0 ), numpy.concatenate((labels_rest_part, labels_new_part) , axis=0 ), ) else: self._index_in_epoch += batch_size UpperCamelCase : Union[str, Any] = self._index_in_epoch return self._images[start:end], self._labels[start:end] @deprecated(_lowerCAmelCase , "Please write your own downloading logic." ) def A_ ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> Union[str, Any]: if not gfile.Exists(_lowerCAmelCase ): gfile.MakeDirs(_lowerCAmelCase ) UpperCamelCase : Optional[Any] = os.path.join(_lowerCAmelCase , _lowerCAmelCase ) if not gfile.Exists(_lowerCAmelCase ): urllib.request.urlretrieve(_lowerCAmelCase , _lowerCAmelCase ) # noqa: S310 with gfile.GFile(_lowerCAmelCase ) as f: UpperCamelCase : Optional[int] = f.size() print("Successfully downloaded" , _lowerCAmelCase , _lowerCAmelCase , "bytes." ) return filepath @deprecated( _lowerCAmelCase , "Please use alternatives such as:" " tensorflow_datasets.load('mnist')" ) def A_ ( _lowerCAmelCase , _lowerCAmelCase=False , _lowerCAmelCase=False , _lowerCAmelCase=dtypes.floataa , _lowerCAmelCase=True , _lowerCAmelCase=5000 , _lowerCAmelCase=None , _lowerCAmelCase=DEFAULT_SOURCE_URL , ) -> List[str]: if fake_data: def fake(): return _DataSet( [] , [] , fake_data=_lowerCAmelCase , one_hot=_lowerCAmelCase , dtype=_lowerCAmelCase , seed=_lowerCAmelCase ) UpperCamelCase : Any = fake() UpperCamelCase : List[str] = fake() UpperCamelCase : Union[str, Any] = fake() return _Datasets(train=_lowerCAmelCase , validation=_lowerCAmelCase , test=_lowerCAmelCase ) if not source_url: # empty string check UpperCamelCase : str = DEFAULT_SOURCE_URL UpperCamelCase : List[str] = "train-images-idx3-ubyte.gz" UpperCamelCase : Optional[int] = "train-labels-idx1-ubyte.gz" UpperCamelCase : List[str] = "t10k-images-idx3-ubyte.gz" UpperCamelCase : Union[str, Any] = "t10k-labels-idx1-ubyte.gz" UpperCamelCase : Optional[int] = _maybe_download( _lowerCAmelCase , _lowerCAmelCase , source_url + train_images_file ) with gfile.Open(_lowerCAmelCase , "rb" ) as f: UpperCamelCase : List[str] = _extract_images(_lowerCAmelCase ) UpperCamelCase : Dict = _maybe_download( _lowerCAmelCase , _lowerCAmelCase , source_url + train_labels_file ) with gfile.Open(_lowerCAmelCase , "rb" ) as f: UpperCamelCase : List[Any] = _extract_labels(_lowerCAmelCase , one_hot=_lowerCAmelCase ) UpperCamelCase : Any = _maybe_download( _lowerCAmelCase , _lowerCAmelCase , source_url + test_images_file ) with gfile.Open(_lowerCAmelCase , "rb" ) as f: UpperCamelCase : Any = _extract_images(_lowerCAmelCase ) UpperCamelCase : List[str] = _maybe_download( _lowerCAmelCase , _lowerCAmelCase , source_url + test_labels_file ) with gfile.Open(_lowerCAmelCase , "rb" ) as f: UpperCamelCase : str = _extract_labels(_lowerCAmelCase , one_hot=_lowerCAmelCase ) if not 0 <= validation_size <= len(_lowerCAmelCase ): UpperCamelCase : Any = ( "Validation size should be between 0 and " F"""{len(_lowerCAmelCase )}. Received: {validation_size}.""" ) raise ValueError(_lowerCAmelCase ) UpperCamelCase : str = train_images[:validation_size] UpperCamelCase : int = train_labels[:validation_size] UpperCamelCase : List[str] = train_images[validation_size:] UpperCamelCase : Union[str, Any] = train_labels[validation_size:] UpperCamelCase : List[str] = {"dtype": dtype, "reshape": reshape, "seed": seed} UpperCamelCase : List[str] = _DataSet(_lowerCAmelCase , _lowerCAmelCase , **_lowerCAmelCase ) UpperCamelCase : List[str] = _DataSet(_lowerCAmelCase , _lowerCAmelCase , **_lowerCAmelCase ) UpperCamelCase : Any = _DataSet(_lowerCAmelCase , _lowerCAmelCase , **_lowerCAmelCase ) return _Datasets(train=_lowerCAmelCase , validation=_lowerCAmelCase , test=_lowerCAmelCase )
140
1
import os from collections.abc import Iterator def lowerCamelCase__ ( _a = "."): for dir_path, dir_names, filenames in os.walk(_a): SCREAMING_SNAKE_CASE : Dict = [d for d in dir_names if d != "scripts" and d[0] not in "._"] for filename in filenames: if filename == "__init__.py": continue if os.path.splitext(_a)[1] in (".py", ".ipynb"): yield os.path.join(_a , _a).lstrip("./") def lowerCamelCase__ ( _a): return f"{i * ' '}*" if i else "\n##" def lowerCamelCase__ ( _a , _a): SCREAMING_SNAKE_CASE : int = old_path.split(os.sep) for i, new_part in enumerate(new_path.split(os.sep)): if (i + 1 > len(_a) or old_parts[i] != new_part) and new_part: print(f"{md_prefix(_a)} {new_part.replace('_' , ' ').title()}") return new_path def lowerCamelCase__ ( _a = "."): SCREAMING_SNAKE_CASE : Dict = "" for filepath in sorted(good_file_paths(_a)): SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Optional[int] = os.path.split(_a) if filepath != old_path: SCREAMING_SNAKE_CASE : Optional[int] = print_path(_a , _a) SCREAMING_SNAKE_CASE : Dict = (filepath.count(os.sep) + 1) if filepath else 0 SCREAMING_SNAKE_CASE : int = f"{filepath}/{filename}".replace(" " , "%20") SCREAMING_SNAKE_CASE : str = os.path.splitext(filename.replace("_" , " ").title())[0] print(f"{md_prefix(_a)} [{filename}]({url})") if __name__ == "__main__": print_directory_md('.')
76
'''simple docstring''' import io import json import fsspec import pytest from datasets import Dataset, DatasetDict, Features, NamedSplit, Value from datasets.io.json import JsonDatasetReader, JsonDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def a ( __a , __a ) -> Optional[int]: '''simple docstring''' assert isinstance(__a , __a ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('''keep_in_memory''' , [False, True] ) def a ( __a , __a , __a ) -> Optional[Any]: '''simple docstring''' UpperCamelCase__ :Union[str, Any] = tmp_path / '''cache''' UpperCamelCase__ :Dict = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): UpperCamelCase__ :Tuple = JsonDatasetReader(__a , cache_dir=__a , keep_in_memory=__a ).read() _check_json_dataset(__a , __a ) @pytest.mark.parametrize( '''features''' , [ None, {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}, {'''col_1''': '''string''', '''col_2''': '''string''', '''col_3''': '''string'''}, {'''col_1''': '''int32''', '''col_2''': '''int32''', '''col_3''': '''int32'''}, {'''col_1''': '''float32''', '''col_2''': '''float32''', '''col_3''': '''float32'''}, ] , ) def a ( __a , __a , __a ) -> Any: '''simple docstring''' UpperCamelCase__ :Union[str, Any] = tmp_path / '''cache''' UpperCamelCase__ :Optional[Any] = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} UpperCamelCase__ :Optional[Any] = features.copy() if features else default_expected_features UpperCamelCase__ :Tuple = ( Features({feature: Value(__a ) for feature, dtype in features.items()} ) if features is not None else None ) UpperCamelCase__ :int = JsonDatasetReader(__a , features=__a , cache_dir=__a ).read() _check_json_dataset(__a , __a ) @pytest.mark.parametrize( '''features''' , [ None, {'''col_3''': '''float64''', '''col_1''': '''string''', '''col_2''': '''int64'''}, ] , ) def a ( __a , __a , __a ) -> Tuple: '''simple docstring''' UpperCamelCase__ :int = tmp_path / '''cache''' UpperCamelCase__ :str = {'''col_3''': '''float64''', '''col_1''': '''string''', '''col_2''': '''int64'''} UpperCamelCase__ :Any = features.copy() if features else default_expected_features UpperCamelCase__ :Union[str, Any] = ( Features({feature: Value(__a ) for feature, dtype in features.items()} ) if features is not None else None ) UpperCamelCase__ :Any = JsonDatasetReader(__a , features=__a , cache_dir=__a ).read() assert isinstance(__a , __a ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_3", "col_1", "col_2"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype def a ( __a , __a ) -> List[Any]: '''simple docstring''' UpperCamelCase__ :Any = {'''col_2''': '''int64''', '''col_3''': '''float64''', '''col_1''': '''string'''} UpperCamelCase__ :int = features.copy() UpperCamelCase__ :List[Any] = ( Features({feature: Value(__a ) for feature, dtype in features.items()} ) if features is not None else None ) UpperCamelCase__ :Optional[int] = tmp_path / '''cache''' UpperCamelCase__ :Dict = JsonDatasetReader(__a , features=__a , cache_dir=__a ).read() assert isinstance(__a , __a ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_2", "col_3", "col_1"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('''split''' , [None, NamedSplit('''train''' ), '''train''', '''test'''] ) def a ( __a , __a , __a ) -> List[Any]: '''simple docstring''' UpperCamelCase__ :Union[str, Any] = tmp_path / '''cache''' UpperCamelCase__ :Optional[Any] = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} UpperCamelCase__ :List[Any] = JsonDatasetReader(__a , cache_dir=__a , split=__a ).read() _check_json_dataset(__a , __a ) assert dataset.split == split if split else "train" @pytest.mark.parametrize('''path_type''' , [str, list] ) def a ( __a , __a , __a ) -> Any: '''simple docstring''' if issubclass(__a , __a ): UpperCamelCase__ :Union[str, Any] = jsonl_path elif issubclass(__a , __a ): UpperCamelCase__ :int = [jsonl_path] UpperCamelCase__ :Dict = tmp_path / '''cache''' UpperCamelCase__ :Any = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} UpperCamelCase__ :List[str] = JsonDatasetReader(__a , cache_dir=__a ).read() _check_json_dataset(__a , __a ) def a ( __a , __a , __a=("train",) ) -> Optional[Any]: '''simple docstring''' assert isinstance(__a , __a ) for split in splits: UpperCamelCase__ :Optional[int] = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('''keep_in_memory''' , [False, True] ) def a ( __a , __a , __a ) -> List[str]: '''simple docstring''' UpperCamelCase__ :List[str] = tmp_path / '''cache''' UpperCamelCase__ :Dict = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): UpperCamelCase__ :str = JsonDatasetReader({'''train''': jsonl_path} , cache_dir=__a , keep_in_memory=__a ).read() _check_json_datasetdict(__a , __a ) @pytest.mark.parametrize( '''features''' , [ None, {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}, {'''col_1''': '''string''', '''col_2''': '''string''', '''col_3''': '''string'''}, {'''col_1''': '''int32''', '''col_2''': '''int32''', '''col_3''': '''int32'''}, {'''col_1''': '''float32''', '''col_2''': '''float32''', '''col_3''': '''float32'''}, ] , ) def a ( __a , __a , __a ) -> int: '''simple docstring''' UpperCamelCase__ :Tuple = tmp_path / '''cache''' UpperCamelCase__ :Any = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} UpperCamelCase__ :Optional[int] = features.copy() if features else default_expected_features UpperCamelCase__ :str = ( Features({feature: Value(__a ) for feature, dtype in features.items()} ) if features is not None else None ) UpperCamelCase__ :Dict = JsonDatasetReader({'''train''': jsonl_path} , features=__a , cache_dir=__a ).read() _check_json_datasetdict(__a , __a ) @pytest.mark.parametrize('''split''' , [None, NamedSplit('''train''' ), '''train''', '''test'''] ) def a ( __a , __a , __a ) -> str: '''simple docstring''' if split: UpperCamelCase__ :List[str] = {split: jsonl_path} else: UpperCamelCase__ :int = '''train''' UpperCamelCase__ :int = {'''train''': jsonl_path, '''test''': jsonl_path} UpperCamelCase__ :Any = tmp_path / '''cache''' UpperCamelCase__ :Union[str, Any] = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} UpperCamelCase__ :Any = JsonDatasetReader(__a , cache_dir=__a ).read() _check_json_datasetdict(__a , __a , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def a ( __a ) -> Union[str, Any]: '''simple docstring''' return json.load(__a ) def a ( __a ) -> int: '''simple docstring''' return [json.loads(__a ) for line in buffer] class lowercase : """simple docstring""" @pytest.mark.parametrize('''lines, load_json_function''' , [(True, load_json_lines), (False, load_json)] ) def lowerCAmelCase__ ( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ): '''simple docstring''' with io.BytesIO() as buffer: JsonDatasetWriter(UpperCamelCase_ , UpperCamelCase_ , lines=UpperCamelCase_ ).write() buffer.seek(0 ) UpperCamelCase__ :List[Any] = load_json_function(UpperCamelCase_ ) assert isinstance(UpperCamelCase_ , UpperCamelCase_ ) assert isinstance(exported_content[0] , UpperCamelCase_ ) assert len(UpperCamelCase_ ) == 10 @pytest.mark.parametrize( '''orient, container, keys, len_at''' , [ ('''records''', list, {'''tokens''', '''labels''', '''answers''', '''id'''}, None), ('''split''', dict, {'''columns''', '''data'''}, '''data'''), ('''index''', dict, set('''0123456789''' ), None), ('''columns''', dict, {'''tokens''', '''labels''', '''answers''', '''id'''}, '''tokens'''), ('''values''', list, None, None), ('''table''', dict, {'''schema''', '''data'''}, '''data'''), ] , ) def lowerCAmelCase__ ( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ): '''simple docstring''' with io.BytesIO() as buffer: JsonDatasetWriter(UpperCamelCase_ , UpperCamelCase_ , lines=UpperCamelCase_ , orient=UpperCamelCase_ ).write() buffer.seek(0 ) UpperCamelCase__ :Optional[int] = load_json(UpperCamelCase_ ) assert isinstance(UpperCamelCase_ , UpperCamelCase_ ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(UpperCamelCase_ , '''keys''' ) and not hasattr(exported_content[0] , '''keys''' ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(UpperCamelCase_ ) == 10 @pytest.mark.parametrize('''lines, load_json_function''' , [(True, load_json_lines), (False, load_json)] ) def lowerCAmelCase__ ( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ): '''simple docstring''' with io.BytesIO() as buffer: JsonDatasetWriter(UpperCamelCase_ , UpperCamelCase_ , lines=UpperCamelCase_ , num_proc=2 ).write() buffer.seek(0 ) UpperCamelCase__ :Union[str, Any] = load_json_function(UpperCamelCase_ ) assert isinstance(UpperCamelCase_ , UpperCamelCase_ ) assert isinstance(exported_content[0] , UpperCamelCase_ ) assert len(UpperCamelCase_ ) == 10 @pytest.mark.parametrize( '''orient, container, keys, len_at''' , [ ('''records''', list, {'''tokens''', '''labels''', '''answers''', '''id'''}, None), ('''split''', dict, {'''columns''', '''data'''}, '''data'''), ('''index''', dict, set('''0123456789''' ), None), ('''columns''', dict, {'''tokens''', '''labels''', '''answers''', '''id'''}, '''tokens'''), ('''values''', list, None, None), ('''table''', dict, {'''schema''', '''data'''}, '''data'''), ] , ) def lowerCAmelCase__ ( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ): '''simple docstring''' with io.BytesIO() as buffer: JsonDatasetWriter(UpperCamelCase_ , UpperCamelCase_ , lines=UpperCamelCase_ , orient=UpperCamelCase_ , num_proc=2 ).write() buffer.seek(0 ) UpperCamelCase__ :int = load_json(UpperCamelCase_ ) assert isinstance(UpperCamelCase_ , UpperCamelCase_ ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(UpperCamelCase_ , '''keys''' ) and not hasattr(exported_content[0] , '''keys''' ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(UpperCamelCase_ ) == 10 def lowerCAmelCase__ ( self , UpperCamelCase_ ): '''simple docstring''' with pytest.raises(UpperCamelCase_ ): with io.BytesIO() as buffer: JsonDatasetWriter(UpperCamelCase_ , UpperCamelCase_ , num_proc=0 ) @pytest.mark.parametrize('''compression, extension''' , [('''gzip''', '''gz'''), ('''bz2''', '''bz2'''), ('''xz''', '''xz''')] ) def lowerCAmelCase__ ( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ :Tuple = tmp_path_factory.mktemp('''data''' ) / F'''test.json.{extension}''' UpperCamelCase__ :Union[str, Any] = str(shared_datadir / F'''test_file.json.{extension}''' ) JsonDatasetWriter(UpperCamelCase_ , UpperCamelCase_ , compression=UpperCamelCase_ ).write() with fsspec.open(UpperCamelCase_ , '''rb''' , compression='''infer''' ) as f: UpperCamelCase__ :Dict = f.read() with fsspec.open(UpperCamelCase_ , '''rb''' , compression='''infer''' ) as f: UpperCamelCase__ :int = f.read() assert exported_content == original_content
97
0
from abc import ABC, abstractmethod from argparse import ArgumentParser class __a ( UpperCAmelCase ): @staticmethod @abstractmethod def UpperCAmelCase__ ( _SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" raise NotImplementedError() @abstractmethod def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" raise NotImplementedError()
185
import argparse import pytorch_lightning as pl import torch from torch import nn from transformers import LongformerForQuestionAnswering, LongformerModel class __a ( pl.LightningModule ): def __init__( self , _SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" super().__init__() _UpperCAmelCase = model _UpperCAmelCase = 2 _UpperCAmelCase = nn.Linear(self.model.config.hidden_size , self.num_labels ) def UpperCAmelCase__ ( self ) -> str: """simple docstring""" pass def lowerCAmelCase__ ( a__: str , a__: str , a__: str ) -> Tuple: '''simple docstring''' _UpperCAmelCase = LongformerModel.from_pretrained(a__ ) _UpperCAmelCase = LightningModel(a__ ) _UpperCAmelCase = torch.load(a__ , map_location=torch.device('cpu' ) ) lightning_model.load_state_dict(ckpt['state_dict'] ) # init longformer question answering model _UpperCAmelCase = LongformerForQuestionAnswering.from_pretrained(a__ ) # transfer weights longformer_for_qa.longformer.load_state_dict(lightning_model.model.state_dict() ) longformer_for_qa.qa_outputs.load_state_dict(lightning_model.qa_outputs.state_dict() ) longformer_for_qa.eval() # save model longformer_for_qa.save_pretrained(a__ ) print(F'''Conversion successful. Model saved under {pytorch_dump_folder_path}''' ) if __name__ == "__main__": lowerCAmelCase__ :Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--longformer_model''', default=None, type=str, required=True, help='''model identifier of longformer. Should be either `longformer-base-4096` or `longformer-large-4096`.''', ) parser.add_argument( '''--longformer_question_answering_ckpt_path''', default=None, type=str, required=True, help='''Path the official PyTorch Lightning Checkpoint.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) lowerCAmelCase__ :Dict = parser.parse_args() convert_longformer_qa_checkpoint_to_pytorch( args.longformer_model, args.longformer_question_answering_ckpt_path, args.pytorch_dump_folder_path )
185
1
import json import os from dataclasses import dataclass from functools import partial from typing import Callable import flax.linen as nn import jax import jax.numpy as jnp import joblib import optax import wandb from flax import jax_utils, struct, traverse_util from flax.serialization import from_bytes, to_bytes from flax.training import train_state from flax.training.common_utils import shard from tqdm.auto import tqdm from transformers import BigBirdConfig, FlaxBigBirdForQuestionAnswering from transformers.models.big_bird.modeling_flax_big_bird import FlaxBigBirdForQuestionAnsweringModule class __snake_case ( lowerCAmelCase ): _a : BigBirdConfig _a : jnp.dtype= jnp.floataa _a : bool= True def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' super().setup() lowercase : List[str] = nn.Dense(5 ,dtype=self.dtype ) def __call__( self ,*snake_case ,**snake_case ): '''simple docstring''' lowercase : int = super().__call__(*snake_case ,**snake_case ) lowercase : Any = self.cls(outputs[2] ) return outputs[:2] + (cls_out,) class __snake_case ( lowerCAmelCase ): _a : List[Any]= FlaxBigBirdForNaturalQuestionsModule def _snake_case( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> List[str]: def cross_entropy(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=None ): lowercase : int = logits.shape[-1] lowercase : Dict = (labels[..., None] == jnp.arange(SCREAMING_SNAKE_CASE__ )[None]).astype("""f4""" ) lowercase : Any = jax.nn.log_softmax(SCREAMING_SNAKE_CASE__ , axis=-1 ) lowercase : Optional[Any] = -jnp.sum(labels * logits , axis=-1 ) if reduction is not None: lowercase : Any = reduction(SCREAMING_SNAKE_CASE__ ) return loss lowercase : Optional[Any] = partial(SCREAMING_SNAKE_CASE__ , reduction=jnp.mean ) lowercase : Optional[int] = cross_entropy(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowercase : Dict = cross_entropy(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowercase : int = cross_entropy(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return (start_loss + end_loss + pooled_loss) / 3 @dataclass class __snake_case : _a : str= "google/bigbird-roberta-base" _a : int= 3000 _a : int= 1_0500 _a : int= 128 _a : int= 3 _a : int= 1 _a : int= 5 # tx_args _a : float= 3E-5 _a : float= 0.0 _a : int= 2_0000 _a : float= 0.00_95 _a : str= "bigbird-roberta-natural-questions" _a : str= "training-expt" _a : str= "data/nq-training.jsonl" _a : str= "data/nq-validation.jsonl" def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' os.makedirs(self.base_dir ,exist_ok=snake_case ) lowercase : Optional[int] = os.path.join(self.base_dir ,self.save_dir ) lowercase : Optional[int] = self.batch_size_per_device * jax.device_count() @dataclass class __snake_case : _a : int _a : int= 4096 # no dynamic padding on TPUs def __call__( self ,snake_case ): '''simple docstring''' lowercase : int = self.collate_fn(snake_case ) lowercase : Union[str, Any] = jax.tree_util.tree_map(snake_case ,snake_case ) return batch def _SCREAMING_SNAKE_CASE ( self ,snake_case ): '''simple docstring''' lowercase , lowercase : Union[str, Any] = self.fetch_inputs(features["""input_ids"""] ) lowercase : Tuple = { """input_ids""": jnp.array(snake_case ,dtype=jnp.intaa ), """attention_mask""": jnp.array(snake_case ,dtype=jnp.intaa ), """start_labels""": jnp.array(features["""start_token"""] ,dtype=jnp.intaa ), """end_labels""": jnp.array(features["""end_token"""] ,dtype=jnp.intaa ), """pooled_labels""": jnp.array(features["""category"""] ,dtype=jnp.intaa ), } return batch def _SCREAMING_SNAKE_CASE ( self ,snake_case ): '''simple docstring''' lowercase : Tuple = [self._fetch_inputs(snake_case ) for ids in input_ids] return zip(*snake_case ) def _SCREAMING_SNAKE_CASE ( self ,snake_case ): '''simple docstring''' lowercase : Union[str, Any] = [1 for _ in range(len(snake_case ) )] while len(snake_case ) < self.max_length: input_ids.append(self.pad_id ) attention_mask.append(0 ) return input_ids, attention_mask def _snake_case( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=None ) -> Any: if seed is not None: lowercase : Optional[int] = dataset.shuffle(seed=SCREAMING_SNAKE_CASE__ ) for i in range(len(SCREAMING_SNAKE_CASE__ ) // batch_size ): lowercase : Optional[Any] = dataset[i * batch_size : (i + 1) * batch_size] yield dict(SCREAMING_SNAKE_CASE__ ) @partial(jax.pmap , axis_name="""batch""" ) def _snake_case( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) -> List[Any]: def loss_fn(SCREAMING_SNAKE_CASE__ ): lowercase : List[str] = model_inputs.pop("""start_labels""" ) lowercase : Optional[int] = model_inputs.pop("""end_labels""" ) lowercase : str = model_inputs.pop("""pooled_labels""" ) lowercase : Union[str, Any] = state.apply_fn(**SCREAMING_SNAKE_CASE__ , params=SCREAMING_SNAKE_CASE__ , dropout_rng=SCREAMING_SNAKE_CASE__ , train=SCREAMING_SNAKE_CASE__ ) lowercase , lowercase , lowercase : List[str] = outputs return state.loss_fn( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , ) lowercase , lowercase : int = jax.random.split(SCREAMING_SNAKE_CASE__ ) lowercase : Dict = jax.value_and_grad(SCREAMING_SNAKE_CASE__ ) lowercase , lowercase : Union[str, Any] = grad_fn(state.params ) lowercase : List[Any] = jax.lax.pmean({"""loss""": loss} , axis_name="""batch""" ) lowercase : List[Any] = jax.lax.pmean(SCREAMING_SNAKE_CASE__ , """batch""" ) lowercase : str = state.apply_gradients(grads=SCREAMING_SNAKE_CASE__ ) return state, metrics, new_drp_rng @partial(jax.pmap , axis_name="""batch""" ) def _snake_case( SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) -> List[str]: lowercase : int = model_inputs.pop("""start_labels""" ) lowercase : Dict = model_inputs.pop("""end_labels""" ) lowercase : Optional[Any] = model_inputs.pop("""pooled_labels""" ) lowercase : Optional[int] = state.apply_fn(**SCREAMING_SNAKE_CASE__ , params=state.params , train=SCREAMING_SNAKE_CASE__ ) lowercase , lowercase , lowercase : List[Any] = outputs lowercase : Dict = state.loss_fn(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowercase : str = jax.lax.pmean({"""loss""": loss} , axis_name="""batch""" ) return metrics class __snake_case ( train_state.TrainState ): _a : Callable= struct.field(pytree_node=lowerCAmelCase ) @dataclass class __snake_case : _a : Args _a : Callable _a : Callable _a : Callable _a : Callable _a : wandb _a : Callable= None def _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case ,snake_case ,snake_case=None ): '''simple docstring''' lowercase : Tuple = model.params lowercase : Any = TrainState.create( apply_fn=model.__call__ ,params=snake_case ,tx=snake_case ,loss_fn=snake_case ,) if ckpt_dir is not None: lowercase , lowercase , lowercase , lowercase , lowercase : Tuple = restore_checkpoint(snake_case ,snake_case ) lowercase : List[str] = { """lr""": args.lr, """init_lr""": args.init_lr, """warmup_steps""": args.warmup_steps, """num_train_steps""": num_train_steps, """weight_decay""": args.weight_decay, } lowercase , lowercase : Tuple = build_tx(**snake_case ) lowercase : str = train_state.TrainState( step=snake_case ,apply_fn=model.__call__ ,params=snake_case ,tx=snake_case ,opt_state=snake_case ,) lowercase : Any = args lowercase : Optional[Any] = data_collator lowercase : List[str] = lr lowercase : str = params lowercase : Tuple = jax_utils.replicate(snake_case ) return state def _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case ,snake_case ): '''simple docstring''' lowercase : Dict = self.args lowercase : Optional[Any] = len(snake_case ) // args.batch_size lowercase : int = jax.random.PRNGKey(0 ) lowercase : List[str] = jax.random.split(snake_case ,jax.device_count() ) for epoch in range(args.max_epochs ): lowercase : List[Any] = jnp.array(0 ,dtype=jnp.floataa ) lowercase : List[str] = get_batched_dataset(snake_case ,args.batch_size ,seed=snake_case ) lowercase : int = 0 for batch in tqdm(snake_case ,total=snake_case ,desc=f"Running EPOCH-{epoch}" ): lowercase : Dict = self.data_collator(snake_case ) lowercase , lowercase , lowercase : Optional[int] = self.train_step_fn(snake_case ,snake_case ,**snake_case ) running_loss += jax_utils.unreplicate(metrics["""loss"""] ) i += 1 if i % args.logging_steps == 0: lowercase : Optional[Any] = jax_utils.unreplicate(state.step ) lowercase : List[str] = running_loss.item() / i lowercase : List[str] = self.scheduler_fn(state_step - 1 ) lowercase : int = self.evaluate(snake_case ,snake_case ) lowercase : Tuple = { """step""": state_step.item(), """eval_loss""": eval_loss.item(), """tr_loss""": tr_loss, """lr""": lr.item(), } tqdm.write(str(snake_case ) ) self.logger.log(snake_case ,commit=snake_case ) if i % args.save_steps == 0: self.save_checkpoint(args.save_dir + f"-e{epoch}-s{i}" ,state=snake_case ) def _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case ): '''simple docstring''' lowercase : List[str] = get_batched_dataset(snake_case ,self.args.batch_size ) lowercase : Any = len(snake_case ) // self.args.batch_size lowercase : List[Any] = jnp.array(0 ,dtype=jnp.floataa ) lowercase : Optional[int] = 0 for batch in tqdm(snake_case ,total=snake_case ,desc="""Evaluating ... """ ): lowercase : Tuple = self.data_collator(snake_case ) lowercase : Optional[int] = self.val_step_fn(snake_case ,**snake_case ) running_loss += jax_utils.unreplicate(metrics["""loss"""] ) i += 1 return running_loss / i def _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case ): '''simple docstring''' lowercase : str = jax_utils.unreplicate(snake_case ) print(f"SAVING CHECKPOINT IN {save_dir}" ,end=""" ... """ ) self.model_save_fn(snake_case ,params=state.params ) with open(os.path.join(snake_case ,"""opt_state.msgpack""" ) ,"""wb""" ) as f: f.write(to_bytes(state.opt_state ) ) joblib.dump(self.args ,os.path.join(snake_case ,"""args.joblib""" ) ) joblib.dump(self.data_collator ,os.path.join(snake_case ,"""data_collator.joblib""" ) ) with open(os.path.join(snake_case ,"""training_state.json""" ) ,"""w""" ) as f: json.dump({"""step""": state.step.item()} ,snake_case ) print("""DONE""" ) def _snake_case( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> Union[str, Any]: print(f"RESTORING CHECKPOINT FROM {save_dir}" , end=""" ... """ ) with open(os.path.join(SCREAMING_SNAKE_CASE__ , """flax_model.msgpack""" ) , """rb""" ) as f: lowercase : str = from_bytes(state.params , f.read() ) with open(os.path.join(SCREAMING_SNAKE_CASE__ , """opt_state.msgpack""" ) , """rb""" ) as f: lowercase : Optional[int] = from_bytes(state.opt_state , f.read() ) lowercase : Optional[Any] = joblib.load(os.path.join(SCREAMING_SNAKE_CASE__ , """args.joblib""" ) ) lowercase : int = joblib.load(os.path.join(SCREAMING_SNAKE_CASE__ , """data_collator.joblib""" ) ) with open(os.path.join(SCREAMING_SNAKE_CASE__ , """training_state.json""" ) , """r""" ) as f: lowercase : Tuple = json.load(SCREAMING_SNAKE_CASE__ ) lowercase : Tuple = training_state["""step"""] print("""DONE""" ) return params, opt_state, step, args, data_collator def _snake_case( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> List[Any]: lowercase : List[str] = num_train_steps - warmup_steps lowercase : Dict = optax.linear_schedule(init_value=SCREAMING_SNAKE_CASE__ , end_value=SCREAMING_SNAKE_CASE__ , transition_steps=SCREAMING_SNAKE_CASE__ ) lowercase : List[str] = optax.linear_schedule(init_value=SCREAMING_SNAKE_CASE__ , end_value=1e-7 , transition_steps=SCREAMING_SNAKE_CASE__ ) lowercase : Tuple = optax.join_schedules(schedules=[warmup_fn, decay_fn] , boundaries=[warmup_steps] ) return lr def _snake_case( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> Optional[Any]: def weight_decay_mask(SCREAMING_SNAKE_CASE__ ): lowercase : List[Any] = traverse_util.flatten_dict(SCREAMING_SNAKE_CASE__ ) lowercase : List[Any] = {k: (v[-1] != """bias""" and v[-2:] != ("""LayerNorm""", """scale""")) for k, v in params.items()} return traverse_util.unflatten_dict(SCREAMING_SNAKE_CASE__ ) lowercase : List[str] = scheduler_fn(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowercase : List[str] = optax.adamw(learning_rate=SCREAMING_SNAKE_CASE__ , weight_decay=SCREAMING_SNAKE_CASE__ , mask=SCREAMING_SNAKE_CASE__ ) return tx, lr
20
'''simple docstring''' import warnings from ...utils import logging from .image_processing_glpn import GLPNImageProcessor A_ = logging.get_logger(__name__) class _snake_case ( _a ): def __init__( self : Optional[Any] ,*SCREAMING_SNAKE_CASE__ : Dict ,**SCREAMING_SNAKE_CASE__ : Tuple ): warnings.warn( "The class GLPNFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use GLPNImageProcessor instead." ,SCREAMING_SNAKE_CASE__ ,) super().__init__(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ )
139
0
from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo __lowerCAmelCase : Optional[Any] ="""\ @misc{wu2016googles, title={Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation}, author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes and Jeffrey Dean}, year={2016}, eprint={1609.08144}, archivePrefix={arXiv}, primaryClass={cs.CL} } """ __lowerCAmelCase : Union[str, Any] ="""\ The BLEU score has some undesirable properties when used for single sentences, as it was designed to be a corpus measure. We therefore use a slightly different score for our RL experiments which we call the 'GLEU score'. For the GLEU score, we record all sub-sequences of 1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then compute a recall, which is the ratio of the number of matching n-grams to the number of total n-grams in the target (ground truth) sequence, and a precision, which is the ratio of the number of matching n-grams to the number of total n-grams in the generated output sequence. Then GLEU score is simply the minimum of recall and precision. This GLEU score's range is always between 0 (no matches) and 1 (all match) and it is symmetrical when switching output and target. According to our experiments, GLEU score correlates quite well with the BLEU metric on a corpus level but does not have its drawbacks for our per sentence reward objective. """ __lowerCAmelCase : str ="""\ Computes corpus-level Google BLEU (GLEU) score of translated segments against one or more references. Instead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching tokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values. Args: predictions (list of str): list of translations to score. Each translation should be tokenized into a list of tokens. references (list of list of str): list of lists of references for each translation. Each reference should be tokenized into a list of tokens. min_len (int): The minimum order of n-gram this function should extract. Defaults to 1. max_len (int): The maximum order of n-gram this function should extract. Defaults to 4. Returns: 'google_bleu': google_bleu score Examples: Example 1: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results[\"google_bleu\"], 2)) 0.44 Example 2: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results[\"google_bleu\"], 2)) 0.61 Example 3: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2) >>> print(round(results[\"google_bleu\"], 2)) 0.53 Example 4: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6) >>> print(round(results[\"google_bleu\"], 2)) 0.4 """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCAmelCase ( datasets.Metric ): def UpperCAmelCase_ ( self :int )-> Dict: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Sequence(datasets.Value("string" , id="token" ) , id="sequence" ), "references": datasets.Sequence( datasets.Sequence(datasets.Value("string" , id="token" ) , id="sequence" ) , id="references" ), } ) , ) def UpperCAmelCase_ ( self :Tuple , lowercase_ :Dict , lowercase_ :Union[str, Any] , lowercase_ :Optional[int] = 1 , lowercase_ :List[Any] = 4 , )-> Optional[int]: return { "google_bleu": gleu_score.corpus_gleu( list_of_references=lowercase_ , hypotheses=lowercase_ , min_len=lowercase_ , max_len=lowercase_ ) }
356
'''simple docstring''' from __future__ import annotations import unittest from transformers import DistilBertConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.distilbert.modeling_tf_distilbert import ( TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDistilBertForMaskedLM, TFDistilBertForMultipleChoice, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertModel, ) class UpperCAmelCase : def __init__( self :str , lowercase_ :str , )-> str: A__ = parent A__ = 13 A__ = 7 A__ = True A__ = True A__ = False A__ = True A__ = 99 A__ = 32 A__ = 2 A__ = 4 A__ = 37 A__ = "gelu" A__ = 0.1 A__ = 0.1 A__ = 5_12 A__ = 16 A__ = 2 A__ = 0.0_2 A__ = 3 A__ = 4 A__ = None def UpperCAmelCase_ ( self :Union[str, Any] )-> int: 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__ = DistilBertConfig( vocab_size=self.vocab_size , dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , hidden_dim=self.intermediate_size , hidden_act=self.hidden_act , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , ) return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ ( self :str , lowercase_ :Optional[int] , lowercase_ :List[str] , lowercase_ :Any , lowercase_ :Union[str, Any] , lowercase_ :Optional[int] , lowercase_ :str )-> List[str]: A__ = TFDistilBertModel(config=lowercase_ ) A__ = {"input_ids": input_ids, "attention_mask": input_mask} A__ = model(lowercase_ ) A__ = [input_ids, input_mask] A__ = model(lowercase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self :List[str] , lowercase_ :str , lowercase_ :Optional[Any] , lowercase_ :Optional[int] , lowercase_ :Optional[int] , lowercase_ :Optional[int] , lowercase_ :Union[str, Any] )-> Optional[int]: A__ = TFDistilBertForMaskedLM(config=lowercase_ ) A__ = {"input_ids": input_ids, "attention_mask": input_mask} A__ = model(lowercase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ ( self :Any , lowercase_ :str , lowercase_ :str , lowercase_ :Optional[int] , lowercase_ :str , lowercase_ :List[Any] , lowercase_ :Union[str, Any] )-> Optional[int]: A__ = TFDistilBertForQuestionAnswering(config=lowercase_ ) A__ = { "input_ids": input_ids, "attention_mask": input_mask, } A__ = model(lowercase_ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def UpperCAmelCase_ ( self :Union[str, Any] , lowercase_ :Optional[int] , lowercase_ :Any , lowercase_ :Dict , lowercase_ :Tuple , lowercase_ :Optional[Any] , lowercase_ :Optional[int] )-> Any: A__ = self.num_labels A__ = TFDistilBertForSequenceClassification(lowercase_ ) A__ = {"input_ids": input_ids, "attention_mask": input_mask} A__ = model(lowercase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase_ ( self :str , lowercase_ :Optional[Any] , lowercase_ :List[Any] , lowercase_ :Dict , lowercase_ :Tuple , lowercase_ :int , lowercase_ :Union[str, Any] )-> str: A__ = self.num_choices A__ = TFDistilBertForMultipleChoice(lowercase_ ) A__ = tf.tile(tf.expand_dims(lowercase_ , 1 ) , (1, self.num_choices, 1) ) A__ = tf.tile(tf.expand_dims(lowercase_ , 1 ) , (1, self.num_choices, 1) ) A__ = { "input_ids": multiple_choice_inputs_ids, "attention_mask": multiple_choice_input_mask, } A__ = model(lowercase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCAmelCase_ ( self :str , lowercase_ :Any , lowercase_ :List[str] , lowercase_ :Any , lowercase_ :int , lowercase_ :List[Any] , lowercase_ :Tuple )-> Tuple: A__ = self.num_labels A__ = TFDistilBertForTokenClassification(lowercase_ ) A__ = {"input_ids": input_ids, "attention_mask": input_mask} A__ = model(lowercase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase_ ( self :Any )-> Union[str, Any]: 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 UpperCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): __lowercase = ( ( TFDistilBertModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertForMultipleChoice, ) if is_tf_available() else None ) __lowercase = ( { """feature-extraction""": TFDistilBertModel, """fill-mask""": TFDistilBertForMaskedLM, """question-answering""": TFDistilBertForQuestionAnswering, """text-classification""": TFDistilBertForSequenceClassification, """token-classification""": TFDistilBertForTokenClassification, """zero-shot""": TFDistilBertForSequenceClassification, } if is_tf_available() else {} ) __lowercase = False __lowercase = False def UpperCAmelCase_ ( self :Optional[Any] )-> List[Any]: A__ = TFDistilBertModelTester(self ) A__ = ConfigTester(self , config_class=lowercase_ , dim=37 ) def UpperCAmelCase_ ( self :Tuple )-> Tuple: self.config_tester.run_common_tests() def UpperCAmelCase_ ( self :int )-> Tuple: A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_model(*lowercase_ ) def UpperCAmelCase_ ( self :Optional[int] )-> Optional[Any]: A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_masked_lm(*lowercase_ ) def UpperCAmelCase_ ( self :str )-> str: A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_question_answering(*lowercase_ ) def UpperCAmelCase_ ( self :List[str] )-> Dict: A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_sequence_classification(*lowercase_ ) def UpperCAmelCase_ ( self :List[str] )-> Optional[int]: A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_multiple_choice(*lowercase_ ) def UpperCAmelCase_ ( self :str )-> int: A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_token_classification(*lowercase_ ) @slow def UpperCAmelCase_ ( self :List[str] )-> Dict: for model_name in list(TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1] ): A__ = TFDistilBertModel.from_pretrained(lowercase_ ) self.assertIsNotNone(lowercase_ ) @require_tf class UpperCAmelCase ( unittest.TestCase ): @slow def UpperCAmelCase_ ( self :List[Any] )-> Any: A__ = TFDistilBertModel.from_pretrained("distilbert-base-uncased" ) A__ = tf.constant([[0, 1, 2, 3, 4, 5]] ) A__ = model(lowercase_ )[0] A__ = [1, 6, 7_68] self.assertEqual(output.shape , lowercase_ ) A__ = tf.constant( [ [ [0.1_9_2_6_1_8_8_5, -0.1_3_7_3_2_9_5_5, 0.4_1_1_9_7_9_9], [0.2_2_1_5_0_1_5_6, -0.0_7_4_2_2_6_6_1, 0.3_9_0_3_7_2_0_4], [0.2_2_7_5_6_0_1_8, -0.0_8_9_6_4_1_4, 0.3_7_0_1_4_6_7], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , lowercase_ , atol=1E-4 )
123
0
# Copyright 2022 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os import platform import numpy as np import psutil import torch from accelerate import __version__ as version from accelerate.commands.config import default_config_file, load_config_from_file from ..utils import is_npu_available, is_xpu_available def __lowercase ( a__=None ) -> Union[str, Any]: if subparsers is not None: __SCREAMING_SNAKE_CASE = subparsers.add_parser('env' ) else: __SCREAMING_SNAKE_CASE = argparse.ArgumentParser('Accelerate env command' ) parser.add_argument( '--config_file' , default=a__ , help='The config file to use for the default values in the launching script.' ) if subparsers is not None: parser.set_defaults(func=a__ ) return parser def __lowercase ( a__ ) -> Optional[int]: __SCREAMING_SNAKE_CASE = torch.__version__ __SCREAMING_SNAKE_CASE = torch.cuda.is_available() __SCREAMING_SNAKE_CASE = is_xpu_available() __SCREAMING_SNAKE_CASE = is_npu_available() __SCREAMING_SNAKE_CASE = 'Not found' # Get the default from the config file. if args.config_file is not None or os.path.isfile(a__ ): __SCREAMING_SNAKE_CASE = load_config_from_file(args.config_file ).to_dict() __SCREAMING_SNAKE_CASE = { '`Accelerate` version': version, 'Platform': platform.platform(), 'Python version': platform.python_version(), 'Numpy version': np.__version__, 'PyTorch version (GPU?)': f"""{pt_version} ({pt_cuda_available})""", 'PyTorch XPU available': str(a__ ), 'PyTorch NPU available': str(a__ ), 'System RAM': f"""{psutil.virtual_memory().total / 10_24 ** 3:.2f} GB""", } if pt_cuda_available: __SCREAMING_SNAKE_CASE = torch.cuda.get_device_name() print('\nCopy-and-paste the text below in your GitHub issue\n' ) print('\n'.join([f"""- {prop}: {val}""" for prop, val in info.items()] ) ) print('- `Accelerate` default config:' if args.config_file is None else '- `Accelerate` config passed:' ) __SCREAMING_SNAKE_CASE = ( '\n'.join([f"""\t- {prop}: {val}""" for prop, val in accelerate_config.items()] ) if isinstance(a__ , a__ ) else f"""\t{accelerate_config}""" ) print(a__ ) __SCREAMING_SNAKE_CASE = accelerate_config return info def __lowercase ( ) -> int: __SCREAMING_SNAKE_CASE = env_command_parser() __SCREAMING_SNAKE_CASE = parser.parse_args() env_command(a__ ) return 0 if __name__ == "__main__": raise SystemExit(main())
257
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowerCAmelCase__ : Optional[Any] ={ '''configuration_mobilenet_v2''': [ '''MOBILENET_V2_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MobileNetV2Config''', '''MobileNetV2OnnxConfig''', ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ : Dict =['''MobileNetV2FeatureExtractor'''] lowerCAmelCase__ : str =['''MobileNetV2ImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ : Union[str, Any] =[ '''MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MobileNetV2ForImageClassification''', '''MobileNetV2ForSemanticSegmentation''', '''MobileNetV2Model''', '''MobileNetV2PreTrainedModel''', '''load_tf_weights_in_mobilenet_v2''', ] if TYPE_CHECKING: from .configuration_mobilenet_va import ( MOBILENET_V2_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileNetVaConfig, MobileNetVaOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_mobilenet_va import MobileNetVaFeatureExtractor from .image_processing_mobilenet_va import MobileNetVaImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mobilenet_va import ( MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation, MobileNetVaModel, MobileNetVaPreTrainedModel, load_tf_weights_in_mobilenet_va, ) else: import sys lowerCAmelCase__ : Union[str, Any] =_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
257
1
import math def UpperCamelCase ( __magic_name__ : float , __magic_name__ : float ) -> float: """simple docstring""" return math.pow(__magic_name__ , 2 ) - a def UpperCamelCase ( __magic_name__ : float ) -> float: """simple docstring""" return 2 * x def UpperCamelCase ( __magic_name__ : float ) -> float: """simple docstring""" lowercase__ = 2.0 while start <= a: lowercase__ = math.pow(__magic_name__ , 2 ) return start def UpperCamelCase ( __magic_name__ : float , __magic_name__ : int = 9999 , __magic_name__ : float = 0.0_0_0_0_0_0_0_0_0_0_0_0_0_1 ) -> float: """simple docstring""" if a < 0: raise ValueError("""math domain error""" ) lowercase__ = get_initial_point(__magic_name__ ) for _ in range(__magic_name__ ): lowercase__ = value lowercase__ = value - fx(__magic_name__ , __magic_name__ ) / fx_derivative(__magic_name__ ) if abs(prev_value - value ) < tolerance: return value return value if __name__ == "__main__": from doctest import testmod testmod()
146
A : Union[str, Any] = [ (1_0_0_0, 'M'), (9_0_0, 'CM'), (5_0_0, 'D'), (4_0_0, 'CD'), (1_0_0, 'C'), (9_0, 'XC'), (5_0, 'L'), (4_0, 'XL'), (1_0, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I'), ] def UpperCamelCase ( __magic_name__ : str ) -> int: """simple docstring""" lowercase__ = {"""I""": 1, """V""": 5, """X""": 10, """L""": 50, """C""": 100, """D""": 500, """M""": 1000} lowercase__ = 0 lowercase__ = 0 while place < len(__magic_name__ ): if (place + 1 < len(__magic_name__ )) and (vals[roman[place]] < vals[roman[place + 1]]): total += vals[roman[place + 1]] - vals[roman[place]] place += 2 else: total += vals[roman[place]] place += 1 return total def UpperCamelCase ( __magic_name__ : int ) -> str: """simple docstring""" lowercase__ = [] for arabic, roman in ROMAN: ((lowercase__) , (lowercase__)) = divmod(__magic_name__ , __magic_name__ ) result.append(roman * factor ) if number == 0: break return "".join(__magic_name__ ) if __name__ == "__main__": import doctest doctest.testmod()
146
1
from io import BytesIO from typing import List, Union import requests from ..utils import add_end_docstrings, is_decord_available, is_torch_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_decord_available(): import numpy as np from decord import VideoReader if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING __a :Dict = logging.get_logger(__name__) @add_end_docstrings(snake_case__ ) class _a ( snake_case__ ): """simple docstring""" def __init__( self : List[str] , *UpperCAmelCase : Tuple , **UpperCAmelCase : List[str] ): super().__init__(*UpperCAmelCase , **UpperCAmelCase ) requires_backends(self , "decord" ) self.check_model_type(UpperCAmelCase ) def __A ( self : Union[str, Any] , UpperCAmelCase : int=None , UpperCAmelCase : int=None , UpperCAmelCase : Any=None ): A_ = {} if frame_sampling_rate is not None: A_ = frame_sampling_rate if num_frames is not None: A_ = num_frames A_ = {} if top_k is not None: A_ = top_k return preprocess_params, {}, postprocess_params def __call__( self : str , UpperCAmelCase : Union[str, List[str]] , **UpperCAmelCase : List[str] ): return super().__call__(UpperCAmelCase , **UpperCAmelCase ) def __A ( self : List[Any] , UpperCAmelCase : str , UpperCAmelCase : List[str]=None , UpperCAmelCase : Optional[int]=1 ): if num_frames is None: A_ = self.model.config.num_frames if video.startswith("http://" ) or video.startswith("https://" ): A_ = BytesIO(requests.get(UpperCAmelCase ).content ) A_ = VideoReader(UpperCAmelCase ) videoreader.seek(0 ) A_ = 0 A_ = num_frames * frame_sampling_rate - 1 A_ = np.linspace(UpperCAmelCase , UpperCAmelCase , num=UpperCAmelCase , dtype=np.intaa ) A_ = videoreader.get_batch(UpperCAmelCase ).asnumpy() A_ = list(UpperCAmelCase ) A_ = self.image_processor(UpperCAmelCase , return_tensors=self.framework ) return model_inputs def __A ( self : Optional[int] , UpperCAmelCase : List[str] ): A_ = self.model(**UpperCAmelCase ) return model_outputs def __A ( self : int , UpperCAmelCase : List[str] , UpperCAmelCase : str=5 ): if top_k > self.model.config.num_labels: A_ = self.model.config.num_labels if self.framework == "pt": A_ = model_outputs.logits.softmax(-1 )[0] A_ = probs.topk(UpperCAmelCase ) else: raise ValueError(f'''Unsupported framework: {self.framework}''' ) A_ = scores.tolist() A_ = ids.tolist() return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(UpperCAmelCase , UpperCAmelCase )]
312
'''simple docstring''' import math import unittest from transformers import BioGptConfig, 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 ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCamelCase_ : '''simple docstring''' def __init__( self : List[Any] , A : Dict , A : Optional[Any]=13 , A : Optional[Any]=7 , A : Union[str, Any]=True , A : Optional[Any]=True , A : int=False , A : str=True , A : Optional[Any]=99 , A : Union[str, Any]=32 , A : int=5 , A : Tuple=4 , A : Union[str, Any]=37 , A : Dict="gelu" , A : Union[str, Any]=0.1 , A : str=0.1 , A : Union[str, Any]=512 , A : int=16 , A : List[str]=2 , A : Tuple=0.02 , A : int=3 , A : List[str]=4 , A : str=None , ): _UpperCAmelCase : List[Any] = parent _UpperCAmelCase : Any = batch_size _UpperCAmelCase : int = seq_length _UpperCAmelCase : Union[str, Any] = is_training _UpperCAmelCase : Any = use_input_mask _UpperCAmelCase : Optional[Any] = use_token_type_ids _UpperCAmelCase : str = use_labels _UpperCAmelCase : Union[str, Any] = vocab_size _UpperCAmelCase : Tuple = hidden_size _UpperCAmelCase : Union[str, Any] = num_hidden_layers _UpperCAmelCase : Optional[Any] = num_attention_heads _UpperCAmelCase : Union[str, Any] = intermediate_size _UpperCAmelCase : Union[str, Any] = hidden_act _UpperCAmelCase : List[Any] = hidden_dropout_prob _UpperCAmelCase : List[Any] = attention_probs_dropout_prob _UpperCAmelCase : Optional[int] = max_position_embeddings _UpperCAmelCase : str = type_vocab_size _UpperCAmelCase : str = type_sequence_label_size _UpperCAmelCase : int = initializer_range _UpperCAmelCase : Optional[Any] = num_labels _UpperCAmelCase : List[str] = num_choices _UpperCAmelCase : List[str] = scope def _A ( self : Optional[int] ): _UpperCAmelCase : Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _UpperCAmelCase : Union[str, Any] = None if self.use_input_mask: _UpperCAmelCase : List[Any] = random_attention_mask([self.batch_size, self.seq_length] ) _UpperCAmelCase : Any = None if self.use_token_type_ids: _UpperCAmelCase : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _UpperCAmelCase : Optional[int] = None _UpperCAmelCase : Any = None _UpperCAmelCase : Optional[int] = None if self.use_labels: _UpperCAmelCase : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _UpperCAmelCase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _UpperCAmelCase : List[str] = ids_tensor([self.batch_size] , self.num_choices ) _UpperCAmelCase : List[Any] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _A ( self : Dict ): return BioGptConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=A , initializer_range=self.initializer_range , ) def _A ( self : int , A : List[Any] , A : Any , A : int , A : Union[str, Any] , A : Dict , A : List[Any] , A : Dict ): _UpperCAmelCase : List[str] = BioGptModel(config=A ) model.to(A ) model.eval() _UpperCAmelCase : Tuple = model(A , attention_mask=A ) _UpperCAmelCase : int = model(A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _A ( self : List[Any] , A : str , A : List[Any] , A : Dict , A : List[Any] , A : List[str] , A : Union[str, Any] , A : int , A : List[str] , A : Dict , ): _UpperCAmelCase : Optional[int] = BioGptForCausalLM(config=A ) model.to(A ) model.eval() _UpperCAmelCase : Optional[int] = model(A , attention_mask=A , token_type_ids=A , labels=A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _A ( self : List[Any] , A : str , A : str , A : str , A : Any , A : List[str] , *A : Optional[int] ): _UpperCAmelCase : str = BioGptModel(config=A ) model.to(A ) model.eval() # create attention mask _UpperCAmelCase : List[Any] = torch.ones(input_ids.shape , dtype=torch.long , device=A ) _UpperCAmelCase : Optional[int] = self.seq_length // 2 _UpperCAmelCase : List[Any] = 0 # first forward pass _UpperCAmelCase , _UpperCAmelCase : List[str] = model(A , attention_mask=A ).to_tuple() # create hypothetical next token and extent to next_input_ids _UpperCAmelCase : List[str] = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids _UpperCAmelCase : List[str] = ids_tensor((1,) , A ).item() + 1 _UpperCAmelCase : str = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) _UpperCAmelCase : Any = random_other_next_tokens # append to next input_ids and attn_mask _UpperCAmelCase : List[Any] = torch.cat([input_ids, next_tokens] , dim=-1 ) _UpperCAmelCase : Optional[int] = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=A )] , dim=1 , ) # get two different outputs _UpperCAmelCase : List[Any] = model(A , attention_mask=A )["last_hidden_state"] _UpperCAmelCase : Optional[Any] = model(A , past_key_values=A , attention_mask=A )["last_hidden_state"] # select random slice _UpperCAmelCase : Any = ids_tensor((1,) , output_from_past.shape[-1] ).item() _UpperCAmelCase : Optional[Any] = output_from_no_past[:, -1, random_slice_idx].detach() _UpperCAmelCase : Any = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(A , A , atol=1E-3 ) ) def _A ( self : int , A : Dict , A : str , A : Dict , A : Union[str, Any] , A : Any , *A : Union[str, Any] ): _UpperCAmelCase : Optional[Any] = BioGptModel(config=A ).to(A ).eval() _UpperCAmelCase : List[Any] = torch.ones(input_ids.shape , dtype=torch.long , device=A ) # first forward pass _UpperCAmelCase : Union[str, Any] = model(A , attention_mask=A , use_cache=A ) _UpperCAmelCase , _UpperCAmelCase : Dict = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids _UpperCAmelCase : str = ids_tensor((self.batch_size, 3) , config.vocab_size ) _UpperCAmelCase : Any = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and _UpperCAmelCase : Optional[Any] = torch.cat([input_ids, next_tokens] , dim=-1 ) _UpperCAmelCase : Dict = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) _UpperCAmelCase : Any = model(A , attention_mask=A )["last_hidden_state"] _UpperCAmelCase : Dict = model(A , attention_mask=A , past_key_values=A )[ "last_hidden_state" ] # select random slice _UpperCAmelCase : Dict = ids_tensor((1,) , output_from_past.shape[-1] ).item() _UpperCAmelCase : Dict = output_from_no_past[:, -3:, random_slice_idx].detach() _UpperCAmelCase : Any = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(A , A , atol=1E-3 ) ) def _A ( self : Optional[Any] , A : Tuple , A : List[str] , A : Tuple , A : Dict , A : List[Any] , *A : Tuple , A : List[str]=False ): _UpperCAmelCase : Optional[int] = BioGptForCausalLM(A ) model.to(A ) if gradient_checkpointing: model.gradient_checkpointing_enable() _UpperCAmelCase : Union[str, Any] = model(A , labels=A ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def _A ( self : Optional[Any] , A : Any , *A : Optional[Any] ): _UpperCAmelCase : Tuple = BioGptModel(A ) _UpperCAmelCase : int = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) , 0.001 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.01 ) def _A ( self : Optional[int] , A : Dict , A : Tuple , A : Optional[int] , A : int , A : List[str] , *A : Dict ): _UpperCAmelCase : Any = self.num_labels _UpperCAmelCase : Any = BioGptForTokenClassification(A ) model.to(A ) model.eval() _UpperCAmelCase : Optional[int] = model(A , attention_mask=A , token_type_ids=A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _A ( self : int ): _UpperCAmelCase : Dict = self.prepare_config_and_inputs() ( ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ) : List[str] = config_and_inputs _UpperCAmelCase : Optional[int] = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class lowerCamelCase_ (snake_case__ , snake_case__ , snake_case__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase: List[str] = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) __UpperCamelCase: List[str] = (BioGptForCausalLM,) if is_torch_available() else () __UpperCamelCase: str = ( { "feature-extraction": BioGptModel, "text-classification": BioGptForSequenceClassification, "text-generation": BioGptForCausalLM, "token-classification": BioGptForTokenClassification, "zero-shot": BioGptForSequenceClassification, } if is_torch_available() else {} ) __UpperCamelCase: Union[str, Any] = False def _A ( self : Optional[Any] ): _UpperCAmelCase : List[Any] = BioGptModelTester(self ) _UpperCAmelCase : str = ConfigTester(self , config_class=A , hidden_size=37 ) def _A ( self : Union[str, Any] ): self.config_tester.run_common_tests() def _A ( self : Any ): _UpperCAmelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A ) def _A ( self : Any ): _UpperCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: _UpperCAmelCase : Tuple = type self.model_tester.create_and_check_model(*A ) def _A ( self : int ): _UpperCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*A ) def _A ( self : Union[str, Any] ): _UpperCAmelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*A , gradient_checkpointing=A ) def _A ( self : Union[str, Any] ): _UpperCAmelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*A ) def _A ( self : Dict ): _UpperCAmelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*A ) def _A ( self : Dict ): _UpperCAmelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*A ) @slow def _A ( self : List[str] ): _UpperCAmelCase : Optional[Any] = BioGptForCausalLM.from_pretrained("microsoft/biogpt" ) model.to(A ) _UpperCAmelCase : Tuple = BioGptTokenizer.from_pretrained("microsoft/biogpt" ) _UpperCAmelCase : str = "left" # Define PAD Token = EOS Token = 50256 _UpperCAmelCase : Any = tokenizer.eos_token _UpperCAmelCase : int = model.config.eos_token_id # use different length sentences to test batching _UpperCAmelCase : Any = [ "Hello, my dog is a little", "Today, I", ] _UpperCAmelCase : Tuple = tokenizer(A , return_tensors="pt" , padding=A ) _UpperCAmelCase : Optional[Any] = inputs["input_ids"].to(A ) _UpperCAmelCase : Any = model.generate( input_ids=A , attention_mask=inputs["attention_mask"].to(A ) , ) _UpperCAmelCase : int = tokenizer(sentences[0] , return_tensors="pt" ).input_ids.to(A ) _UpperCAmelCase : List[Any] = model.generate(input_ids=A ) _UpperCAmelCase : List[Any] = inputs_non_padded.shape[-1] - inputs["attention_mask"][-1].long().sum().cpu().item() _UpperCAmelCase : int = tokenizer(sentences[1] , return_tensors="pt" ).input_ids.to(A ) _UpperCAmelCase : int = model.generate(input_ids=A , max_length=model.config.max_length - num_paddings ) _UpperCAmelCase : Dict = tokenizer.batch_decode(A , skip_special_tokens=A ) _UpperCAmelCase : Any = tokenizer.decode(output_non_padded[0] , skip_special_tokens=A ) _UpperCAmelCase : Optional[int] = tokenizer.decode(output_padded[0] , skip_special_tokens=A ) _UpperCAmelCase : str = [ "Hello, my dog is a little bit bigger than a little bit.", "Today, I have a good idea of how to use the information", ] self.assertListEqual(A , A ) self.assertListEqual(A , [non_padded_sentence, padded_sentence] ) @slow def _A ( self : str ): for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _UpperCAmelCase : Optional[Any] = BioGptModel.from_pretrained(A ) self.assertIsNotNone(A ) def _A ( self : List[str] ): _UpperCAmelCase , _UpperCAmelCase : int = self.model_tester.prepare_config_and_inputs_for_common() _UpperCAmelCase : str = 3 _UpperCAmelCase : List[str] = input_dict["input_ids"] _UpperCAmelCase : Dict = input_ids.ne(1 ).to(A ) _UpperCAmelCase : List[Any] = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) _UpperCAmelCase : List[str] = BioGptForSequenceClassification(A ) model.to(A ) model.eval() _UpperCAmelCase : List[str] = model(A , attention_mask=A , labels=A ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def _A ( self : int ): _UpperCAmelCase , _UpperCAmelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() _UpperCAmelCase : int = 3 _UpperCAmelCase : Dict = "multi_label_classification" _UpperCAmelCase : Optional[Any] = input_dict["input_ids"] _UpperCAmelCase : Optional[int] = input_ids.ne(1 ).to(A ) _UpperCAmelCase : Tuple = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) _UpperCAmelCase : Optional[Any] = BioGptForSequenceClassification(A ) model.to(A ) model.eval() _UpperCAmelCase : Tuple = model(A , attention_mask=A , labels=A ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class lowerCamelCase_ (unittest.TestCase ): '''simple docstring''' @slow def _A ( self : List[Any] ): _UpperCAmelCase : Optional[Any] = BioGptForCausalLM.from_pretrained("microsoft/biogpt" ) _UpperCAmelCase : List[str] = torch.tensor([[2, 4805, 9, 656, 21]] ) _UpperCAmelCase : List[Any] = model(A )[0] _UpperCAmelCase : int = 42384 _UpperCAmelCase : int = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , A ) _UpperCAmelCase : Any = torch.tensor( [[[-9.5_236, -9.8_918, 10.4_557], [-11.0_469, -9.6_423, 8.1_022], [-8.8_664, -7.8_826, 5.5_325]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , A , atol=1E-4 ) ) @slow def _A ( self : Any ): _UpperCAmelCase : str = BioGptTokenizer.from_pretrained("microsoft/biogpt" ) _UpperCAmelCase : Tuple = BioGptForCausalLM.from_pretrained("microsoft/biogpt" ) model.to(A ) torch.manual_seed(0 ) _UpperCAmelCase : Optional[Any] = tokenizer("COVID-19 is" , return_tensors="pt" ).to(A ) _UpperCAmelCase : Dict = model.generate( **A , min_length=100 , max_length=1024 , num_beams=5 , early_stopping=A , ) _UpperCAmelCase : Optional[Any] = tokenizer.decode(output_ids[0] , skip_special_tokens=A ) _UpperCAmelCase : List[str] = ( "COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the" " causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and" " territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK)," " and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and" " more than 800,000 deaths." ) self.assertEqual(A , A )
31
0
import os import unittest from transformers.models.transfo_xl.tokenization_transfo_xl import VOCAB_FILES_NAMES, TransfoXLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowercase_ = TransfoXLTokenizer lowercase_ = False lowercase_ = False def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Union[str, Any]: '''simple docstring''' super().setUp() lowerCamelCase__: int =[ "<unk>", "[CLS]", "[SEP]", "want", "unwanted", "wa", "un", "running", ",", "low", "l", ] lowerCamelCase__: Tuple =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"]) with open(self.vocab_file , "w" , encoding="utf-8") as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens])) def SCREAMING_SNAKE_CASE_ (self : Optional[int] , **UpperCAmelCase_ : List[str]) ->List[str]: '''simple docstring''' lowerCamelCase__: int =True return TransfoXLTokenizer.from_pretrained(self.tmpdirname , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : List[Any]) ->Optional[int]: '''simple docstring''' lowerCamelCase__: List[Any] ="<unk> UNwanted , running" lowerCamelCase__: Any ="<unk> unwanted, running" return input_text, output_text def SCREAMING_SNAKE_CASE_ (self : Dict) ->Tuple: '''simple docstring''' lowerCamelCase__: Any =TransfoXLTokenizer(vocab_file=self.vocab_file , lower_case=UpperCAmelCase_) lowerCamelCase__: Union[str, Any] =tokenizer.tokenize("<unk> UNwanted , running") self.assertListEqual(UpperCAmelCase_ , ["<unk>", "unwanted", ",", "running"]) self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase_) , [0, 4, 8, 7]) def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->Any: '''simple docstring''' lowerCamelCase__: int =TransfoXLTokenizer(lower_case=UpperCAmelCase_) self.assertListEqual( tokenizer.tokenize(" \tHeLLo ! how \n Are yoU ? ") , ["hello", "!", "how", "are", "you", "?"]) def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: List[Any] =TransfoXLTokenizer(lower_case=UpperCAmelCase_) self.assertListEqual( tokenizer.tokenize(" \tHeLLo ! how \n Are yoU ? ") , ["HeLLo", "!", "how", "Are", "yoU", "?"]) def SCREAMING_SNAKE_CASE_ (self : Any) ->Dict: '''simple docstring''' lowerCamelCase__: Union[str, Any] =TransfoXLTokenizer(lower_case=UpperCAmelCase_) lowerCamelCase__: Any ="Hello (bracket) and side-scrolled [and] Henry's $5,000 with 3.34 m. What's up!?" lowerCamelCase__: List[Any] =[ "Hello", "(", "bracket", ")", "and", "side", "@-@", "scrolled", "[", "and", "]", "Henry", "'s", "$", "5", "@,@", "000", "with", "3", "@.@", "34", "m", ".", "What", "'s", "up", "!", "?", ] self.assertListEqual(tokenizer.tokenize(UpperCAmelCase_) , UpperCAmelCase_) self.assertEqual(tokenizer.convert_tokens_to_string(UpperCAmelCase_) , UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : str) ->List[Any]: '''simple docstring''' lowerCamelCase__: Optional[int] =self.get_tokenizer() lowerCamelCase__: Any =len(UpperCAmelCase_) tokenizer.add_tokens(["new1", "new2"]) tokenizer.move_added_token("new1" , 1) # Check that moved token is not copied (duplicate) self.assertEqual(len(UpperCAmelCase_) , original_len + 2) # Check that token is moved to specified id self.assertEqual(tokenizer.encode("new1") , [1]) self.assertEqual(tokenizer.decode([1]) , "new1")
273
from __future__ import annotations from typing import Any class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__(self : Tuple , UpperCAmelCase_ : int , UpperCAmelCase_ : int , UpperCAmelCase_ : float = 0) ->None: '''simple docstring''' lowerCamelCase__ , lowerCamelCase__: Any =row, column lowerCamelCase__: List[str] =[[default_value for c in range(UpperCAmelCase_)] for r in range(UpperCAmelCase_)] def __str__(self : Tuple) ->str: '''simple docstring''' lowerCamelCase__: Union[str, Any] =F"""Matrix consist of {self.row} rows and {self.column} columns\n""" # Make string identifier lowerCamelCase__: List[str] =0 for row_vector in self.array: for obj in row_vector: lowerCamelCase__: int =max(UpperCAmelCase_ , len(str(UpperCAmelCase_))) lowerCamelCase__: Any =F"""%{max_element_length}s""" # Make string and return def single_line(UpperCAmelCase_ : list[float]) -> str: nonlocal string_format_identifier lowerCamelCase__: Tuple ="[" line += ", ".join(string_format_identifier % (obj,) for obj in row_vector) line += "]" return line s += "\n".join(single_line(UpperCAmelCase_) for row_vector in self.array) return s def __repr__(self : Optional[int]) ->str: '''simple docstring''' return str(self) def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : tuple[int, int]) ->bool: '''simple docstring''' if not (isinstance(UpperCAmelCase_ , (list, tuple)) and len(UpperCAmelCase_) == 2): return False elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column): return False else: return True def __getitem__(self : int , UpperCAmelCase_ : tuple[int, int]) ->Any: '''simple docstring''' assert self.validate_indicies(UpperCAmelCase_) return self.array[loc[0]][loc[1]] def __setitem__(self : Optional[Any] , UpperCAmelCase_ : tuple[int, int] , UpperCAmelCase_ : float) ->None: '''simple docstring''' assert self.validate_indicies(UpperCAmelCase_) lowerCamelCase__: str =value def __add__(self : Dict , UpperCAmelCase_ : Matrix) ->Matrix: '''simple docstring''' assert isinstance(UpperCAmelCase_ , UpperCAmelCase_) assert self.row == another.row and self.column == another.column # Add lowerCamelCase__: Dict =Matrix(self.row , self.column) for r in range(self.row): for c in range(self.column): lowerCamelCase__: List[str] =self[r, c] + another[r, c] return result def __neg__(self : str) ->Matrix: '''simple docstring''' lowerCamelCase__: List[Any] =Matrix(self.row , self.column) for r in range(self.row): for c in range(self.column): lowerCamelCase__: Union[str, Any] =-self[r, c] return result def __sub__(self : str , UpperCAmelCase_ : Matrix) ->Matrix: '''simple docstring''' return self + (-another) def __mul__(self : List[str] , UpperCAmelCase_ : int | float | Matrix) ->Matrix: '''simple docstring''' if isinstance(UpperCAmelCase_ , (int, float)): # Scalar multiplication lowerCamelCase__: List[Any] =Matrix(self.row , self.column) for r in range(self.row): for c in range(self.column): lowerCamelCase__: Union[str, Any] =self[r, c] * another return result elif isinstance(UpperCAmelCase_ , UpperCAmelCase_): # Matrix multiplication assert self.column == another.row lowerCamelCase__: Dict =Matrix(self.row , another.column) for r in range(self.row): for c in range(another.column): for i in range(self.column): result[r, c] += self[r, i] * another[i, c] return result else: lowerCamelCase__: int =F"""Unsupported type given for another ({type(UpperCAmelCase_)})""" raise TypeError(UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Matrix: '''simple docstring''' lowerCamelCase__: Optional[Any] =Matrix(self.column , self.row) for r in range(self.row): for c in range(self.column): lowerCamelCase__: Optional[int] =self[r, c] return result def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : Matrix , UpperCAmelCase_ : Matrix) ->Any: '''simple docstring''' assert isinstance(UpperCAmelCase_ , UpperCAmelCase_) and isinstance(UpperCAmelCase_ , UpperCAmelCase_) assert self.row == self.column == u.row == v.row # u, v should be column vector assert u.column == v.column == 1 # u, v should be column vector # Calculate lowerCamelCase__: Tuple =v.transpose() lowerCamelCase__: Optional[Any] =(v_t * self * u)[0, 0] + 1 if numerator_factor == 0: return None # It's not invertable return self - ((self * u) * (v_t * self) * (1.0 / numerator_factor)) # Testing if __name__ == "__main__": def lowerCAmelCase_ ( ) -> None: """simple docstring""" lowerCamelCase__: List[str] =Matrix(3 , 3 , 0 ) for i in range(3 ): lowerCamelCase__: Union[str, Any] =1 print(F"""a^(-1) is {ainv}""" ) # u, v lowerCamelCase__: Optional[int] =Matrix(3 , 1 , 0 ) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: int =1, 2, -3 lowerCamelCase__: Optional[Any] =Matrix(3 , 1 , 0 ) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Any =4, -2, 5 print(F"""u is {u}""" ) print(F"""v is {v}""" ) print(F"""uv^T is {u * v.transpose()}""" ) # Sherman Morrison print(F"""(a + uv^T)^(-1) is {ainv.sherman_morrison(__a , __a )}""" ) def lowerCAmelCase_ ( ) -> None: """simple docstring""" import doctest doctest.testmod() testa()
273
1
from ...processing_utils import ProcessorMixin class _lowerCamelCase ( a_ ): """simple docstring""" UpperCAmelCase_ : Optional[int] ="SpeechT5FeatureExtractor" UpperCAmelCase_ : Tuple ="SpeechT5Tokenizer" def __init__( self , UpperCAmelCase , UpperCAmelCase ) -> Optional[Any]: '''simple docstring''' super().__init__(_A , _A ) def __call__( self , *UpperCAmelCase , **UpperCAmelCase ) -> Optional[Any]: '''simple docstring''' __snake_case : Union[str, Any] = kwargs.pop("audio" , _A ) __snake_case : Tuple = kwargs.pop("text" , _A ) __snake_case : Dict = kwargs.pop("text_target" , _A ) __snake_case : List[Any] = kwargs.pop("audio_target" , _A ) __snake_case : Optional[Any] = kwargs.pop("sampling_rate" , _A ) if audio is not None and text is not None: raise ValueError( "Cannot process both `audio` and `text` inputs. Did you mean `audio_target` or `text_target`?" ) if audio_target is not None and text_target is not None: raise ValueError( "Cannot process both `audio_target` and `text_target` inputs. Did you mean `audio` or `text`?" ) if audio is None and audio_target is None and text is None and text_target is None: raise ValueError( "You need to specify either an `audio`, `audio_target`, `text`, or `text_target` input to process." ) if audio is not None: __snake_case : Tuple = self.feature_extractor(_A , *_A , sampling_rate=_A , **_A ) elif text is not None: __snake_case : Any = self.tokenizer(_A , **_A ) else: __snake_case : List[Any] = None if audio_target is not None: __snake_case : Union[str, Any] = self.feature_extractor(audio_target=_A , *_A , sampling_rate=_A , **_A ) __snake_case : Tuple = targets["input_values"] elif text_target is not None: __snake_case : List[Any] = self.tokenizer(_A , **_A ) __snake_case : List[Any] = targets["input_ids"] else: __snake_case : str = None if inputs is None: return targets if targets is not None: __snake_case : List[str] = labels __snake_case : Optional[int] = targets.get("attention_mask" ) if decoder_attention_mask is not None: __snake_case : List[str] = decoder_attention_mask return inputs def UpperCAmelCase ( self , *UpperCAmelCase , **UpperCAmelCase ) -> Optional[Any]: '''simple docstring''' __snake_case : List[Any] = kwargs.pop("input_values" , _A ) __snake_case : Optional[int] = kwargs.pop("input_ids" , _A ) __snake_case : Optional[int] = kwargs.pop("labels" , _A ) if input_values is not None and input_ids is not None: raise ValueError("Cannot process both `input_values` and `input_ids` inputs." ) if input_values is None and input_ids is None and labels is None: raise ValueError( "You need to specify either an `input_values`, `input_ids`, or `labels` input to be padded." ) if input_values is not None: __snake_case : Optional[int] = self.feature_extractor.pad(_A , *_A , **_A ) elif input_ids is not None: __snake_case : Optional[Any] = self.tokenizer.pad(_A , **_A ) else: __snake_case : List[str] = None if labels is not None: if "input_ids" in labels or (isinstance(_A , _A ) and "input_ids" in labels[0]): __snake_case : Optional[int] = self.tokenizer.pad(_A , **_A ) __snake_case : List[Any] = targets["input_ids"] else: __snake_case : List[Any] = self.feature_extractor.feature_size __snake_case : Optional[int] = self.feature_extractor.num_mel_bins __snake_case : str = self.feature_extractor.pad(_A , *_A , **_A ) __snake_case : Tuple = feature_size_hack __snake_case : Optional[int] = targets["input_values"] else: __snake_case : Optional[int] = None if inputs is None: return targets if targets is not None: __snake_case : Dict = labels __snake_case : Tuple = targets.get("attention_mask" ) if decoder_attention_mask is not None: __snake_case : Any = decoder_attention_mask return inputs def UpperCAmelCase ( self , *UpperCAmelCase , **UpperCAmelCase ) -> Dict: '''simple docstring''' return self.tokenizer.batch_decode(*_A , **_A ) def UpperCAmelCase ( self , *UpperCAmelCase , **UpperCAmelCase ) -> Optional[Any]: '''simple docstring''' return self.tokenizer.decode(*_A , **_A )
326
import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv('''TEST_SAGEMAKER''' , '''False''' ) ) is not True , reason='''Skipping test because should only be run when releasing minor transformers version''' , ) @pytest.mark.usefixtures('''sm_env''' ) @parameterized_class( [ { '''framework''': '''pytorch''', '''script''': '''run_glue.py''', '''model_name_or_path''': '''distilbert-base-cased''', '''instance_type''': '''ml.g4dn.xlarge''', '''results''': {'''train_runtime''': 6_5_0, '''eval_accuracy''': 0.6, '''eval_loss''': 0.9}, }, { '''framework''': '''tensorflow''', '''script''': '''run_tf.py''', '''model_name_or_path''': '''distilbert-base-cased''', '''instance_type''': '''ml.g4dn.xlarge''', '''results''': {'''train_runtime''': 6_0_0, '''eval_accuracy''': 0.3, '''eval_loss''': 0.9}, }, ] ) class A_ (unittest.TestCase ): def _lowercase ( self ): '''simple docstring''' if self.framework == "pytorch": subprocess.run( F"""cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py""".split() , encoding='''utf-8''' , check=_A , ) assert hasattr(self , '''env''' ) def _lowercase ( self , _A=1 ): '''simple docstring''' return HuggingFace( entry_point=self.script , source_dir=self.env.test_path , role=self.env.role , image_uri=self.env.image_uri , base_job_name=F"""{self.env.base_job_name}-single""" , instance_count=_A , instance_type=self.instance_type , debugger_hook_config=_A , hyperparameters={**self.env.hyperparameters, '''model_name_or_path''': self.model_name_or_path} , metric_definitions=self.env.metric_definitions , py_version='''py36''' , ) def _lowercase ( self , _A ): '''simple docstring''' TrainingJobAnalytics(_A ).export_csv(F"""{self.env.test_path}/{job_name}_metrics.csv""" ) def _lowercase ( self ): '''simple docstring''' UpperCAmelCase = self.create_estimator() # run training estimator.fit() # result dataframe UpperCAmelCase = TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe() # extract kpis UpperCAmelCase = list(result_metrics_df[result_metrics_df.metric_name == '''eval_accuracy''']['''value'''] ) UpperCAmelCase = list(result_metrics_df[result_metrics_df.metric_name == '''eval_loss''']['''value'''] ) # get train time from SageMaker job, this includes starting, preprocessing, stopping UpperCAmelCase = ( Session().describe_training_job(estimator.latest_training_job.name ).get('''TrainingTimeInSeconds''' , 9_9_9_9_9_9 ) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results['''eval_accuracy'''] for t in eval_accuracy ) assert all(t <= self.results['''eval_loss'''] for t in eval_loss ) # dump tests result into json file to share in PR with open(F"""{estimator.latest_training_job.name}.json""" , '''w''' ) as outfile: json.dump({'''train_time''': train_runtime, '''eval_accuracy''': eval_accuracy, '''eval_loss''': eval_loss} , _A )
273
0
"""simple docstring""" import copy import os from typing import TYPE_CHECKING, List, Union if TYPE_CHECKING: pass from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase_ = logging.get_logger(__name__) lowerCamelCase_ = { "kakaobrain/align-base": "https://huggingface.co/kakaobrain/align-base/resolve/main/config.json", } class _SCREAMING_SNAKE_CASE( A ): SCREAMING_SNAKE_CASE_ : Dict = '''align_text_model''' def __init__( self ,SCREAMING_SNAKE_CASE__=3_05_22 ,SCREAMING_SNAKE_CASE__=7_68 ,SCREAMING_SNAKE_CASE__=12 ,SCREAMING_SNAKE_CASE__=12 ,SCREAMING_SNAKE_CASE__=30_72 ,SCREAMING_SNAKE_CASE__="gelu" ,SCREAMING_SNAKE_CASE__=0.1 ,SCREAMING_SNAKE_CASE__=0.1 ,SCREAMING_SNAKE_CASE__=5_12 ,SCREAMING_SNAKE_CASE__=2 ,SCREAMING_SNAKE_CASE__=0.0_2 ,SCREAMING_SNAKE_CASE__=1E-12 ,SCREAMING_SNAKE_CASE__=0 ,SCREAMING_SNAKE_CASE__="absolute" ,SCREAMING_SNAKE_CASE__=True ,**SCREAMING_SNAKE_CASE__ ,) -> List[str]: """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE__ ) __SCREAMING_SNAKE_CASE :Tuple = vocab_size __SCREAMING_SNAKE_CASE :Optional[Any] = hidden_size __SCREAMING_SNAKE_CASE :str = num_hidden_layers __SCREAMING_SNAKE_CASE :Dict = num_attention_heads __SCREAMING_SNAKE_CASE :Optional[int] = hidden_act __SCREAMING_SNAKE_CASE :List[str] = intermediate_size __SCREAMING_SNAKE_CASE :str = hidden_dropout_prob __SCREAMING_SNAKE_CASE :Optional[Any] = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE :Any = max_position_embeddings __SCREAMING_SNAKE_CASE :Optional[Any] = type_vocab_size __SCREAMING_SNAKE_CASE :Union[str, Any] = initializer_range __SCREAMING_SNAKE_CASE :Optional[Any] = layer_norm_eps __SCREAMING_SNAKE_CASE :List[str] = position_embedding_type __SCREAMING_SNAKE_CASE :Dict = use_cache __SCREAMING_SNAKE_CASE :int = pad_token_id @classmethod def _UpperCamelCase ( cls ,SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE__ ) __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE :Union[str, Any] = cls.get_config_dict(SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ) # get the text config dict if we are loading from AlignConfig if config_dict.get('''model_type''' ) == "align": __SCREAMING_SNAKE_CASE :int = config_dict['''text_config'''] if "model_type" in config_dict and hasattr(cls ,'''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type ''' f'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ) class _SCREAMING_SNAKE_CASE( A ): SCREAMING_SNAKE_CASE_ : Optional[Any] = '''align_vision_model''' def __init__( self ,SCREAMING_SNAKE_CASE__ = 3 ,SCREAMING_SNAKE_CASE__ = 6_00 ,SCREAMING_SNAKE_CASE__ = 2.0 ,SCREAMING_SNAKE_CASE__ = 3.1 ,SCREAMING_SNAKE_CASE__ = 8 ,SCREAMING_SNAKE_CASE__ = [3, 3, 5, 3, 5, 5, 3] ,SCREAMING_SNAKE_CASE__ = [32, 16, 24, 40, 80, 1_12, 1_92] ,SCREAMING_SNAKE_CASE__ = [16, 24, 40, 80, 1_12, 1_92, 3_20] ,SCREAMING_SNAKE_CASE__ = [] ,SCREAMING_SNAKE_CASE__ = [1, 2, 2, 2, 1, 2, 1] ,SCREAMING_SNAKE_CASE__ = [1, 2, 2, 3, 3, 4, 1] ,SCREAMING_SNAKE_CASE__ = [1, 6, 6, 6, 6, 6, 6] ,SCREAMING_SNAKE_CASE__ = 0.2_5 ,SCREAMING_SNAKE_CASE__ = "swish" ,SCREAMING_SNAKE_CASE__ = 25_60 ,SCREAMING_SNAKE_CASE__ = "mean" ,SCREAMING_SNAKE_CASE__ = 0.0_2 ,SCREAMING_SNAKE_CASE__ = 0.0_0_1 ,SCREAMING_SNAKE_CASE__ = 0.9_9 ,SCREAMING_SNAKE_CASE__ = 0.2 ,**SCREAMING_SNAKE_CASE__ ,) -> str: """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE__ ) __SCREAMING_SNAKE_CASE :Any = num_channels __SCREAMING_SNAKE_CASE :Tuple = image_size __SCREAMING_SNAKE_CASE :Dict = width_coefficient __SCREAMING_SNAKE_CASE :List[Any] = depth_coefficient __SCREAMING_SNAKE_CASE :str = depth_divisor __SCREAMING_SNAKE_CASE :int = kernel_sizes __SCREAMING_SNAKE_CASE :Tuple = in_channels __SCREAMING_SNAKE_CASE :Optional[int] = out_channels __SCREAMING_SNAKE_CASE :int = depthwise_padding __SCREAMING_SNAKE_CASE :Dict = strides __SCREAMING_SNAKE_CASE :Union[str, Any] = num_block_repeats __SCREAMING_SNAKE_CASE :Any = expand_ratios __SCREAMING_SNAKE_CASE :Any = squeeze_expansion_ratio __SCREAMING_SNAKE_CASE :Dict = hidden_act __SCREAMING_SNAKE_CASE :Any = hidden_dim __SCREAMING_SNAKE_CASE :Any = pooling_type __SCREAMING_SNAKE_CASE :List[str] = initializer_range __SCREAMING_SNAKE_CASE :str = batch_norm_eps __SCREAMING_SNAKE_CASE :str = batch_norm_momentum __SCREAMING_SNAKE_CASE :Any = drop_connect_rate __SCREAMING_SNAKE_CASE :Dict = sum(SCREAMING_SNAKE_CASE__ ) * 4 @classmethod def _UpperCamelCase ( cls ,SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE__ ) __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE :Tuple = cls.get_config_dict(SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ) # get the vision config dict if we are loading from AlignConfig if config_dict.get('''model_type''' ) == "align": __SCREAMING_SNAKE_CASE :List[str] = config_dict['''vision_config'''] if "model_type" in config_dict and hasattr(cls ,'''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type ''' f'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ) class _SCREAMING_SNAKE_CASE( A ): SCREAMING_SNAKE_CASE_ : Optional[Any] = '''align''' SCREAMING_SNAKE_CASE_ : int = True def __init__( self ,SCREAMING_SNAKE_CASE__=None ,SCREAMING_SNAKE_CASE__=None ,SCREAMING_SNAKE_CASE__=6_40 ,SCREAMING_SNAKE_CASE__=1.0 ,SCREAMING_SNAKE_CASE__=0.0_2 ,**SCREAMING_SNAKE_CASE__ ,) -> Any: """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE__ ) if text_config is None: __SCREAMING_SNAKE_CASE :str = {} logger.info('''text_config is None. Initializing the AlignTextConfig with default values.''' ) if vision_config is None: __SCREAMING_SNAKE_CASE :int = {} logger.info('''vision_config is None. Initializing the AlignVisionConfig with default values.''' ) __SCREAMING_SNAKE_CASE :Union[str, Any] = AlignTextConfig(**SCREAMING_SNAKE_CASE__ ) __SCREAMING_SNAKE_CASE :Any = AlignVisionConfig(**SCREAMING_SNAKE_CASE__ ) __SCREAMING_SNAKE_CASE :Any = projection_dim __SCREAMING_SNAKE_CASE :str = temperature_init_value __SCREAMING_SNAKE_CASE :List[Any] = initializer_range @classmethod def _UpperCamelCase ( cls ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ) -> Any: """simple docstring""" return cls(text_config=text_config.to_dict() ,vision_config=vision_config.to_dict() ,**SCREAMING_SNAKE_CASE__ ) def _UpperCamelCase ( self ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE :int = copy.deepcopy(self.__dict__ ) __SCREAMING_SNAKE_CASE :str = self.text_config.to_dict() __SCREAMING_SNAKE_CASE :List[Any] = self.vision_config.to_dict() __SCREAMING_SNAKE_CASE :str = self.__class__.model_type return output
239
"""simple docstring""" def __lowerCamelCase ( a_ : Union[str, Any] , a_ : Optional[Any] ) -> Union[str, Any]: return (pointa[0] - pointa[0]) ** 2 + (pointa[1] - pointa[1]) ** 2 def __lowerCamelCase ( a_ : Optional[int] , a_ : Any=0 ) -> Optional[Any]: return sorted(a_ , key=lambda a_ : x[column] ) def __lowerCamelCase ( a_ : Optional[Any] , a_ : Optional[int] , a_ : str=float('''inf''' ) ) -> str: for i in range(points_counts - 1 ): for j in range(i + 1 , a_ ): __SCREAMING_SNAKE_CASE :Dict = euclidean_distance_sqr(points[i] , points[j] ) if current_dis < min_dis: __SCREAMING_SNAKE_CASE :Optional[Any] = current_dis return min_dis def __lowerCamelCase ( a_ : List[Any] , a_ : Any , a_ : Optional[int]=float('''inf''' ) ) -> Optional[Any]: for i in range(min(6 , points_counts - 1 ) , a_ ): for j in range(max(0 , i - 6 ) , a_ ): __SCREAMING_SNAKE_CASE :Dict = euclidean_distance_sqr(points[i] , points[j] ) if current_dis < min_dis: __SCREAMING_SNAKE_CASE :int = current_dis return min_dis def __lowerCamelCase ( a_ : str , a_ : List[Any] , a_ : int ) -> Optional[int]: # base case if points_counts <= 3: return dis_between_closest_pair(a_ , a_ ) # recursion __SCREAMING_SNAKE_CASE :int = points_counts // 2 __SCREAMING_SNAKE_CASE :Dict = closest_pair_of_points_sqr( a_ , points_sorted_on_y[:mid] , a_ ) __SCREAMING_SNAKE_CASE :Any = closest_pair_of_points_sqr( a_ , points_sorted_on_y[mid:] , points_counts - mid ) __SCREAMING_SNAKE_CASE :Union[str, Any] = min(a_ , a_ ) __SCREAMING_SNAKE_CASE :str = [] for point in points_sorted_on_x: if abs(point[0] - points_sorted_on_x[mid][0] ) < closest_pair_dis: cross_strip.append(a_ ) __SCREAMING_SNAKE_CASE :Dict = dis_between_closest_in_strip( a_ , len(a_ ) , a_ ) return min(a_ , a_ ) def __lowerCamelCase ( a_ : int , a_ : Tuple ) -> List[Any]: __SCREAMING_SNAKE_CASE :Union[str, Any] = column_based_sort(a_ , column=0 ) __SCREAMING_SNAKE_CASE :int = column_based_sort(a_ , column=1 ) return ( closest_pair_of_points_sqr( a_ , a_ , a_ ) ) ** 0.5 if __name__ == "__main__": lowerCamelCase_ = [(2, 3), (1_2, 3_0), (4_0, 5_0), (5, 1), (1_2, 1_0), (3, 4)] print("Distance:", closest_pair_of_points(points, len(points)))
239
1
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import PaddingStrategy, logging from .tokenization_realm import RealmTokenizer lowercase_ = logging.get_logger(__name__) lowercase_ = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} lowercase_ = { "vocab_file": { "google/realm-cc-news-pretrained-embedder": ( "https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/vocab.txt" ), "google/realm-cc-news-pretrained-encoder": ( "https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/vocab.txt" ), "google/realm-cc-news-pretrained-scorer": ( "https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/vocab.txt" ), "google/realm-cc-news-pretrained-openqa": ( "https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/vocab.txt" ), "google/realm-orqa-nq-openqa": "https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/vocab.txt", "google/realm-orqa-nq-reader": "https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/vocab.txt", "google/realm-orqa-wq-openqa": "https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/vocab.txt", "google/realm-orqa-wq-reader": "https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/vocab.txt", }, "tokenizer_file": { "google/realm-cc-news-pretrained-embedder": ( "https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/tokenizer.jsont" ), "google/realm-cc-news-pretrained-encoder": ( "https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/tokenizer.json" ), "google/realm-cc-news-pretrained-scorer": ( "https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/tokenizer.json" ), "google/realm-cc-news-pretrained-openqa": ( "https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/tokenizer.json" ), "google/realm-orqa-nq-openqa": ( "https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/tokenizer.json" ), "google/realm-orqa-nq-reader": ( "https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/tokenizer.json" ), "google/realm-orqa-wq-openqa": ( "https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/tokenizer.json" ), "google/realm-orqa-wq-reader": ( "https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/tokenizer.json" ), }, } lowercase_ = { "google/realm-cc-news-pretrained-embedder": 5_1_2, "google/realm-cc-news-pretrained-encoder": 5_1_2, "google/realm-cc-news-pretrained-scorer": 5_1_2, "google/realm-cc-news-pretrained-openqa": 5_1_2, "google/realm-orqa-nq-openqa": 5_1_2, "google/realm-orqa-nq-reader": 5_1_2, "google/realm-orqa-wq-openqa": 5_1_2, "google/realm-orqa-wq-reader": 5_1_2, } lowercase_ = { "google/realm-cc-news-pretrained-embedder": {"do_lower_case": True}, "google/realm-cc-news-pretrained-encoder": {"do_lower_case": True}, "google/realm-cc-news-pretrained-scorer": {"do_lower_case": True}, "google/realm-cc-news-pretrained-openqa": {"do_lower_case": True}, "google/realm-orqa-nq-openqa": {"do_lower_case": True}, "google/realm-orqa-nq-reader": {"do_lower_case": True}, "google/realm-orqa-wq-openqa": {"do_lower_case": True}, "google/realm-orqa-wq-reader": {"do_lower_case": True}, } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : List[str] = VOCAB_FILES_NAMES __UpperCAmelCase : Optional[int] = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase : Optional[int] = PRETRAINED_INIT_CONFIGURATION __UpperCAmelCase : int = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase : Tuple = RealmTokenizer def __init__( self , _a=None , _a=None , _a=True , _a="[UNK]" , _a="[SEP]" , _a="[PAD]" , _a="[CLS]" , _a="[MASK]" , _a=True , _a=None , **_a , ): super().__init__( _a , tokenizer_file=_a , do_lower_case=_a , unk_token=_a , sep_token=_a , pad_token=_a , cls_token=_a , mask_token=_a , tokenize_chinese_chars=_a , strip_accents=_a , **_a , ) __a = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , _a ) != do_lower_case or normalizer_state.get('''strip_accents''' , _a ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , _a ) != tokenize_chinese_chars ): __a = getattr(_a , normalizer_state.pop('''type''' ) ) __a = do_lower_case __a = strip_accents __a = tokenize_chinese_chars __a = normalizer_class(**_a ) __a = do_lower_case def __UpperCAmelCase ( self , _a , **_a ): __a = PaddingStrategy.MAX_LENGTH __a = text __a = kwargs.pop('''text_pair''' , _a ) __a = kwargs.pop('''return_tensors''' , _a ) __a = { '''input_ids''': [], '''attention_mask''': [], '''token_type_ids''': [], } for idx, candidate_text in enumerate(_a ): if batch_text_pair is not None: __a = batch_text_pair[idx] else: __a = None __a = super().__call__(_a , _a , return_tensors=_a , **_a ) __a = encoded_candidates.get('''input_ids''' ) __a = encoded_candidates.get('''attention_mask''' ) __a = encoded_candidates.get('''token_type_ids''' ) if encoded_input_ids is not None: output_data["input_ids"].append(_a ) if encoded_attention_mask is not None: output_data["attention_mask"].append(_a ) if encoded_token_type_ids is not None: output_data["token_type_ids"].append(_a ) __a = {key: item for key, item in output_data.items() if len(_a ) != 0} return BatchEncoding(_a , tensor_type=_a ) def __UpperCAmelCase ( self , _a , _a=None ): __a = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __UpperCAmelCase ( self , _a , _a = 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 __UpperCAmelCase ( self , _a , _a = None ): __a = self._tokenizer.model.save(_a , name=_a ) return tuple(_a )
45
"""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
1
from math import factorial __UpperCAmelCase = {str(d): factorial(d) for d in range(10)} def lowercase__ ( __snake_case : int ): '''simple docstring''' return sum(DIGIT_FACTORIAL[d] for d in str(__snake_case ) ) def lowercase__ ( ): '''simple docstring''' UpperCAmelCase_ : Union[str, Any] = 7 * factorial(9 ) + 1 return sum(i for i in range(3 , __snake_case ) if sum_of_digit_factorial(__snake_case ) == i ) if __name__ == "__main__": print(F'{solution() = }')
145
from __future__ import annotations from collections.abc import Callable __UpperCAmelCase = list[list[float | int]] def lowercase__ ( __snake_case : Matrix , __snake_case : Matrix ): '''simple docstring''' UpperCAmelCase_ : int = len(__snake_case ) UpperCAmelCase_ : Matrix = [[0 for _ in range(size + 1 )] for _ in range(__snake_case )] UpperCAmelCase_ : int UpperCAmelCase_ : int UpperCAmelCase_ : int UpperCAmelCase_ : int UpperCAmelCase_ : int UpperCAmelCase_ : float for row in range(__snake_case ): for col in range(__snake_case ): UpperCAmelCase_ : Dict = matrix[row][col] UpperCAmelCase_ : Union[str, Any] = vector[row][0] UpperCAmelCase_ : Union[str, Any] = 0 UpperCAmelCase_ : Union[str, Any] = 0 while row < size and col < size: # pivoting UpperCAmelCase_ : Optional[Any] = max((abs(augmented[rowa][col] ), rowa) for rowa in range(__snake_case , __snake_case ) )[ 1 ] if augmented[pivot_row][col] == 0: col += 1 continue else: UpperCAmelCase_ , UpperCAmelCase_ : Tuple = augmented[pivot_row], augmented[row] for rowa in range(row + 1 , __snake_case ): UpperCAmelCase_ : Optional[int] = augmented[rowa][col] / augmented[row][col] UpperCAmelCase_ : List[str] = 0 for cola in range(col + 1 , size + 1 ): augmented[rowa][cola] -= augmented[row][cola] * ratio row += 1 col += 1 # back substitution for col in range(1 , __snake_case ): for row in range(__snake_case ): UpperCAmelCase_ : Union[str, Any] = augmented[row][col] / augmented[col][col] for cola in range(__snake_case , size + 1 ): augmented[row][cola] -= augmented[col][cola] * ratio # round to get rid of numbers like 2.000000000000004 return [ [round(augmented[row][size] / augmented[row][row] , 10 )] for row in range(__snake_case ) ] def lowercase__ ( __snake_case : list[int] ): '''simple docstring''' UpperCAmelCase_ : int = len(__snake_case ) UpperCAmelCase_ : Matrix = [[0 for _ in range(__snake_case )] for _ in range(__snake_case )] UpperCAmelCase_ : Matrix = [[0] for _ in range(__snake_case )] UpperCAmelCase_ : Matrix UpperCAmelCase_ : int UpperCAmelCase_ : int UpperCAmelCase_ : int for x_val, y_val in enumerate(__snake_case ): for col in range(__snake_case ): UpperCAmelCase_ : int = (x_val + 1) ** (size - col - 1) UpperCAmelCase_ : int = y_val UpperCAmelCase_ : List[str] = solve(__snake_case , __snake_case ) def interpolated_func(__snake_case : int ) -> int: return sum( round(coeffs[x_val][0] ) * (var ** (size - x_val - 1)) for x_val in range(__snake_case ) ) return interpolated_func def lowercase__ ( __snake_case : int ): '''simple docstring''' return ( 1 - variable + variable**2 - variable**3 + variable**4 - variable**5 + variable**6 - variable**7 + variable**8 - variable**9 + variable**10 ) def lowercase__ ( __snake_case : Callable[[int], int] = question_function , __snake_case : int = 10 ): '''simple docstring''' UpperCAmelCase_ : list[int] = [func(__snake_case ) for x_val in range(1 , order + 1 )] UpperCAmelCase_ : list[Callable[[int], int]] = [ interpolate(data_points[:max_coeff] ) for max_coeff in range(1 , order + 1 ) ] UpperCAmelCase_ : int = 0 UpperCAmelCase_ : Callable[[int], int] UpperCAmelCase_ : int for poly in polynomials: UpperCAmelCase_ : Optional[int] = 1 while func(__snake_case ) == poly(__snake_case ): x_val += 1 ret += poly(__snake_case ) return ret if __name__ == "__main__": print(F'{solution() = }')
145
1
"""simple docstring""" import unittest from .lib import ( Matrix, Vector, axpy, square_zero_matrix, unit_basis_vector, zero_vector, ) class A_ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self :Optional[int] ) -> None: UpperCAmelCase = Vector([1, 2, 3] ) self.assertEqual(x.component(0 ) , 1 ) self.assertEqual(x.component(2 ) , 3 ) UpperCAmelCase = Vector() def UpperCAmelCase__ ( self :Optional[int] ) -> None: UpperCAmelCase = Vector([0, 0, 0, 0, 0, 1] ) self.assertEqual(str(lowercase_ ) , '(0,0,0,0,0,1)' ) def UpperCAmelCase__ ( self :Union[str, Any] ) -> None: UpperCAmelCase = Vector([1, 2, 3, 4] ) self.assertEqual(len(lowercase_ ) , 4 ) def UpperCAmelCase__ ( self :Optional[int] ) -> None: UpperCAmelCase = Vector([1, 2] ) UpperCAmelCase = Vector([1, 2, 3, 4, 5] ) UpperCAmelCase = Vector([0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ) UpperCAmelCase = Vector([1, -1, 1, -1, 2, -3, 4, -5] ) self.assertAlmostEqual(x.euclidean_length() , 2.236 , 3 ) self.assertAlmostEqual(y.euclidean_length() , 7.416 , 3 ) self.assertEqual(z.euclidean_length() , 0 ) self.assertAlmostEqual(w.euclidean_length() , 7.616 , 3 ) def UpperCAmelCase__ ( self :Dict ) -> None: UpperCAmelCase = Vector([1, 2, 3] ) UpperCAmelCase = Vector([1, 1, 1] ) self.assertEqual((x + y).component(0 ) , 2 ) self.assertEqual((x + y).component(1 ) , 3 ) self.assertEqual((x + y).component(2 ) , 4 ) def UpperCAmelCase__ ( self :Tuple ) -> None: UpperCAmelCase = Vector([1, 2, 3] ) UpperCAmelCase = Vector([1, 1, 1] ) self.assertEqual((x - y).component(0 ) , 0 ) self.assertEqual((x - y).component(1 ) , 1 ) self.assertEqual((x - y).component(2 ) , 2 ) def UpperCAmelCase__ ( self :Optional[int] ) -> None: UpperCAmelCase = Vector([1, 2, 3] ) UpperCAmelCase = Vector([2, -1, 4] ) # for test of dot product UpperCAmelCase = Vector([1, -2, -1] ) self.assertEqual(str(x * 3.0 ) , '(3.0,6.0,9.0)' ) self.assertEqual((a * b) , 0 ) def UpperCAmelCase__ ( self :Optional[int] ) -> None: self.assertEqual(str(zero_vector(10 ) ).count('0' ) , 10 ) def UpperCAmelCase__ ( self :List[Any] ) -> None: self.assertEqual(str(unit_basis_vector(3 , 1 ) ) , '(0,1,0)' ) def UpperCAmelCase__ ( self :Dict ) -> None: UpperCAmelCase = Vector([1, 2, 3] ) UpperCAmelCase = Vector([1, 0, 1] ) self.assertEqual(str(axpy(2 , lowercase_ , lowercase_ ) ) , '(3,4,7)' ) def UpperCAmelCase__ ( self :Tuple ) -> None: UpperCAmelCase = Vector([1, 0, 0, 0, 0, 0] ) UpperCAmelCase = x.copy() self.assertEqual(str(lowercase_ ) , str(lowercase_ ) ) def UpperCAmelCase__ ( self :List[str] ) -> None: UpperCAmelCase = Vector([1, 0, 0] ) x.change_component(0 , 0 ) x.change_component(1 , 1 ) self.assertEqual(str(lowercase_ ) , '(0,1,0)' ) def UpperCAmelCase__ ( self :str ) -> None: UpperCAmelCase = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) self.assertEqual('|1,2,3|\n|2,4,5|\n|6,7,8|\n' , str(lowercase_ ) ) def UpperCAmelCase__ ( self :Union[str, Any] ) -> None: UpperCAmelCase = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) UpperCAmelCase = [[-3, -14, -10], [-5, -10, -5], [-2, -1, 0]] for x in range(a.height() ): for y in range(a.width() ): self.assertEqual(minors[x][y] , a.minor(lowercase_ , lowercase_ ) ) def UpperCAmelCase__ ( self :Optional[Any] ) -> None: UpperCAmelCase = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) UpperCAmelCase = [[-3, 14, -10], [5, -10, 5], [-2, 1, 0]] for x in range(a.height() ): for y in range(a.width() ): self.assertEqual(cofactors[x][y] , a.cofactor(lowercase_ , lowercase_ ) ) def UpperCAmelCase__ ( self :Optional[Any] ) -> None: UpperCAmelCase = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) self.assertEqual(-5 , a.determinant() ) def UpperCAmelCase__ ( self :Union[str, Any] ) -> None: UpperCAmelCase = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]] , 3 , 3 ) UpperCAmelCase = Vector([1, 2, 3] ) self.assertEqual('(14,32,50)' , str(a * x ) ) self.assertEqual('|2,4,6|\n|8,10,12|\n|14,16,18|\n' , str(a * 2 ) ) def UpperCAmelCase__ ( self :List[Any] ) -> None: UpperCAmelCase = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) a.change_component(0 , 2 , 5 ) self.assertEqual('|1,2,5|\n|2,4,5|\n|6,7,8|\n' , str(lowercase_ ) ) def UpperCAmelCase__ ( self :int ) -> None: UpperCAmelCase = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) self.assertEqual(7 , a.component(2 , 1 ) , 0.01 ) def UpperCAmelCase__ ( self :Optional[Any] ) -> None: UpperCAmelCase = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) UpperCAmelCase = Matrix([[1, 2, 7], [2, 4, 5], [6, 7, 10]] , 3 , 3 ) self.assertEqual('|2,4,10|\n|4,8,10|\n|12,14,18|\n' , str(a + b ) ) def UpperCAmelCase__ ( self :str ) -> None: UpperCAmelCase = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) UpperCAmelCase = Matrix([[1, 2, 7], [2, 4, 5], [6, 7, 10]] , 3 , 3 ) self.assertEqual('|0,0,-4|\n|0,0,0|\n|0,0,-2|\n' , str(a - b ) ) def UpperCAmelCase__ ( self :Optional[Any] ) -> None: self.assertEqual( '|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n' , str(square_zero_matrix(5 ) ) , ) if __name__ == "__main__": unittest.main()
78
"""simple docstring""" import argparse import os import re import numpy as np import PIL import torch from timm import create_model from torch.optim.lr_scheduler import OneCycleLR from torch.utils.data import DataLoader, Dataset from torchvision.transforms import Compose, RandomResizedCrop, Resize, ToTensor from accelerate import Accelerator def _lowerCAmelCase ( lowercase_ ): UpperCAmelCase = fname.split(os.path.sep )[-1] return re.search(R'^(.*)_\d+\.jpg$' , lowercase_ ).groups()[0] class A_ ( SCREAMING_SNAKE_CASE_ ): """simple docstring""" def __init__( self :List[str] , lowercase_ :Dict , lowercase_ :List[str]=None , lowercase_ :Optional[Any]=None ) -> Optional[int]: UpperCAmelCase = file_names UpperCAmelCase = image_transform UpperCAmelCase = label_to_id def __len__( self :Optional[int] ) -> Optional[Any]: return len(self.file_names ) def __getitem__( self :int , lowercase_ :str ) -> List[str]: UpperCAmelCase = self.file_names[idx] UpperCAmelCase = PIL.Image.open(lowercase_ ) UpperCAmelCase = raw_image.convert('RGB' ) if self.image_transform is not None: UpperCAmelCase = self.image_transform(lowercase_ ) UpperCAmelCase = extract_label(lowercase_ ) if self.label_to_id is not None: UpperCAmelCase = self.label_to_id[label] return {"image": image, "label": label} def _lowerCAmelCase ( lowercase_ , lowercase_ ): # Initialize accelerator if args.with_tracking: UpperCAmelCase = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , log_with='all' , project_dir=args.project_dir ) else: UpperCAmelCase = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs UpperCAmelCase = config['lr'] UpperCAmelCase = int(config['num_epochs'] ) UpperCAmelCase = int(config['seed'] ) UpperCAmelCase = int(config['batch_size'] ) UpperCAmelCase = config['image_size'] if not isinstance(lowercase_ , (list, tuple) ): UpperCAmelCase = (image_size, image_size) # Parse out whether we are saving every epoch or after a certain number of batches if hasattr(args.checkpointing_steps , 'isdigit' ): if args.checkpointing_steps == "epoch": UpperCAmelCase = args.checkpointing_steps elif args.checkpointing_steps.isdigit(): UpperCAmelCase = int(args.checkpointing_steps ) else: raise ValueError( F"""Argument `checkpointing_steps` must be either a number or `epoch`. `{args.checkpointing_steps}` passed.""" ) else: UpperCAmelCase = None # We need to initialize the trackers we use, and also store our configuration if args.with_tracking: UpperCAmelCase = os.path.split(lowercase_ )[-1].split('.' )[0] accelerator.init_trackers(lowercase_ , lowercase_ ) # Grab all the image filenames UpperCAmelCase = [os.path.join(args.data_dir , lowercase_ ) for fname in os.listdir(args.data_dir ) if fname.endswith('.jpg' )] # Build the label correspondences UpperCAmelCase = [extract_label(lowercase_ ) for fname in file_names] UpperCAmelCase = list(set(lowercase_ ) ) id_to_label.sort() UpperCAmelCase = {lbl: i for i, lbl in enumerate(lowercase_ )} # Set the seed before splitting the data. np.random.seed(lowercase_ ) torch.manual_seed(lowercase_ ) torch.cuda.manual_seed_all(lowercase_ ) # Split our filenames between train and validation UpperCAmelCase = np.random.permutation(len(lowercase_ ) ) UpperCAmelCase = int(0.8 * len(lowercase_ ) ) UpperCAmelCase = random_perm[:cut] UpperCAmelCase = random_perm[cut:] # For training we use a simple RandomResizedCrop UpperCAmelCase = Compose([RandomResizedCrop(lowercase_ , scale=(0.5, 1.0) ), ToTensor()] ) UpperCAmelCase = PetsDataset( [file_names[i] for i in train_split] , image_transform=lowercase_ , label_to_id=lowercase_ ) # For evaluation, we use a deterministic Resize UpperCAmelCase = Compose([Resize(lowercase_ ), ToTensor()] ) UpperCAmelCase = PetsDataset([file_names[i] for i in eval_split] , image_transform=lowercase_ , label_to_id=lowercase_ ) # Instantiate dataloaders. UpperCAmelCase = DataLoader(lowercase_ , shuffle=lowercase_ , batch_size=lowercase_ , num_workers=4 ) UpperCAmelCase = DataLoader(lowercase_ , shuffle=lowercase_ , batch_size=lowercase_ , num_workers=4 ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) UpperCAmelCase = create_model('resnet50d' , pretrained=lowercase_ , num_classes=len(lowercase_ ) ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). UpperCAmelCase = model.to(accelerator.device ) # Freezing the base model for param in model.parameters(): UpperCAmelCase = False for param in model.get_classifier().parameters(): UpperCAmelCase = True # We normalize the batches of images to be a bit faster. UpperCAmelCase = torch.tensor(model.default_cfg['mean'] )[None, :, None, None].to(accelerator.device ) UpperCAmelCase = torch.tensor(model.default_cfg['std'] )[None, :, None, None].to(accelerator.device ) # Instantiate optimizer UpperCAmelCase = torch.optim.Adam(params=model.parameters() , lr=lr / 25 ) # Instantiate learning rate scheduler UpperCAmelCase = OneCycleLR(optimizer=lowercase_ , max_lr=lowercase_ , epochs=lowercase_ , steps_per_epoch=len(lowercase_ ) ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = accelerator.prepare( lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ ) # We need to keep track of how many total steps we have iterated over UpperCAmelCase = 0 # We also need to keep track of the starting epoch so files are named properly UpperCAmelCase = 0 # Potentially load in the weights and states from a previous save if args.resume_from_checkpoint: if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "": accelerator.print(F"""Resumed from checkpoint: {args.resume_from_checkpoint}""" ) accelerator.load_state(args.resume_from_checkpoint ) UpperCAmelCase = os.path.basename(args.resume_from_checkpoint ) else: # Get the most recent checkpoint UpperCAmelCase = [f.name for f in os.scandir(os.getcwd() ) if f.is_dir()] dirs.sort(key=os.path.getctime ) UpperCAmelCase = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last # Extract `epoch_{i}` or `step_{i}` UpperCAmelCase = os.path.splitext(lowercase_ )[0] if "epoch" in training_difference: UpperCAmelCase = int(training_difference.replace('epoch_' , '' ) ) + 1 UpperCAmelCase = None else: UpperCAmelCase = int(training_difference.replace('step_' , '' ) ) UpperCAmelCase = resume_step // len(lowercase_ ) resume_step -= starting_epoch * len(lowercase_ ) # Now we train the model for epoch in range(lowercase_ , lowercase_ ): model.train() if args.with_tracking: UpperCAmelCase = 0 if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None: # We need to skip steps until we reach the resumed step UpperCAmelCase = accelerator.skip_first_batches(lowercase_ , lowercase_ ) overall_step += resume_step else: # After the first iteration though, we need to go back to the original dataloader UpperCAmelCase = train_dataloader for batch in active_dataloader: # We could avoid this line since we set the accelerator with `device_placement=True`. UpperCAmelCase = {k: v.to(accelerator.device ) for k, v in batch.items()} UpperCAmelCase = (batch['image'] - mean) / std UpperCAmelCase = model(lowercase_ ) UpperCAmelCase = torch.nn.functional.cross_entropy(lowercase_ , batch['label'] ) # We keep track of the loss at each epoch if args.with_tracking: total_loss += loss.detach().float() accelerator.backward(lowercase_ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 if isinstance(lowercase_ , lowercase_ ): UpperCAmelCase = F"""step_{overall_step}""" if overall_step % checkpointing_steps == 0: if args.output_dir is not None: UpperCAmelCase = os.path.join(args.output_dir , lowercase_ ) accelerator.save_state(lowercase_ ) model.eval() UpperCAmelCase = 0 UpperCAmelCase = 0 for step, batch in enumerate(lowercase_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. UpperCAmelCase = {k: v.to(accelerator.device ) for k, v in batch.items()} UpperCAmelCase = (batch['image'] - mean) / std with torch.no_grad(): UpperCAmelCase = model(lowercase_ ) UpperCAmelCase = outputs.argmax(dim=-1 ) UpperCAmelCase , UpperCAmelCase = accelerator.gather_for_metrics((predictions, batch['label']) ) UpperCAmelCase = predictions == references num_elems += accurate_preds.shape[0] accurate += accurate_preds.long().sum() UpperCAmelCase = accurate.item() / num_elems # Use accelerator.print to print only on the main process. accelerator.print(F"""epoch {epoch}: {100 * eval_metric:.2f}""" ) if args.with_tracking: accelerator.log( { 'accuracy': 100 * eval_metric, 'train_loss': total_loss.item() / len(lowercase_ ), 'epoch': epoch, } , step=lowercase_ , ) if checkpointing_steps == "epoch": UpperCAmelCase = F"""epoch_{epoch}""" if args.output_dir is not None: UpperCAmelCase = os.path.join(args.output_dir , lowercase_ ) accelerator.save_state(lowercase_ ) if args.with_tracking: accelerator.end_training() def _lowerCAmelCase ( ): UpperCAmelCase = argparse.ArgumentParser(description='Simple example of training script.' ) parser.add_argument('--data_dir' , required=lowercase_ , help='The data folder on disk.' ) parser.add_argument('--fp16' , action='store_true' , help='If passed, will use FP16 training.' ) parser.add_argument( '--mixed_precision' , type=lowercase_ , default=lowercase_ , choices=['no', 'fp16', 'bf16', 'fp8'] , help='Whether to use mixed precision. Choose' 'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.' 'and an Nvidia Ampere GPU.' , ) parser.add_argument('--cpu' , action='store_true' , help='If passed, will train on the CPU.' ) parser.add_argument( '--checkpointing_steps' , type=lowercase_ , default=lowercase_ , help='Whether the various states should be saved at the end of every n steps, or \'epoch\' for each epoch.' , ) parser.add_argument( '--output_dir' , type=lowercase_ , default='.' , help='Optional save directory where all checkpoint folders will be stored. Default is the current working directory.' , ) parser.add_argument( '--resume_from_checkpoint' , type=lowercase_ , default=lowercase_ , help='If the training should continue from a checkpoint folder.' , ) parser.add_argument( '--with_tracking' , action='store_true' , help='Whether to load in all available experiment trackers from the environment and use them for logging.' , ) parser.add_argument( '--project_dir' , type=lowercase_ , default='logs' , help='Location on where to store experiment tracking logs` and relevent project information' , ) UpperCAmelCase = parser.parse_args() UpperCAmelCase = {'lr': 3e-2, 'num_epochs': 3, 'seed': 42, 'batch_size': 64, 'image_size': 224} training_function(lowercase_ , lowercase_ ) if __name__ == "__main__": main()
78
1
from __future__ import annotations SCREAMING_SNAKE_CASE : str = 1.6021E-19 # units = C def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , ) -> tuple[str, float]: 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()
364
def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ ) -> int: return int((input_a, input_a).count(1 ) != 0 ) def UpperCamelCase_( ) -> None: assert or_gate(0 , 0 ) == 0 assert or_gate(0 , 1 ) == 1 assert or_gate(1 , 0 ) == 1 assert or_gate(1 , 1 ) == 1 if __name__ == "__main__": print(or_gate(0, 1)) print(or_gate(1, 0)) print(or_gate(0, 0)) print(or_gate(1, 1))
84
0
'''simple docstring''' import torch from transformers import PreTrainedModel, XLMRobertaConfig, XLMRobertaModel class _A ( SCREAMING_SNAKE_CASE_ ): _SCREAMING_SNAKE_CASE : Optional[int] = "M-CLIP" def __init__( self , __UpperCAmelCase=1_024 , __UpperCAmelCase=768 , **__UpperCAmelCase ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : Union[str, Any] = transformerDimSize __UpperCAmelCase : int = imageDimSize super().__init__(**_a ) class _A ( SCREAMING_SNAKE_CASE_ ): _SCREAMING_SNAKE_CASE : Tuple = MCLIPConfig def __init__( self , __UpperCAmelCase , *__UpperCAmelCase , **__UpperCAmelCase ) -> Dict: '''simple docstring''' super().__init__(_a , *_a , **_a ) __UpperCAmelCase : Optional[int] = XLMRobertaModel(_a ) __UpperCAmelCase : List[Any] = torch.nn.Linear( in_features=config.transformerDimensions , out_features=config.numDims ) def __A ( self , __UpperCAmelCase , __UpperCAmelCase ) -> Union[str, Any]: '''simple docstring''' __UpperCAmelCase : Tuple = self.transformer(input_ids=_a , attention_mask=_a )[0] __UpperCAmelCase : int = (embs * attention_mask.unsqueeze(2 )).sum(dim=1 ) / attention_mask.sum(dim=1 )[:, None] return self.LinearTransformation(_a ), embs
254
'''simple docstring''' def a_ ( _lowerCAmelCase ) -> str: if not all(char in '01' for char in bin_string ): raise ValueError('Non-binary value was passed to the function' ) if not bin_string: raise ValueError('Empty string was passed to the function' ) __lowerCamelCase : int = '' while len(_lowerCAmelCase ) % 3 != 0: __lowerCamelCase : str = '0' + bin_string __lowerCamelCase : Union[str, Any] = [ bin_string[index : index + 3] for index in range(len(_lowerCAmelCase ) ) if index % 3 == 0 ] for bin_group in bin_string_in_3_list: __lowerCamelCase : Tuple = 0 for index, val in enumerate(_lowerCAmelCase ): oct_val += int(2 ** (2 - index) * int(_lowerCAmelCase ) ) oct_string += str(_lowerCAmelCase ) return oct_string if __name__ == "__main__": from doctest import testmod testmod()
208
0
"""simple docstring""" import argparse import re import numpy as np import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( SamConfig, SamImageProcessor, SamModel, SamProcessor, SamVisionConfig, ) __lowerCAmelCase : Dict ={ """iou_prediction_head.layers.0""": """iou_prediction_head.proj_in""", """iou_prediction_head.layers.1""": """iou_prediction_head.layers.0""", """iou_prediction_head.layers.2""": """iou_prediction_head.proj_out""", """mask_decoder.output_upscaling.0""": """mask_decoder.upscale_conv1""", """mask_decoder.output_upscaling.1""": """mask_decoder.upscale_layer_norm""", """mask_decoder.output_upscaling.3""": """mask_decoder.upscale_conv2""", """mask_downscaling.0""": """mask_embed.conv1""", """mask_downscaling.1""": """mask_embed.layer_norm1""", """mask_downscaling.3""": """mask_embed.conv2""", """mask_downscaling.4""": """mask_embed.layer_norm2""", """mask_downscaling.6""": """mask_embed.conv3""", """point_embeddings""": """point_embed""", """pe_layer.positional_encoding_gaussian_matrix""": """shared_embedding.positional_embedding""", """image_encoder""": """vision_encoder""", """neck.0""": """neck.conv1""", """neck.1""": """neck.layer_norm1""", """neck.2""": """neck.conv2""", """neck.3""": """neck.layer_norm2""", """patch_embed.proj""": """patch_embed.projection""", """.norm""": """.layer_norm""", """blocks""": """layers""", } def UpperCAmelCase__ ( lowerCAmelCase__ :int ) -> str: '''simple docstring''' lowercase = {} state_dict.pop("""pixel_mean""" , lowerCAmelCase__ ) state_dict.pop("""pixel_std""" , lowerCAmelCase__ ) lowercase = R""".*.output_hypernetworks_mlps.(\d+).layers.(\d+).*""" for key, value in state_dict.items(): for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items(): if key_to_modify in key: lowercase = key.replace(lowerCAmelCase__ , lowerCAmelCase__ ) if re.match(lowerCAmelCase__ , lowerCAmelCase__ ): lowercase = int(re.match(lowerCAmelCase__ , lowerCAmelCase__ ).group(2 ) ) if layer_nb == 0: lowercase = key.replace("""layers.0""" , """proj_in""" ) elif layer_nb == 1: lowercase = key.replace("""layers.1""" , """layers.0""" ) elif layer_nb == 2: lowercase = key.replace("""layers.2""" , """proj_out""" ) lowercase = value lowercase = model_state_dict[ """prompt_encoder.shared_embedding.positional_embedding""" ] return model_state_dict def UpperCAmelCase__ ( lowerCAmelCase__ :Dict , lowerCAmelCase__ :int , lowerCAmelCase__ :Any , lowerCAmelCase__ :Optional[int]="ybelkada/segment-anything" ) -> List[Any]: '''simple docstring''' lowercase = hf_hub_download(lowerCAmelCase__ , f'checkpoints/{model_name}.pth' ) if "sam_vit_b" in model_name: lowercase = SamConfig() elif "sam_vit_l" in model_name: lowercase = SamVisionConfig( hidden_size=1_0_2_4 , num_hidden_layers=2_4 , num_attention_heads=1_6 , global_attn_indexes=[5, 1_1, 1_7, 2_3] , ) lowercase = SamConfig( vision_config=lowerCAmelCase__ , ) elif "sam_vit_h" in model_name: lowercase = SamVisionConfig( hidden_size=1_2_8_0 , num_hidden_layers=3_2 , num_attention_heads=1_6 , global_attn_indexes=[7, 1_5, 2_3, 3_1] , ) lowercase = SamConfig( vision_config=lowerCAmelCase__ , ) lowercase = torch.load(lowerCAmelCase__ , map_location="""cpu""" ) lowercase = replace_keys(lowerCAmelCase__ ) lowercase = SamImageProcessor() lowercase = SamProcessor(image_processor=lowerCAmelCase__ ) lowercase = SamModel(lowerCAmelCase__ ) hf_model.load_state_dict(lowerCAmelCase__ ) lowercase = hf_model.to("""cuda""" ) lowercase = """https://huggingface.co/ybelkada/segment-anything/resolve/main/assets/car.png""" lowercase = Image.open(requests.get(lowerCAmelCase__ , stream=lowerCAmelCase__ ).raw ).convert("""RGB""" ) lowercase = [[[4_0_0, 6_5_0]]] lowercase = [[1]] lowercase = processor(images=np.array(lowerCAmelCase__ ) , return_tensors="""pt""" ).to("""cuda""" ) with torch.no_grad(): lowercase = hf_model(**lowerCAmelCase__ ) lowercase = output.iou_scores.squeeze() if model_name == "sam_vit_h_4b8939": assert scores[-1].item() == 0.579_890_251_159_668 lowercase = processor( images=np.array(lowerCAmelCase__ ) , input_points=lowerCAmelCase__ , input_labels=lowerCAmelCase__ , return_tensors="""pt""" ).to("""cuda""" ) with torch.no_grad(): lowercase = hf_model(**lowerCAmelCase__ ) lowercase = output.iou_scores.squeeze() assert scores[-1].item() == 0.9_712_603_092_193_604 lowercase = ((7_5, 2_7_5, 1_7_2_5, 8_5_0),) lowercase = processor(images=np.array(lowerCAmelCase__ ) , input_boxes=lowerCAmelCase__ , return_tensors="""pt""" ).to("""cuda""" ) with torch.no_grad(): lowercase = hf_model(**lowerCAmelCase__ ) lowercase = output.iou_scores.squeeze() assert scores[-1].item() == 0.8_686_015_605_926_514 # Test with 2 points and 1 image. lowercase = [[[4_0_0, 6_5_0], [8_0_0, 6_5_0]]] lowercase = [[1, 1]] lowercase = processor( images=np.array(lowerCAmelCase__ ) , input_points=lowerCAmelCase__ , input_labels=lowerCAmelCase__ , return_tensors="""pt""" ).to("""cuda""" ) with torch.no_grad(): lowercase = hf_model(**lowerCAmelCase__ ) lowercase = output.iou_scores.squeeze() assert scores[-1].item() == 0.9_936_047_792_434_692 if __name__ == "__main__": __lowerCAmelCase : Any =argparse.ArgumentParser() __lowerCAmelCase : List[Any] =["""sam_vit_b_01ec64""", """sam_vit_h_4b8939""", """sam_vit_l_0b3195"""] parser.add_argument( """--model_name""", default="""sam_vit_h_4b8939""", choices=choices, type=str, help="""Path to hf config.json of model to convert""", ) parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Whether to push the model and processor to the hub after converting""", ) parser.add_argument( """--model_hub_id""", default="""ybelkada/segment-anything""", choices=choices, type=str, help="""Path to hf config.json of model to convert""", ) __lowerCAmelCase : Dict =parser.parse_args() convert_sam_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub, args.model_hub_id)
32
"""simple docstring""" def UpperCAmelCase__ ( lowerCAmelCase__ :int ) -> int: '''simple docstring''' if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise TypeError("""only integers accepted as input""" ) else: lowercase = str(abs(lowerCAmelCase__ ) ) lowercase = [list(lowerCAmelCase__ ) for char in range(len(lowerCAmelCase__ ) )] for index in range(len(lowerCAmelCase__ ) ): num_transpositions[index].pop(lowerCAmelCase__ ) return max( int("""""".join(list(lowerCAmelCase__ ) ) ) for transposition in num_transpositions ) if __name__ == "__main__": __import__("""doctest""").testmod()
32
1
"""simple docstring""" import argparse from collections import defaultdict import yaml lowerCAmelCase = """docs/source/en/_toctree.yml""" def lowerCAmelCase_ ( snake_case_ : Union[str, Any] ) ->Optional[Any]: lowerCamelCase__ : Optional[int] =defaultdict(snake_case_ ) for doc in model_doc: counts[doc["local"]] += 1 lowerCamelCase__ : Tuple =[key for key, value in counts.items() if value > 1] lowerCamelCase__ : Dict =[] for duplicate_key in duplicates: lowerCamelCase__ : List[str] =list({doc['title'] for doc in model_doc if doc['local'] == duplicate_key} ) if len(snake_case_ ) > 1: raise ValueError( f"""{duplicate_key} is present several times in the documentation table of content at """ '`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the ' 'others.' ) # Only add this once new_doc.append({'local': duplicate_key, 'title': titles[0]} ) # Add none duplicate-keys new_doc.extend([doc for doc in model_doc if counts[doc['local']] == 1] ) # Sort return sorted(snake_case_ , key=lambda snake_case_ : s["title"].lower() ) def lowerCAmelCase_ ( snake_case_ : List[Any]=False ) ->List[str]: with open(snake_case_ , encoding='utf-8' ) as f: lowerCamelCase__ : Tuple =yaml.safe_load(f.read() ) # Get to the API doc lowerCamelCase__ : int =0 while content[api_idx]["title"] != "API": api_idx += 1 lowerCamelCase__ : Any =content[api_idx]['sections'] # Then to the model doc lowerCamelCase__ : Optional[Any] =0 while api_doc[model_idx]["title"] != "Models": model_idx += 1 lowerCamelCase__ : Tuple =api_doc[model_idx]['sections'] lowerCamelCase__ : Optional[Any] =[(idx, section) for idx, section in enumerate(snake_case_ ) if 'sections' in section] lowerCamelCase__ : Optional[int] =False for idx, modality_doc in modalities_docs: lowerCamelCase__ : Union[str, Any] =modality_doc['sections'] lowerCamelCase__ : Union[str, Any] =clean_model_doc_toc(snake_case_ ) if old_modality_doc != new_modality_doc: lowerCamelCase__ : Union[str, Any] =True if overwrite: lowerCamelCase__ : Any =new_modality_doc if diff: if overwrite: lowerCamelCase__ : Optional[Any] =model_doc lowerCamelCase__ : Optional[Any] =api_doc with open(snake_case_ , 'w' , encoding='utf-8' ) as f: f.write(yaml.dump(snake_case_ , allow_unicode=snake_case_ ) ) else: raise ValueError( 'The model doc part of the table of content is not properly sorted, run `make style` to fix this.' ) if __name__ == "__main__": lowerCAmelCase = argparse.ArgumentParser() parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""") lowerCAmelCase = parser.parse_args() check_model_doc(args.fix_and_overwrite)
126
"""simple docstring""" import unittest from transformers import MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING, AutoTokenizer, is_vision_available from transformers.pipelines import pipeline from transformers.pipelines.document_question_answering import apply_tesseract from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_detectrona, require_pytesseract, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image from transformers.image_utils import load_image else: class A_ : """simple docstring""" @staticmethod def UpperCAmelCase__ ( *lowerCamelCase_ :Optional[int] , **lowerCamelCase_ :Optional[Any] ): """simple docstring""" pass def lowerCAmelCase_ ( snake_case_ : List[str] ) ->str: return None # This is a pinned image from a specific revision of a document question answering space, hosted by HuggingFace, # so we can expect it to be available. lowerCAmelCase = ( """https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png""" ) @is_pipeline_test @require_torch @require_vision class A_ ( unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE_ = MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING @require_pytesseract @require_vision def UpperCAmelCase__ ( self :Optional[Any] , lowerCamelCase_ :Union[str, Any] , lowerCamelCase_ :Tuple , lowerCamelCase_ :int ): """simple docstring""" lowerCamelCase__ : Optional[int] =pipeline( 'document-question-answering' , model=lowerCamelCase_ , tokenizer=lowerCamelCase_ , image_processor=lowerCamelCase_ ) lowerCamelCase__ : Tuple =INVOICE_URL lowerCamelCase__ : Optional[Any] =list(zip(*apply_tesseract(load_image(lowerCamelCase_ ) , lowerCamelCase_ , '' ) ) ) lowerCamelCase__ : Optional[Any] ='What is the placebo?' lowerCamelCase__ : List[str] =[ { 'image': load_image(lowerCamelCase_ ), 'question': question, }, { 'image': image, 'question': question, }, { 'image': image, 'question': question, 'word_boxes': word_boxes, }, ] return dqa_pipeline, examples def UpperCAmelCase__ ( self :int , lowerCamelCase_ :Tuple , lowerCamelCase_ :Tuple ): """simple docstring""" lowerCamelCase__ : List[str] =dqa_pipeline(lowerCamelCase_ , top_k=2 ) self.assertEqual( lowerCamelCase_ , [ [ {'score': ANY(lowerCamelCase_ ), 'answer': ANY(lowerCamelCase_ ), 'start': ANY(lowerCamelCase_ ), 'end': ANY(lowerCamelCase_ )}, {'score': ANY(lowerCamelCase_ ), 'answer': ANY(lowerCamelCase_ ), 'start': ANY(lowerCamelCase_ ), 'end': ANY(lowerCamelCase_ )}, ] ] * 3 , ) @require_torch @require_detectrona @require_pytesseract def UpperCAmelCase__ ( self :Any ): """simple docstring""" lowerCamelCase__ : str =pipeline('document-question-answering' , model='hf-internal-testing/tiny-random-layoutlmv2' ) lowerCamelCase__ : Any =INVOICE_URL lowerCamelCase__ : Union[str, Any] ='How many cats are there?' lowerCamelCase__ : List[Any] =[ {'score': 0.00_01, 'answer': 'oy 2312/2019', 'start': 38, 'end': 39}, {'score': 0.00_01, 'answer': 'oy 2312/2019 DUE', 'start': 38, 'end': 40}, ] lowerCamelCase__ : Dict =dqa_pipeline(image=lowerCamelCase_ , question=lowerCamelCase_ , top_k=2 ) self.assertEqual(nested_simplify(lowerCamelCase_ , decimals=4 ) , lowerCamelCase_ ) lowerCamelCase__ : int =dqa_pipeline({'image': image, 'question': question} , top_k=2 ) self.assertEqual(nested_simplify(lowerCamelCase_ , decimals=4 ) , lowerCamelCase_ ) # This image does not detect ANY text in it, meaning layoutlmv2 should fail. # Empty answer probably lowerCamelCase__ : str ='./tests/fixtures/tests_samples/COCO/000000039769.png' lowerCamelCase__ : Union[str, Any] =dqa_pipeline(image=lowerCamelCase_ , question=lowerCamelCase_ , top_k=2 ) self.assertEqual(lowerCamelCase_ , [] ) # We can optionnally pass directly the words and bounding boxes lowerCamelCase__ : str ='./tests/fixtures/tests_samples/COCO/000000039769.png' lowerCamelCase__ : Optional[Any] =[] lowerCamelCase__ : Tuple =[] lowerCamelCase__ : Tuple =dqa_pipeline(image=lowerCamelCase_ , question=lowerCamelCase_ , words=lowerCamelCase_ , boxes=lowerCamelCase_ , top_k=2 ) self.assertEqual(lowerCamelCase_ , [] ) @slow @require_torch @require_detectrona @require_pytesseract def UpperCAmelCase__ ( self :Any ): """simple docstring""" lowerCamelCase__ : int =pipeline( 'document-question-answering' , model='tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa' , revision='9977165' , ) lowerCamelCase__ : Dict =INVOICE_URL lowerCamelCase__ : int ='What is the invoice number?' lowerCamelCase__ : Union[str, Any] =dqa_pipeline(image=lowerCamelCase_ , question=lowerCamelCase_ , top_k=2 ) self.assertEqual( nested_simplify(lowerCamelCase_ , decimals=4 ) , [ {'score': 0.99_44, 'answer': 'us-001', 'start': 16, 'end': 16}, {'score': 0.00_09, 'answer': 'us-001', 'start': 16, 'end': 16}, ] , ) lowerCamelCase__ : Optional[int] =dqa_pipeline({'image': image, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(lowerCamelCase_ , decimals=4 ) , [ {'score': 0.99_44, 'answer': 'us-001', 'start': 16, 'end': 16}, {'score': 0.00_09, 'answer': 'us-001', 'start': 16, 'end': 16}, ] , ) lowerCamelCase__ : List[str] =dqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] , top_k=2 ) self.assertEqual( nested_simplify(lowerCamelCase_ , decimals=4 ) , [ [ {'score': 0.99_44, 'answer': 'us-001', 'start': 16, 'end': 16}, {'score': 0.00_09, 'answer': 'us-001', 'start': 16, 'end': 16}, ], ] * 2 , ) @slow @require_torch @require_detectrona @require_pytesseract def UpperCAmelCase__ ( self :List[str] ): """simple docstring""" lowerCamelCase__ : int =pipeline( 'document-question-answering' , model='tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa' , revision='9977165' , max_seq_len=50 , ) lowerCamelCase__ : Tuple =INVOICE_URL lowerCamelCase__ : Any ='What is the invoice number?' lowerCamelCase__ : Union[str, Any] =dqa_pipeline(image=lowerCamelCase_ , question=lowerCamelCase_ , top_k=2 ) self.assertEqual( nested_simplify(lowerCamelCase_ , decimals=4 ) , [ {'score': 0.99_74, 'answer': '1110212019', 'start': 23, 'end': 23}, {'score': 0.99_48, 'answer': 'us-001', 'start': 16, 'end': 16}, ] , ) lowerCamelCase__ : List[Any] =dqa_pipeline({'image': image, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(lowerCamelCase_ , decimals=4 ) , [ {'score': 0.99_74, 'answer': '1110212019', 'start': 23, 'end': 23}, {'score': 0.99_48, 'answer': 'us-001', 'start': 16, 'end': 16}, ] , ) lowerCamelCase__ : List[Any] =dqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] , top_k=2 ) self.assertEqual( nested_simplify(lowerCamelCase_ , decimals=4 ) , [ [ {'score': 0.99_74, 'answer': '1110212019', 'start': 23, 'end': 23}, {'score': 0.99_48, 'answer': 'us-001', 'start': 16, 'end': 16}, ] ] * 2 , ) @slow @require_torch @require_pytesseract @require_vision def UpperCAmelCase__ ( self :Dict ): """simple docstring""" lowerCamelCase__ : int =AutoTokenizer.from_pretrained( 'impira/layoutlm-document-qa' , revision='3dc6de3' , add_prefix_space=lowerCamelCase_ ) lowerCamelCase__ : Optional[Any] =pipeline( 'document-question-answering' , model='impira/layoutlm-document-qa' , tokenizer=lowerCamelCase_ , revision='3dc6de3' , ) lowerCamelCase__ : int =INVOICE_URL lowerCamelCase__ : Tuple ='What is the invoice number?' lowerCamelCase__ : Optional[Any] =dqa_pipeline(image=lowerCamelCase_ , question=lowerCamelCase_ , top_k=2 ) self.assertEqual( nested_simplify(lowerCamelCase_ , decimals=4 ) , [ {'score': 0.42_51, 'answer': 'us-001', 'start': 16, 'end': 16}, {'score': 0.08_19, 'answer': '1110212019', 'start': 23, 'end': 23}, ] , ) lowerCamelCase__ : Optional[int] =dqa_pipeline({'image': image, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(lowerCamelCase_ , decimals=4 ) , [ {'score': 0.42_51, 'answer': 'us-001', 'start': 16, 'end': 16}, {'score': 0.08_19, 'answer': '1110212019', 'start': 23, 'end': 23}, ] , ) lowerCamelCase__ : Optional[Any] =dqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] , top_k=2 ) self.assertEqual( nested_simplify(lowerCamelCase_ , decimals=4 ) , [ [ {'score': 0.42_51, 'answer': 'us-001', 'start': 16, 'end': 16}, {'score': 0.08_19, 'answer': '1110212019', 'start': 23, 'end': 23}, ] ] * 2 , ) lowerCamelCase__ : Tuple =list(zip(*apply_tesseract(load_image(lowerCamelCase_ ) , lowerCamelCase_ , '' ) ) ) # This model should also work if `image` is set to None lowerCamelCase__ : Optional[int] =dqa_pipeline({'image': None, 'word_boxes': word_boxes, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(lowerCamelCase_ , decimals=4 ) , [ {'score': 0.42_51, 'answer': 'us-001', 'start': 16, 'end': 16}, {'score': 0.08_19, 'answer': '1110212019', 'start': 23, 'end': 23}, ] , ) @slow @require_torch @require_pytesseract @require_vision def UpperCAmelCase__ ( self :Optional[Any] ): """simple docstring""" lowerCamelCase__ : Optional[Any] =AutoTokenizer.from_pretrained( 'impira/layoutlm-document-qa' , revision='3dc6de3' , add_prefix_space=lowerCamelCase_ ) lowerCamelCase__ : Any =pipeline( 'document-question-answering' , model='impira/layoutlm-document-qa' , tokenizer=lowerCamelCase_ , revision='3dc6de3' , max_seq_len=50 , ) lowerCamelCase__ : Dict =INVOICE_URL lowerCamelCase__ : Optional[Any] ='What is the invoice number?' lowerCamelCase__ : Tuple =dqa_pipeline(image=lowerCamelCase_ , question=lowerCamelCase_ , top_k=2 ) self.assertEqual( nested_simplify(lowerCamelCase_ , decimals=4 ) , [ {'score': 0.99_99, 'answer': 'us-001', 'start': 16, 'end': 16}, {'score': 0.99_98, 'answer': 'us-001', 'start': 16, 'end': 16}, ] , ) lowerCamelCase__ : Tuple =dqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] , top_k=2 ) self.assertEqual( nested_simplify(lowerCamelCase_ , decimals=4 ) , [ [ {'score': 0.99_99, 'answer': 'us-001', 'start': 16, 'end': 16}, {'score': 0.99_98, 'answer': 'us-001', 'start': 16, 'end': 16}, ] ] * 2 , ) lowerCamelCase__ : str =list(zip(*apply_tesseract(load_image(lowerCamelCase_ ) , lowerCamelCase_ , '' ) ) ) # This model should also work if `image` is set to None lowerCamelCase__ : Union[str, Any] =dqa_pipeline({'image': None, 'word_boxes': word_boxes, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(lowerCamelCase_ , decimals=4 ) , [ {'score': 0.99_99, 'answer': 'us-001', 'start': 16, 'end': 16}, {'score': 0.99_98, 'answer': 'us-001', 'start': 16, 'end': 16}, ] , ) @slow @require_torch def UpperCAmelCase__ ( self :str ): """simple docstring""" lowerCamelCase__ : List[Any] =pipeline( 'document-question-answering' , model='naver-clova-ix/donut-base-finetuned-docvqa' , tokenizer=AutoTokenizer.from_pretrained('naver-clova-ix/donut-base-finetuned-docvqa' ) , feature_extractor='naver-clova-ix/donut-base-finetuned-docvqa' , ) lowerCamelCase__ : Union[str, Any] =INVOICE_URL lowerCamelCase__ : Union[str, Any] ='What is the invoice number?' lowerCamelCase__ : Union[str, Any] =dqa_pipeline(image=lowerCamelCase_ , question=lowerCamelCase_ , top_k=2 ) self.assertEqual(nested_simplify(lowerCamelCase_ , decimals=4 ) , [{'answer': 'us-001'}] ) @require_tf @unittest.skip('Document question answering not implemented in TF' ) def UpperCAmelCase__ ( self :str ): """simple docstring""" pass
126
1
import argparse import os import shutil from pathlib import Path import onnx import torch from packaging import version from torch.onnx import export from diffusers import OnnxRuntimeModel, OnnxStableDiffusionPipeline, StableDiffusionPipeline __a = version.parse(version.parse(torch.__version__).base_version) < version.parse('''1.11''') def __lowercase ( _UpperCamelCase, _UpperCamelCase, _UpperCamelCase, _UpperCamelCase, _UpperCamelCase, _UpperCamelCase, _UpperCamelCase, _UpperCamelCase=False, ) ->Tuple: """simple docstring""" output_path.parent.mkdir(parents=_UpperCamelCase, exist_ok=_UpperCamelCase ) # PyTorch deprecated the `enable_onnx_checker` and `use_external_data_format` arguments in v1.11, # so we check the torch version for backwards compatibility if is_torch_less_than_1_11: export( _UpperCamelCase, _UpperCamelCase, f=output_path.as_posix(), input_names=_UpperCamelCase, output_names=_UpperCamelCase, dynamic_axes=_UpperCamelCase, do_constant_folding=_UpperCamelCase, use_external_data_format=_UpperCamelCase, enable_onnx_checker=_UpperCamelCase, opset_version=_UpperCamelCase, ) else: export( _UpperCamelCase, _UpperCamelCase, f=output_path.as_posix(), input_names=_UpperCamelCase, output_names=_UpperCamelCase, dynamic_axes=_UpperCamelCase, do_constant_folding=_UpperCamelCase, opset_version=_UpperCamelCase, ) @torch.no_grad() def __lowercase ( _UpperCamelCase, _UpperCamelCase, _UpperCamelCase, _UpperCamelCase = False ) ->List[str]: """simple docstring""" lowercase : Union[str, Any] = torch.floataa if fpaa else torch.floataa if fpaa and torch.cuda.is_available(): lowercase : Tuple = '''cuda''' elif fpaa and not torch.cuda.is_available(): raise ValueError('''`float16` model export is only supported on GPUs with CUDA''' ) else: lowercase : int = '''cpu''' lowercase : int = StableDiffusionPipeline.from_pretrained(_UpperCamelCase, torch_dtype=_UpperCamelCase ).to(_UpperCamelCase ) lowercase : List[str] = Path(_UpperCamelCase ) # TEXT ENCODER lowercase : str = pipeline.text_encoder.config.max_position_embeddings lowercase : List[str] = pipeline.text_encoder.config.hidden_size lowercase : Tuple = pipeline.tokenizer( '''A sample prompt''', padding='''max_length''', max_length=pipeline.tokenizer.model_max_length, truncation=_UpperCamelCase, return_tensors='''pt''', ) onnx_export( pipeline.text_encoder, model_args=(text_input.input_ids.to(device=_UpperCamelCase, dtype=torch.intaa )), output_path=output_path / '''text_encoder''' / '''model.onnx''', ordered_input_names=['''input_ids'''], output_names=['''last_hidden_state''', '''pooler_output'''], dynamic_axes={ '''input_ids''': {0: '''batch''', 1: '''sequence'''}, }, opset=_UpperCamelCase, ) del pipeline.text_encoder # UNET lowercase : Any = pipeline.unet.config.in_channels lowercase : Union[str, Any] = pipeline.unet.config.sample_size lowercase : Optional[Any] = output_path / '''unet''' / '''model.onnx''' onnx_export( pipeline.unet, model_args=( torch.randn(2, _UpperCamelCase, _UpperCamelCase, _UpperCamelCase ).to(device=_UpperCamelCase, dtype=_UpperCamelCase ), torch.randn(2 ).to(device=_UpperCamelCase, dtype=_UpperCamelCase ), torch.randn(2, _UpperCamelCase, _UpperCamelCase ).to(device=_UpperCamelCase, dtype=_UpperCamelCase ), False, ), output_path=_UpperCamelCase, ordered_input_names=['''sample''', '''timestep''', '''encoder_hidden_states''', '''return_dict'''], output_names=['''out_sample'''], dynamic_axes={ '''sample''': {0: '''batch''', 1: '''channels''', 2: '''height''', 3: '''width'''}, '''timestep''': {0: '''batch'''}, '''encoder_hidden_states''': {0: '''batch''', 1: '''sequence'''}, }, opset=_UpperCamelCase, use_external_data_format=_UpperCamelCase, ) lowercase : str = str(unet_path.absolute().as_posix() ) lowercase : Optional[int] = os.path.dirname(_UpperCamelCase ) lowercase : List[Any] = onnx.load(_UpperCamelCase ) # clean up existing tensor files shutil.rmtree(_UpperCamelCase ) os.mkdir(_UpperCamelCase ) # collate external tensor files into one onnx.save_model( _UpperCamelCase, _UpperCamelCase, save_as_external_data=_UpperCamelCase, all_tensors_to_one_file=_UpperCamelCase, location='''weights.pb''', convert_attribute=_UpperCamelCase, ) del pipeline.unet # VAE ENCODER lowercase : Optional[Any] = pipeline.vae lowercase : Any = vae_encoder.config.in_channels lowercase : Any = vae_encoder.config.sample_size # need to get the raw tensor output (sample) from the encoder lowercase : str = lambda _UpperCamelCase, _UpperCamelCase : vae_encoder.encode(_UpperCamelCase, _UpperCamelCase )[0].sample() onnx_export( _UpperCamelCase, model_args=( torch.randn(1, _UpperCamelCase, _UpperCamelCase, _UpperCamelCase ).to(device=_UpperCamelCase, dtype=_UpperCamelCase ), False, ), output_path=output_path / '''vae_encoder''' / '''model.onnx''', ordered_input_names=['''sample''', '''return_dict'''], output_names=['''latent_sample'''], dynamic_axes={ '''sample''': {0: '''batch''', 1: '''channels''', 2: '''height''', 3: '''width'''}, }, opset=_UpperCamelCase, ) # VAE DECODER lowercase : Union[str, Any] = pipeline.vae lowercase : str = vae_decoder.config.latent_channels lowercase : List[str] = vae_decoder.config.out_channels # forward only through the decoder part lowercase : List[str] = vae_encoder.decode onnx_export( _UpperCamelCase, model_args=( torch.randn(1, _UpperCamelCase, _UpperCamelCase, _UpperCamelCase ).to(device=_UpperCamelCase, dtype=_UpperCamelCase ), False, ), output_path=output_path / '''vae_decoder''' / '''model.onnx''', ordered_input_names=['''latent_sample''', '''return_dict'''], output_names=['''sample'''], dynamic_axes={ '''latent_sample''': {0: '''batch''', 1: '''channels''', 2: '''height''', 3: '''width'''}, }, opset=_UpperCamelCase, ) del pipeline.vae # SAFETY CHECKER if pipeline.safety_checker is not None: lowercase : int = pipeline.safety_checker lowercase : Optional[int] = safety_checker.config.vision_config.num_channels lowercase : Any = safety_checker.config.vision_config.image_size lowercase : str = safety_checker.forward_onnx onnx_export( pipeline.safety_checker, model_args=( torch.randn( 1, _UpperCamelCase, _UpperCamelCase, _UpperCamelCase, ).to(device=_UpperCamelCase, dtype=_UpperCamelCase ), torch.randn(1, _UpperCamelCase, _UpperCamelCase, _UpperCamelCase ).to(device=_UpperCamelCase, dtype=_UpperCamelCase ), ), output_path=output_path / '''safety_checker''' / '''model.onnx''', ordered_input_names=['''clip_input''', '''images'''], output_names=['''out_images''', '''has_nsfw_concepts'''], dynamic_axes={ '''clip_input''': {0: '''batch''', 1: '''channels''', 2: '''height''', 3: '''width'''}, '''images''': {0: '''batch''', 1: '''height''', 2: '''width''', 3: '''channels'''}, }, opset=_UpperCamelCase, ) del pipeline.safety_checker lowercase : Dict = OnnxRuntimeModel.from_pretrained(output_path / '''safety_checker''' ) lowercase : Tuple = pipeline.feature_extractor else: lowercase : Optional[Any] = None lowercase : Union[str, Any] = None lowercase : Tuple = OnnxStableDiffusionPipeline( vae_encoder=OnnxRuntimeModel.from_pretrained(output_path / '''vae_encoder''' ), vae_decoder=OnnxRuntimeModel.from_pretrained(output_path / '''vae_decoder''' ), text_encoder=OnnxRuntimeModel.from_pretrained(output_path / '''text_encoder''' ), tokenizer=pipeline.tokenizer, unet=OnnxRuntimeModel.from_pretrained(output_path / '''unet''' ), scheduler=pipeline.scheduler, safety_checker=_UpperCamelCase, feature_extractor=_UpperCamelCase, requires_safety_checker=safety_checker is not None, ) onnx_pipeline.save_pretrained(_UpperCamelCase ) print('''ONNX pipeline saved to''', _UpperCamelCase ) del pipeline del onnx_pipeline lowercase : Any = OnnxStableDiffusionPipeline.from_pretrained(_UpperCamelCase, provider='''CPUExecutionProvider''' ) print('''ONNX pipeline is loadable''' ) if __name__ == "__main__": __a = argparse.ArgumentParser() parser.add_argument( '''--model_path''', type=str, required=True, help='''Path to the `diffusers` checkpoint to convert (either a local directory or on the Hub).''', ) parser.add_argument('''--output_path''', type=str, required=True, help='''Path to the output model.''') parser.add_argument( '''--opset''', default=14, type=int, help='''The version of the ONNX operator set to use.''', ) parser.add_argument('''--fp16''', action='''store_true''', default=False, help='''Export the models in `float16` mode''') __a = parser.parse_args() convert_models(args.model_path, args.output_path, args.opset, args.fpaa)
173
def __lowercase ( _UpperCamelCase = 50 ) ->int: """simple docstring""" lowercase : str = [[0] * 3 for _ in range(length + 1 )] for row_length in range(length + 1 ): for tile_length in range(2, 5 ): for tile_start in range(row_length - tile_length + 1 ): different_colour_ways_number[row_length][tile_length - 2] += ( different_colour_ways_number[row_length - tile_start - tile_length][ tile_length - 2 ] + 1 ) return sum(different_colour_ways_number[length] ) if __name__ == "__main__": print(F'''{solution() = }''')
173
1
"""simple docstring""" from math import sqrt def _A ( UpperCamelCase_ : int) -> int: '''simple docstring''' __lowercase = 0 for i in range(1, int(sqrt(UpperCamelCase_) + 1)): if n % i == 0 and i != sqrt(UpperCamelCase_): total += i + n // i elif i == sqrt(UpperCamelCase_): total += i return total - n def _A ( UpperCamelCase_ : int = 10000) -> int: '''simple docstring''' __lowercase = sum( i for i in range(1, UpperCamelCase_) if sum_of_divisors(sum_of_divisors(UpperCamelCase_)) == i and sum_of_divisors(UpperCamelCase_) != i) return total if __name__ == "__main__": print(solution(int(str(input()).strip())))
17
import unittest from transformers import DebertaVaTokenizer, DebertaVaTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin UpperCamelCase__ = get_tests_dir("""fixtures/spiece.model""") @require_sentencepiece @require_tokenizers class a__ ( snake_case__ , unittest.TestCase ): _a : Optional[Any] = DebertaVaTokenizer _a : Optional[Any] = DebertaVaTokenizerFast _a : List[str] = True _a : Optional[Any] = True def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing __lowerCAmelCase = DebertaVaTokenizer(_A , unk_token="<unk>" ) tokenizer.save_pretrained(self.tmpdirname ) def __SCREAMING_SNAKE_CASE( self , _A ): """simple docstring""" __lowerCAmelCase = "this is a test" __lowerCAmelCase = "this is a test" return input_text, output_text def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "<pad>" __lowerCAmelCase = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_A ) , _A ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_A ) , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<pad>" ) self.assertEqual(vocab_keys[1] , "<unk>" ) self.assertEqual(vocab_keys[-1] , "[PAD]" ) self.assertEqual(len(_A ) , 3_0_0_0_1 ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 3_0_0_0_0 ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = " \tHeLLo!how \n Are yoU? " __lowerCAmelCase = ["▁hello", "!", "how", "▁are", "▁you", "?"] # fmt: on __lowerCAmelCase = DebertaVaTokenizer(_A , do_lower_case=_A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , do_lower_case=_A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) @unittest.skip("There is an inconsistency between slow and fast tokenizer due to a bug in the fast one." ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" pass @unittest.skip("There is an inconsistency between slow and fast tokenizer due to a bug in the fast one." ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" pass def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = ["▁", "<unk>", "▁was", "▁born", "▁in", "▁9", "2000", "▁", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", "▁", ".", ] # fmt: on __lowerCAmelCase = DebertaVaTokenizer(_A , split_by_punct=_A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , split_by_punct=_A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = ["▁i", "▁was", "▁born", "▁in", "▁9", "2000", "▁", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", "▁", ".", ] # fmt: on __lowerCAmelCase = DebertaVaTokenizer(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = ["▁i", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", ".", ] # fmt: on __lowerCAmelCase = DebertaVaTokenizer(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = ["▁", "<unk>", "▁was", "▁born", "▁in", "▁9", "2000", "▁", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", "▁", ".", ] # fmt: on __lowerCAmelCase = DebertaVaTokenizer(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = " \tHeLLo!how \n Are yoU? " __lowerCAmelCase = ["▁", "<unk>", "e", "<unk>", "o", "!", "how", "▁", "<unk>", "re", "▁yo", "<unk>", "?"] # fmt: on __lowerCAmelCase = DebertaVaTokenizer(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , do_lower_case=_A , split_by_punct=_A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self.get_tokenizer() __lowerCAmelCase = self.get_rust_tokenizer() __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = tokenizer.convert_ids_to_tokens(tokenizer.encode(_A , add_special_tokens=_A ) ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(_A , add_special_tokens=_A ) ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.encode(_A , add_special_tokens=_A ) __lowerCAmelCase = rust_tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = self.get_rust_tokenizer() __lowerCAmelCase = tokenizer.encode(_A ) __lowerCAmelCase = rust_tokenizer.encode(_A ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = "This is a test" __lowerCAmelCase = [1_3, 1, 4_3_9_8, 2_5, 2_1, 1_2_8_9] __lowerCAmelCase = ["▁", "T", "his", "▁is", "▁a", "▁test"] __lowerCAmelCase = ["▁", "<unk>", "his", "▁is", "▁a", "▁test"] __lowerCAmelCase = DebertaVaTokenizer(_A , keep_accents=_A ) __lowerCAmelCase = DebertaVaTokenizerFast(_A , keep_accents=_A ) __lowerCAmelCase = tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = rust_tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = rust_tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(_A ) self.assertListEqual(_A , _A ) # fmt: off __lowerCAmelCase = "I was born in 92000, and this is falsé." __lowerCAmelCase = [1_3, 1, 2_3, 3_8_6, 1_9, 5_6_1, 3_0_5_0, 1_5, 1_7, 4_8, 2_5, 8_2_5_6, 1_8, 1, 9] __lowerCAmelCase = ["▁", "I", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "é", ".", ] __lowerCAmelCase = ["▁", "<unk>", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", ".", ] # fmt: on __lowerCAmelCase = tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = tokenizer.convert_ids_to_tokens(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = rust_tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = rust_tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) __lowerCAmelCase = rust_tokenizer.convert_ids_to_tokens(_A ) self.assertListEqual(_A , _A ) def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = DebertaVaTokenizer(_A ) __lowerCAmelCase = tokenizer.encode("sequence builders" ) __lowerCAmelCase = tokenizer.encode("multi-sequence build" ) __lowerCAmelCase = tokenizer.build_inputs_with_special_tokens(_A ) __lowerCAmelCase = tokenizer.build_inputs_with_special_tokens(_A , _A ) self.assertEqual([tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] , _A ) self.assertEqual( [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [tokenizer.sep_token_id] , _A , ) @slow def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = {"input_ids": [[1, 3_9_8_6_7, 3_6, 1_9_3_9_0, 4_8_6, 2_7, 3_5_0_5_2, 8_1_4_3_6, 1_8, 6_0_6_8_5, 1_2_2_5, 7, 3_5_0_5_2, 8_1_4_3_6, 1_8, 9_3_6_7, 1_6_8_9_9, 1_8, 1_5_9_3_7, 5_3, 5_9_4, 7_7_3, 1_8, 1_6_2_8_7, 3_0_4_6_5, 3_6, 1_5_9_3_7, 6, 4_1_1_3_9, 3_8, 3_6_9_7_9, 6_0_7_6_3, 1_9_1, 6, 3_4_1_3_2, 9_9, 6, 5_0_5_3_8, 3_9_0, 4_3_2_3_0, 6, 3_4_1_3_2, 2_7_7_9, 2_0_8_5_0, 1_4, 6_9_9, 1_0_7_2, 1_1_9_4, 3_6, 3_8_2, 1_0_9_0_1, 5_3, 7, 6_9_9, 1_0_7_2, 2_0_8_4, 3_6, 2_0_4_2_2, 6_3_0, 5_3, 1_9, 1_0_5, 3_0_4_9, 1_8_9_6, 1_0_5_3, 1_6_8_9_9, 1_5_0_6, 1_1, 3_7_9_7_8, 4_2_4_3, 7, 1_2_3_7, 3_1_8_6_9, 2_0_0, 1_6_5_6_6, 6_5_4, 6, 3_5_0_5_2, 8_1_4_3_6, 7, 5_5_6_3_0, 1_3_5_9_3, 4, 2], [1, 2_6, 1_5_0_1_1, 1_3, 6_6_7, 8, 1_0_5_3, 1_8, 2_3_6_1_1, 1_2_3_7, 7_2_3_5_6, 1_2_8_2_0, 3_4, 1_0_4_1_3_4, 1_2_0_9, 3_5, 1_3_3_1_3, 6_6_2_7, 2_1, 2_0_2, 3_4_7, 7, 1_6_4, 2_3_9_9, 1_1, 4_6, 4_4_8_5, 4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 5, 1_2_3_2, 2_8_6_4, 1_5_7_8_5, 1_4_9_5_1, 1_0_5, 5, 8_5_8_1, 1_2_5_0, 4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "token_type_ids": [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=_A , model_name="microsoft/deberta-v2-xlarge" , revision="ad6e42c1532ddf3a15c39246b63f5559d558b670" , )
92
0
"""simple docstring""" from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, is_torch_available, is_vision_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_tf_available(): import tensorflow as tf from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING from ..tf_utils import stable_softmax if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING UpperCAmelCase__ = logging.get_logger(__name__) @add_end_docstrings(a_ ) class lowerCAmelCase__ ( a_ ): def __init__( self : str , *_lowerCamelCase : str , **_lowerCamelCase : Tuple ): super().__init__(*lowercase_ , **lowercase_ ) requires_backends(self , '''vision''' ) self.check_model_type( TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING if self.framework == '''tf''' else MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING ) def lowercase ( self : Optional[Any] , _lowerCamelCase : Union[str, Any]=None ): _snake_case = {} if top_k is not None: _snake_case = top_k return {}, {}, postprocess_params def __call__( self : Tuple , _lowerCamelCase : List[Any] , **_lowerCamelCase : Dict ): return super().__call__(lowercase_ , **lowercase_ ) def lowercase ( self : Tuple , _lowerCamelCase : Optional[Any] ): _snake_case = load_image(lowercase_ ) _snake_case = self.image_processor(images=lowercase_ , return_tensors=self.framework ) return model_inputs def lowercase ( self : Dict , _lowerCamelCase : List[str] ): _snake_case = self.model(**lowercase_ ) return model_outputs def lowercase ( self : str , _lowerCamelCase : int , _lowerCamelCase : Optional[Any]=5 ): if top_k > self.model.config.num_labels: _snake_case = self.model.config.num_labels if self.framework == "pt": _snake_case = model_outputs.logits.softmax(-1 )[0] _snake_case , _snake_case = probs.topk(lowercase_ ) elif self.framework == "tf": _snake_case = stable_softmax(model_outputs.logits , axis=-1 )[0] _snake_case = tf.math.top_k(lowercase_ , k=lowercase_ ) _snake_case , _snake_case = topk.values.numpy(), topk.indices.numpy() else: raise ValueError(f'''Unsupported framework: {self.framework}''' ) _snake_case = scores.tolist() _snake_case = ids.tolist() return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(lowercase_ , lowercase_ )]
364
"""simple docstring""" from __future__ import annotations from random import random class lowerCAmelCase__ : def __init__( self : str , _lowerCamelCase : int | None = None ): _snake_case = value _snake_case = random() _snake_case = None _snake_case = None def __repr__( self : int ): from pprint import pformat if self.left is None and self.right is None: return f'''\'{self.value}: {self.prior:.5}\'''' else: return pformat( {f'''{self.value}: {self.prior:.5}''': (self.left, self.right)} , indent=1 ) def __str__( self : Optional[int] ): _snake_case = str(self.value ) + ''' ''' _snake_case = str(self.left or '''''' ) _snake_case = str(self.right or '''''' ) return value + left + right def _UpperCAmelCase ( __lowerCamelCase : Node | None , __lowerCamelCase : int ) -> tuple[Node | None, Node | None]: if root is None: # None tree is split into 2 Nones return None, None elif root.value is None: return None, None else: if value < root.value: _snake_case , _snake_case = split(root.left , __lowerCamelCase ) return left, root else: _snake_case , _snake_case = split(root.right , __lowerCamelCase ) return root, right def _UpperCAmelCase ( __lowerCamelCase : Node | None , __lowerCamelCase : Node | None ) -> Node | None: if (not left) or (not right): # If one node is None, return the other return left or right elif left.prior < right.prior: _snake_case = merge(left.right , __lowerCamelCase ) return left else: _snake_case = merge(__lowerCamelCase , right.left ) return right def _UpperCAmelCase ( __lowerCamelCase : Node | None , __lowerCamelCase : int ) -> Node | None: _snake_case = Node(__lowerCamelCase ) _snake_case , _snake_case = split(__lowerCamelCase , __lowerCamelCase ) return merge(merge(__lowerCamelCase , __lowerCamelCase ) , __lowerCamelCase ) def _UpperCAmelCase ( __lowerCamelCase : Node | None , __lowerCamelCase : int ) -> Node | None: _snake_case , _snake_case = split(__lowerCamelCase , value - 1 ) _snake_case , _snake_case = split(__lowerCamelCase , __lowerCamelCase ) return merge(__lowerCamelCase , __lowerCamelCase ) def _UpperCAmelCase ( __lowerCamelCase : Node | None ) -> None: if not root: # None return else: inorder(root.left ) print(root.value , end=''',''' ) inorder(root.right ) def _UpperCAmelCase ( __lowerCamelCase : Node | None , __lowerCamelCase : str ) -> Node | None: for arg in args.split(): if arg[0] == "+": _snake_case = insert(__lowerCamelCase , int(arg[1:] ) ) elif arg[0] == "-": _snake_case = erase(__lowerCamelCase , int(arg[1:] ) ) else: print('''Unknown command''' ) return root def _UpperCAmelCase ( ) -> None: _snake_case = None print( '''enter numbers to create a tree, + value to add value into treap, ''' '''- value to erase all nodes with value. \'q\' to quit. ''' ) _snake_case = input() while args != "q": _snake_case = interact_treap(__lowerCamelCase , __lowerCamelCase ) print(__lowerCamelCase ) _snake_case = input() print('''good by!''' ) if __name__ == "__main__": import doctest doctest.testmod() main()
40
0
'''simple docstring''' import os import tempfile import unittest from transformers import NezhaConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, NezhaModel, ) from transformers.models.nezha.modeling_nezha import NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST class A : '''simple docstring''' def __init__(self , _UpperCAmelCase , _UpperCAmelCase=1_3 , _UpperCAmelCase=7 , _UpperCAmelCase=True , _UpperCAmelCase=True , _UpperCAmelCase=True , _UpperCAmelCase=True , _UpperCAmelCase=9_9 , _UpperCAmelCase=3_2 , _UpperCAmelCase=5 , _UpperCAmelCase=4 , _UpperCAmelCase=3_7 , _UpperCAmelCase="gelu" , _UpperCAmelCase=0.1 , _UpperCAmelCase=0.1 , _UpperCAmelCase=1_2_8 , _UpperCAmelCase=3_2 , _UpperCAmelCase=1_6 , _UpperCAmelCase=2 , _UpperCAmelCase=0.02 , _UpperCAmelCase=3 , _UpperCAmelCase=4 , _UpperCAmelCase=None , ) -> List[str]: __UpperCamelCase : Optional[int] = parent __UpperCamelCase : int = batch_size __UpperCamelCase : List[Any] = seq_length __UpperCamelCase : Optional[Any] = is_training __UpperCamelCase : Tuple = use_input_mask __UpperCamelCase : List[Any] = use_token_type_ids __UpperCamelCase : Dict = use_labels __UpperCamelCase : List[str] = vocab_size __UpperCamelCase : List[Any] = hidden_size __UpperCamelCase : Optional[Any] = num_hidden_layers __UpperCamelCase : Optional[Any] = num_attention_heads __UpperCamelCase : Optional[int] = intermediate_size __UpperCamelCase : Tuple = hidden_act __UpperCamelCase : Any = hidden_dropout_prob __UpperCamelCase : str = attention_probs_dropout_prob __UpperCamelCase : Tuple = max_position_embeddings __UpperCamelCase : List[Any] = type_vocab_size __UpperCamelCase : Union[str, Any] = type_sequence_label_size __UpperCamelCase : Any = initializer_range __UpperCamelCase : Tuple = num_labels __UpperCamelCase : List[str] = num_choices __UpperCamelCase : Tuple = scope def a_ (self ) -> int: __UpperCamelCase : Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __UpperCamelCase : Optional[int] = None if self.use_input_mask: __UpperCamelCase : Tuple = random_attention_mask([self.batch_size, self.seq_length] ) __UpperCamelCase : str = None if self.use_token_type_ids: __UpperCamelCase : Any = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __UpperCamelCase : Union[str, Any] = None __UpperCamelCase : int = None __UpperCamelCase : Any = None if self.use_labels: __UpperCamelCase : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __UpperCamelCase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __UpperCamelCase : Optional[int] = ids_tensor([self.batch_size] , self.num_choices ) __UpperCamelCase : Dict = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def a_ (self ) -> List[Any]: return NezhaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_UpperCAmelCase , initializer_range=self.initializer_range , ) def a_ (self ) -> int: ( __UpperCamelCase ) : Union[str, Any] = self.prepare_config_and_inputs() __UpperCamelCase : Tuple = True __UpperCamelCase : Any = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __UpperCamelCase : List[str] = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def a_ (self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) -> List[str]: __UpperCamelCase : Optional[int] = NezhaModel(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() __UpperCamelCase : List[Any] = model(_UpperCAmelCase , attention_mask=_UpperCAmelCase , token_type_ids=_UpperCAmelCase ) __UpperCamelCase : Any = model(_UpperCAmelCase , token_type_ids=_UpperCAmelCase ) __UpperCamelCase : int = model(_UpperCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def a_ (self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , ) -> Any: __UpperCamelCase : Union[str, Any] = True __UpperCamelCase : int = NezhaModel(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() __UpperCamelCase : Any = model( _UpperCAmelCase , attention_mask=_UpperCAmelCase , token_type_ids=_UpperCAmelCase , encoder_hidden_states=_UpperCAmelCase , encoder_attention_mask=_UpperCAmelCase , ) __UpperCamelCase : Optional[int] = model( _UpperCAmelCase , attention_mask=_UpperCAmelCase , token_type_ids=_UpperCAmelCase , encoder_hidden_states=_UpperCAmelCase , ) __UpperCamelCase : List[str] = model(_UpperCAmelCase , attention_mask=_UpperCAmelCase , token_type_ids=_UpperCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def a_ (self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) -> Dict: __UpperCamelCase : Optional[Any] = NezhaForMaskedLM(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() __UpperCamelCase : Optional[int] = model(_UpperCAmelCase , attention_mask=_UpperCAmelCase , token_type_ids=_UpperCAmelCase , labels=_UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def a_ (self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) -> List[str]: __UpperCamelCase : List[str] = NezhaForNextSentencePrediction(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() __UpperCamelCase : List[Any] = model( _UpperCAmelCase , attention_mask=_UpperCAmelCase , token_type_ids=_UpperCAmelCase , labels=_UpperCAmelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def a_ (self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) -> Optional[Any]: __UpperCamelCase : Union[str, Any] = NezhaForPreTraining(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() __UpperCamelCase : List[str] = model( _UpperCAmelCase , attention_mask=_UpperCAmelCase , token_type_ids=_UpperCAmelCase , labels=_UpperCAmelCase , next_sentence_label=_UpperCAmelCase , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) ) def a_ (self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) -> int: __UpperCamelCase : Union[str, Any] = NezhaForQuestionAnswering(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() __UpperCamelCase : Any = model( _UpperCAmelCase , attention_mask=_UpperCAmelCase , token_type_ids=_UpperCAmelCase , start_positions=_UpperCAmelCase , end_positions=_UpperCAmelCase , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def a_ (self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) -> Optional[int]: __UpperCamelCase : Dict = self.num_labels __UpperCamelCase : Union[str, Any] = NezhaForSequenceClassification(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() __UpperCamelCase : Union[str, Any] = model(_UpperCAmelCase , attention_mask=_UpperCAmelCase , token_type_ids=_UpperCAmelCase , labels=_UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def a_ (self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) -> int: __UpperCamelCase : Optional[Any] = self.num_labels __UpperCamelCase : Dict = NezhaForTokenClassification(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() __UpperCamelCase : List[Any] = model(_UpperCAmelCase , attention_mask=_UpperCAmelCase , token_type_ids=_UpperCAmelCase , labels=_UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def a_ (self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) -> Any: __UpperCamelCase : Dict = self.num_choices __UpperCamelCase : str = NezhaForMultipleChoice(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() __UpperCamelCase : List[str] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __UpperCamelCase : List[str] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __UpperCamelCase : str = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __UpperCamelCase : str = model( _UpperCAmelCase , attention_mask=_UpperCAmelCase , token_type_ids=_UpperCAmelCase , labels=_UpperCAmelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def a_ (self ) -> List[Any]: __UpperCamelCase : List[str] = self.prepare_config_and_inputs() ( __UpperCamelCase ) : Optional[Any] = config_and_inputs __UpperCamelCase : List[Any] = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class A ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , unittest.TestCase ): '''simple docstring''' A = ( ( NezhaModel, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, ) if is_torch_available() else () ) A = ( { "feature-extraction": NezhaModel, "fill-mask": NezhaForMaskedLM, "question-answering": NezhaForQuestionAnswering, "text-classification": NezhaForSequenceClassification, "token-classification": NezhaForTokenClassification, "zero-shot": NezhaForSequenceClassification, } if is_torch_available() else {} ) A = True def a_ (self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=False ) -> Optional[int]: __UpperCamelCase : Any = super()._prepare_for_class(_UpperCAmelCase , _UpperCAmelCase , return_labels=_UpperCAmelCase ) if return_labels: if model_class in get_values(_UpperCAmelCase ): __UpperCamelCase : Tuple = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=_UpperCAmelCase ) __UpperCamelCase : Tuple = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=_UpperCAmelCase ) return inputs_dict def a_ (self ) -> str: __UpperCamelCase : List[str] = NezhaModelTester(self ) __UpperCamelCase : List[Any] = ConfigTester(self , config_class=_UpperCAmelCase , hidden_size=3_7 ) def a_ (self ) -> Dict: self.config_tester.run_common_tests() def a_ (self ) -> List[str]: __UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_UpperCAmelCase ) def a_ (self ) -> List[str]: __UpperCamelCase : Optional[int] = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*_UpperCAmelCase ) def a_ (self ) -> str: # This regression test was failing with PyTorch < 1.3 ( __UpperCamelCase ) : Optional[int] = self.model_tester.prepare_config_and_inputs_for_decoder() __UpperCamelCase : List[Any] = None self.model_tester.create_and_check_model_as_decoder( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , ) def a_ (self ) -> int: __UpperCamelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_UpperCAmelCase ) def a_ (self ) -> Union[str, Any]: __UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*_UpperCAmelCase ) def a_ (self ) -> Any: __UpperCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_next_sequence_prediction(*_UpperCAmelCase ) def a_ (self ) -> List[Any]: __UpperCamelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*_UpperCAmelCase ) def a_ (self ) -> Optional[Any]: __UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_UpperCAmelCase ) def a_ (self ) -> Optional[Any]: __UpperCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*_UpperCAmelCase ) def a_ (self ) -> Dict: __UpperCamelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_UpperCAmelCase ) @slow def a_ (self ) -> Optional[int]: for model_name in NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCamelCase : Union[str, Any] = NezhaModel.from_pretrained(_UpperCAmelCase ) self.assertIsNotNone(_UpperCAmelCase ) @slow @require_torch_gpu def a_ (self ) -> Any: __UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # NezhaForMultipleChoice behaves incorrectly in JIT environments. if model_class == NezhaForMultipleChoice: return __UpperCamelCase : Optional[Any] = True __UpperCamelCase : List[str] = model_class(config=_UpperCAmelCase ) __UpperCamelCase : Union[str, Any] = self._prepare_for_class(_UpperCAmelCase , _UpperCAmelCase ) __UpperCamelCase : List[Any] = torch.jit.trace( _UpperCAmelCase , (inputs_dict["input_ids"].to("cpu" ), inputs_dict["attention_mask"].to("cpu" )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(_UpperCAmelCase , os.path.join(_UpperCAmelCase , "bert.pt" ) ) __UpperCamelCase : Optional[Any] = torch.jit.load(os.path.join(_UpperCAmelCase , "bert.pt" ) , map_location=_UpperCAmelCase ) loaded(inputs_dict["input_ids"].to(_UpperCAmelCase ) , inputs_dict["attention_mask"].to(_UpperCAmelCase ) ) @require_torch class A ( unittest.TestCase ): '''simple docstring''' @slow def a_ (self ) -> Optional[int]: __UpperCamelCase : Any = NezhaModel.from_pretrained("sijunhe/nezha-cn-base" ) __UpperCamelCase : Optional[Any] = torch.tensor([[0, 1, 2, 3, 4, 5]] ) __UpperCamelCase : List[str] = torch.tensor([[0, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __UpperCamelCase : Tuple = model(_UpperCAmelCase , attention_mask=_UpperCAmelCase )[0] __UpperCamelCase : Any = torch.Size((1, 6, 7_6_8) ) self.assertEqual(output.shape , _UpperCAmelCase ) __UpperCamelCase : List[str] = torch.tensor([[[0.0_685, 0.2_441, 0.1_102], [0.0_600, 0.1_906, 0.1_349], [0.0_221, 0.0_819, 0.0_586]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , _UpperCAmelCase , atol=1E-4 ) ) @slow def a_ (self ) -> int: __UpperCamelCase : List[str] = NezhaForMaskedLM.from_pretrained("sijunhe/nezha-cn-base" ) __UpperCamelCase : Tuple = torch.tensor([[0, 1, 2, 3, 4, 5]] ) __UpperCamelCase : Tuple = torch.tensor([[1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __UpperCamelCase : Union[str, Any] = model(_UpperCAmelCase , attention_mask=_UpperCAmelCase )[0] __UpperCamelCase : Union[str, Any] = torch.Size((1, 6, 2_1_1_2_8) ) self.assertEqual(output.shape , _UpperCAmelCase ) __UpperCamelCase : int = torch.tensor( [[-2.7_939, -1.7_902, -2.2_189], [-2.8_585, -1.8_908, -2.3_723], [-2.6_499, -1.7_750, -2.2_558]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , _UpperCAmelCase , atol=1E-4 ) )
298
"""simple docstring""" def lowercase__ ( _UpperCAmelCase ) -> int: '''simple docstring''' if not isinstance(_UpperCAmelCase , _UpperCAmelCase ): raise TypeError('Input value must be an \'int\' type' ) lowercase : str = 0 while number: position += 1 number >>= 1 return position if __name__ == "__main__": import doctest doctest.testmod()
255
0
import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import SPIECE_UNDERLINE, logging UpperCAmelCase__ : Union[str, Any] =logging.get_logger(__name__) UpperCAmelCase__ : Union[str, Any] ={'''vocab_file''': '''spiece.model'''} UpperCAmelCase__ : Any ={ '''vocab_file''': { '''TsinghuaAI/CPM-Generate''': '''https://huggingface.co/TsinghuaAI/CPM-Generate/resolve/main/spiece.model''', } } class __A ( a ): def __init__( self , UpperCAmelCase_ , UpperCAmelCase_=False , UpperCAmelCase_=True , UpperCAmelCase_=False , UpperCAmelCase_="<s>" , UpperCAmelCase_="</s>" , UpperCAmelCase_="<unk>" , UpperCAmelCase_="<sep>" , UpperCAmelCase_="<pad>" , UpperCAmelCase_="<cls>" , UpperCAmelCase_="<mask>" , UpperCAmelCase_=["<eop>", "<eod>"] , UpperCAmelCase_ = None , **UpperCAmelCase_ , ): lowerCamelCase =AddedToken(UpperCAmelCase_ , lstrip=UpperCAmelCase_ , rstrip=UpperCAmelCase_ ) if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) else mask_token lowerCamelCase ={} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=UpperCAmelCase_ , remove_space=UpperCAmelCase_ , keep_accents=UpperCAmelCase_ , bos_token=UpperCAmelCase_ , eos_token=UpperCAmelCase_ , unk_token=UpperCAmelCase_ , sep_token=UpperCAmelCase_ , pad_token=UpperCAmelCase_ , cls_token=UpperCAmelCase_ , mask_token=UpperCAmelCase_ , additional_special_tokens=UpperCAmelCase_ , sp_model_kwargs=self.sp_model_kwargs , **UpperCAmelCase_ , ) lowerCamelCase =3 lowerCamelCase =do_lower_case lowerCamelCase =remove_space lowerCamelCase =keep_accents lowerCamelCase =vocab_file lowerCamelCase =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(UpperCAmelCase_ ) try: import jieba except ModuleNotFoundError as error: raise error.__class__( """You need to install jieba to use CpmTokenizer or CpmTokenizerFast. """ """See https://pypi.org/project/jieba/ for installation.""" ) lowerCamelCase =jieba lowerCamelCase =str.maketrans(""" \n""" , """\u2582\u2583""" ) @property # Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.vocab_size def _snake_case ( self ): return len(self.sp_model ) def _snake_case ( self ): lowerCamelCase ={self.convert_ids_to_tokens(UpperCAmelCase_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ): lowerCamelCase =self.__dict__.copy() lowerCamelCase =None return state def __setstate__( self , UpperCAmelCase_ ): lowerCamelCase =d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): lowerCamelCase ={} lowerCamelCase =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _snake_case ( self , UpperCAmelCase_ ): if self.remove_space: lowerCamelCase =""" """.join(inputs.strip().split() ) else: lowerCamelCase =inputs lowerCamelCase =outputs.replace("""``""" , """\"""" ).replace("""''""" , """\"""" ) if not self.keep_accents: lowerCamelCase =unicodedata.normalize("""NFKD""" , UpperCAmelCase_ ) lowerCamelCase ="""""".join([c for c in outputs if not unicodedata.combining(UpperCAmelCase_ )] ) if self.do_lower_case: lowerCamelCase =outputs.lower() return outputs def _snake_case ( self , UpperCAmelCase_ ): lowerCamelCase =self.preprocess_text(UpperCAmelCase_ ) lowerCamelCase =self.sp_model.encode(UpperCAmelCase_ , out_type=UpperCAmelCase_ ) lowerCamelCase =[] for piece in pieces: if len(UpperCAmelCase_ ) > 1 and piece[-1] == str(""",""" ) and piece[-2].isdigit(): lowerCamelCase =self.sp_model.EncodeAsPieces(piece[:-1].replace(UpperCAmelCase_ , """""" ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: lowerCamelCase =cur_pieces[1:] else: lowerCamelCase =cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(UpperCAmelCase_ ) else: new_pieces.append(UpperCAmelCase_ ) return new_pieces def _snake_case ( self , UpperCAmelCase_ ): return self.sp_model.PieceToId(UpperCAmelCase_ ) def _snake_case ( self , UpperCAmelCase_ ): return self.sp_model.IdToPiece(UpperCAmelCase_ ) def _snake_case ( self , UpperCAmelCase_ ): lowerCamelCase ="""""".join(UpperCAmelCase_ ).replace(UpperCAmelCase_ , """ """ ).strip() return out_string def _snake_case ( self , UpperCAmelCase_ , UpperCAmelCase_ = None ): lowerCamelCase =[self.sep_token_id] lowerCamelCase =[self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def _snake_case ( self , UpperCAmelCase_ , UpperCAmelCase_ = None , UpperCAmelCase_ = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=UpperCAmelCase_ , token_ids_a=UpperCAmelCase_ , already_has_special_tokens=UpperCAmelCase_ ) if token_ids_a is not None: return ([0] * len(UpperCAmelCase_ )) + [1] + ([0] * len(UpperCAmelCase_ )) + [1, 1] return ([0] * len(UpperCAmelCase_ )) + [1, 1] def _snake_case ( self , UpperCAmelCase_ , UpperCAmelCase_ = None ): lowerCamelCase =[self.sep_token_id] lowerCamelCase =[2] if token_ids_a is None: return len(token_ids_a + sep ) * [0] + cls_segment_id return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id def _snake_case ( self , UpperCAmelCase_ , UpperCAmelCase_ = None ): if not os.path.isdir(UpperCAmelCase_ ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return lowerCamelCase =os.path.join( UpperCAmelCase_ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCAmelCase_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , UpperCAmelCase_ ) elif not os.path.isfile(self.vocab_file ): with open(UpperCAmelCase_ , """wb""" ) as fi: lowerCamelCase =self.sp_model.serialized_model_proto() fi.write(UpperCAmelCase_ ) return (out_vocab_file,) def _snake_case ( self , *UpperCAmelCase_ , **UpperCAmelCase_ ): lowerCamelCase =super()._decode(*UpperCAmelCase_ , **UpperCAmelCase_ ) lowerCamelCase =text.replace(""" """ , """""" ).replace("""\u2582""" , """ """ ).replace("""\u2583""" , """\n""" ) return text
368
from typing import List, Optional, Tuple, Union import torch from ...utils import logging, randn_tensor from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline UpperCAmelCase__ : Dict =logging.get_logger(__name__) # pylint: disable=invalid-name class __A ( a ): def __init__( self , UpperCAmelCase_ , UpperCAmelCase_ ): super().__init__() self.register_modules(unet=UpperCAmelCase_ , scheduler=UpperCAmelCase_ ) @torch.no_grad() def __call__( self , UpperCAmelCase_ = 1 , UpperCAmelCase_ = 100 , UpperCAmelCase_ = None , UpperCAmelCase_ = None , UpperCAmelCase_ = True , ): if audio_length_in_s is None: lowerCamelCase =self.unet.config.sample_size / self.unet.config.sample_rate lowerCamelCase =audio_length_in_s * self.unet.config.sample_rate lowerCamelCase =2 ** len(self.unet.up_blocks ) if sample_size < 3 * down_scale_factor: raise ValueError( f"""{audio_length_in_s} is too small. Make sure it's bigger or equal to""" f""" {3 * down_scale_factor / self.unet.config.sample_rate}.""" ) lowerCamelCase =int(UpperCAmelCase_ ) if sample_size % down_scale_factor != 0: lowerCamelCase =( (audio_length_in_s * self.unet.config.sample_rate) // down_scale_factor + 1 ) * down_scale_factor logger.info( f"""{audio_length_in_s} is increased to {sample_size / self.unet.config.sample_rate} so that it can be handled""" f""" by the model. It will be cut to {original_sample_size / self.unet.config.sample_rate} after the denoising""" """ process.""" ) lowerCamelCase =int(UpperCAmelCase_ ) lowerCamelCase =next(iter(self.unet.parameters() ) ).dtype lowerCamelCase =(batch_size, self.unet.config.in_channels, sample_size) if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) and len(UpperCAmelCase_ ) != batch_size: raise ValueError( f"""You have passed a list of generators of length {len(UpperCAmelCase_ )}, but requested an effective batch""" f""" size of {batch_size}. Make sure the batch size matches the length of the generators.""" ) lowerCamelCase =randn_tensor(UpperCAmelCase_ , generator=UpperCAmelCase_ , device=self.device , dtype=UpperCAmelCase_ ) # set step values self.scheduler.set_timesteps(UpperCAmelCase_ , device=audio.device ) lowerCamelCase =self.scheduler.timesteps.to(UpperCAmelCase_ ) for t in self.progress_bar(self.scheduler.timesteps ): # 1. predict noise model_output lowerCamelCase =self.unet(UpperCAmelCase_ , UpperCAmelCase_ ).sample # 2. compute previous image: x_t -> t_t-1 lowerCamelCase =self.scheduler.step(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ).prev_sample lowerCamelCase =audio.clamp(-1 , 1 ).float().cpu().numpy() lowerCamelCase =audio[:, :, :original_sample_size] if not return_dict: return (audio,) return AudioPipelineOutput(audios=UpperCAmelCase_ )
262
0
import argparse import json import gdown import numpy as np import torch from huggingface_hub import hf_hub_download from transformers import ( VideoMAEConfig, VideoMAEForPreTraining, VideoMAEForVideoClassification, VideoMAEImageProcessor, ) def _a ( UpperCAmelCase ) -> Dict: """simple docstring""" lowerCamelCase__ : Union[str, Any] = VideoMAEConfig() set_architecture_configs(UpperCAmelCase , UpperCAmelCase ) if "finetuned" not in model_name: lowerCamelCase__ : List[Any] = False if "finetuned" in model_name: lowerCamelCase__ : Any = '''huggingface/label-files''' if "kinetics" in model_name: lowerCamelCase__ : Optional[int] = 400 lowerCamelCase__ : Optional[Any] = '''kinetics400-id2label.json''' elif "ssv2" in model_name: lowerCamelCase__ : Union[str, Any] = 174 lowerCamelCase__ : str = '''something-something-v2-id2label.json''' else: raise ValueError('''Model name should either contain \'kinetics\' or \'ssv2\' in case it\'s fine-tuned.''' ) lowerCamelCase__ : Optional[int] = json.load(open(hf_hub_download(UpperCAmelCase , UpperCAmelCase , repo_type='''dataset''' ) , '''r''' ) ) lowerCamelCase__ : Optional[int] = {int(UpperCAmelCase ): v for k, v in idalabel.items()} lowerCamelCase__ : Union[str, Any] = idalabel lowerCamelCase__ : Union[str, Any] = {v: k for k, v in idalabel.items()} return config def _a ( UpperCAmelCase , UpperCAmelCase ) -> Optional[int]: """simple docstring""" if "small" in model_name: lowerCamelCase__ : Optional[Any] = 384 lowerCamelCase__ : Any = 1536 lowerCamelCase__ : Optional[Any] = 12 lowerCamelCase__ : Dict = 16 lowerCamelCase__ : Tuple = 12 lowerCamelCase__ : List[str] = 3 lowerCamelCase__ : List[str] = 192 lowerCamelCase__ : Union[str, Any] = 768 elif "large" in model_name: lowerCamelCase__ : List[Any] = 1024 lowerCamelCase__ : Union[str, Any] = 4096 lowerCamelCase__ : Dict = 24 lowerCamelCase__ : str = 16 lowerCamelCase__ : Union[str, Any] = 12 lowerCamelCase__ : Tuple = 8 lowerCamelCase__ : Tuple = 512 lowerCamelCase__ : Optional[int] = 2048 elif "huge" in model_name: lowerCamelCase__ : Dict = 1280 lowerCamelCase__ : Optional[int] = 5120 lowerCamelCase__ : List[str] = 32 lowerCamelCase__ : Optional[Any] = 16 lowerCamelCase__ : Optional[Any] = 12 lowerCamelCase__ : Dict = 8 lowerCamelCase__ : Any = 640 lowerCamelCase__ : str = 2560 elif "base" not in model_name: raise ValueError('''Model name should include either "small", "base", "large", or "huge"''' ) def _a ( UpperCAmelCase ) -> Any: """simple docstring""" if "encoder." in name: lowerCamelCase__ : Optional[Any] = name.replace('''encoder.''' , '''''' ) if "cls_token" in name: lowerCamelCase__ : Dict = name.replace('''cls_token''' , '''videomae.embeddings.cls_token''' ) if "decoder_pos_embed" in name: lowerCamelCase__ : Dict = name.replace('''decoder_pos_embed''' , '''decoder.decoder_pos_embed''' ) if "pos_embed" in name and "decoder" not in name: lowerCamelCase__ : int = name.replace('''pos_embed''' , '''videomae.embeddings.position_embeddings''' ) if "patch_embed.proj" in name: lowerCamelCase__ : List[str] = name.replace('''patch_embed.proj''' , '''videomae.embeddings.patch_embeddings.projection''' ) if "patch_embed.norm" in name: lowerCamelCase__ : Any = name.replace('''patch_embed.norm''' , '''videomae.embeddings.norm''' ) if "decoder.blocks" in name: lowerCamelCase__ : Union[str, Any] = name.replace('''decoder.blocks''' , '''decoder.decoder_layers''' ) if "blocks" in name: lowerCamelCase__ : Optional[Any] = name.replace('''blocks''' , '''videomae.encoder.layer''' ) if "attn.proj" in name: lowerCamelCase__ : Optional[int] = name.replace('''attn.proj''' , '''attention.output.dense''' ) if "attn" in name and "bias" not in name: lowerCamelCase__ : Any = name.replace('''attn''' , '''attention.self''' ) if "attn" in name: lowerCamelCase__ : List[Any] = name.replace('''attn''' , '''attention.attention''' ) if "norm1" in name: lowerCamelCase__ : Optional[int] = name.replace('''norm1''' , '''layernorm_before''' ) if "norm2" in name: lowerCamelCase__ : List[str] = name.replace('''norm2''' , '''layernorm_after''' ) if "mlp.fc1" in name: lowerCamelCase__ : List[Any] = name.replace('''mlp.fc1''' , '''intermediate.dense''' ) if "mlp.fc2" in name: lowerCamelCase__ : List[str] = name.replace('''mlp.fc2''' , '''output.dense''' ) if "decoder_embed" in name: lowerCamelCase__ : Dict = name.replace('''decoder_embed''' , '''decoder.decoder_embed''' ) if "decoder_norm" in name: lowerCamelCase__ : Optional[Any] = name.replace('''decoder_norm''' , '''decoder.decoder_norm''' ) if "decoder_pred" in name: lowerCamelCase__ : Any = name.replace('''decoder_pred''' , '''decoder.decoder_pred''' ) if "norm.weight" in name and "decoder" not in name and "fc" not in name: lowerCamelCase__ : Tuple = name.replace('''norm.weight''' , '''videomae.layernorm.weight''' ) if "norm.bias" in name and "decoder" not in name and "fc" not in name: lowerCamelCase__ : List[Any] = name.replace('''norm.bias''' , '''videomae.layernorm.bias''' ) if "head" in name and "decoder" not in name: lowerCamelCase__ : int = name.replace('''head''' , '''classifier''' ) return name def _a ( UpperCAmelCase , UpperCAmelCase ) -> Optional[Any]: """simple docstring""" for key in orig_state_dict.copy().keys(): lowerCamelCase__ : List[Any] = orig_state_dict.pop(UpperCAmelCase ) if key.startswith('''encoder.''' ): lowerCamelCase__ : str = key.replace('''encoder.''' , '''''' ) if "qkv" in key: lowerCamelCase__ : Union[str, Any] = key.split('''.''' ) if key.startswith('''decoder.blocks''' ): lowerCamelCase__ : str = config.decoder_hidden_size lowerCamelCase__ : Optional[Any] = int(key_split[2] ) lowerCamelCase__ : str = '''decoder.decoder_layers.''' if "weight" in key: lowerCamelCase__ : List[Any] = val[:dim, :] lowerCamelCase__ : Any = val[dim : dim * 2, :] lowerCamelCase__ : Optional[int] = val[-dim:, :] else: lowerCamelCase__ : Optional[int] = config.hidden_size lowerCamelCase__ : int = int(key_split[1] ) lowerCamelCase__ : Dict = '''videomae.encoder.layer.''' if "weight" in key: lowerCamelCase__ : int = val[:dim, :] lowerCamelCase__ : Any = val[dim : dim * 2, :] lowerCamelCase__ : List[str] = val[-dim:, :] else: lowerCamelCase__ : List[str] = val return orig_state_dict def _a ( ) -> Optional[Any]: """simple docstring""" lowerCamelCase__ : Optional[Any] = hf_hub_download( repo_id='''hf-internal-testing/spaghetti-video''' , filename='''eating_spaghetti.npy''' , repo_type='''dataset''' ) lowerCamelCase__ : Tuple = np.load(UpperCAmelCase ) return list(UpperCAmelCase ) def _a ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> List[str]: """simple docstring""" lowerCamelCase__ : Union[str, Any] = get_videomae_config(UpperCAmelCase ) if "finetuned" in model_name: lowerCamelCase__ : List[Any] = VideoMAEForVideoClassification(UpperCAmelCase ) else: lowerCamelCase__ : List[Any] = VideoMAEForPreTraining(UpperCAmelCase ) # download original checkpoint, hosted on Google Drive lowerCamelCase__ : List[Any] = '''pytorch_model.bin''' gdown.cached_download(UpperCAmelCase , UpperCAmelCase , quiet=UpperCAmelCase ) lowerCamelCase__ : Optional[Any] = torch.load(UpperCAmelCase , map_location='''cpu''' ) if "model" in files: lowerCamelCase__ : Optional[int] = files['''model'''] else: lowerCamelCase__ : Dict = files['''module'''] lowerCamelCase__ : Tuple = convert_state_dict(UpperCAmelCase , UpperCAmelCase ) model.load_state_dict(UpperCAmelCase ) model.eval() # verify model on basic input lowerCamelCase__ : Optional[int] = VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5] , image_std=[0.5, 0.5, 0.5] ) lowerCamelCase__ : Any = prepare_video() lowerCamelCase__ : Optional[int] = image_processor(UpperCAmelCase , return_tensors='''pt''' ) if "finetuned" not in model_name: lowerCamelCase__ : Optional[Any] = hf_hub_download(repo_id='''hf-internal-testing/bool-masked-pos''' , filename='''bool_masked_pos.pt''' ) lowerCamelCase__ : Optional[Any] = torch.load(UpperCAmelCase ) lowerCamelCase__ : List[Any] = model(**UpperCAmelCase ) lowerCamelCase__ : Any = outputs.logits lowerCamelCase__ : Dict = [ '''videomae-small-finetuned-kinetics''', '''videomae-small-finetuned-ssv2''', # Kinetics-400 checkpoints (short = pretrained only for 800 epochs instead of 1600) '''videomae-base-short''', '''videomae-base-short-finetuned-kinetics''', '''videomae-base''', '''videomae-base-finetuned-kinetics''', '''videomae-large''', '''videomae-large-finetuned-kinetics''', '''videomae-huge-finetuned-kinetics''', # Something-Something-v2 checkpoints (short = pretrained only for 800 epochs instead of 2400) '''videomae-base-short-ssv2''', '''videomae-base-short-finetuned-ssv2''', '''videomae-base-ssv2''', '''videomae-base-finetuned-ssv2''', ] # NOTE: logits were tested with image_mean and image_std equal to [0.5, 0.5, 0.5] and [0.5, 0.5, 0.5] if model_name == "videomae-small-finetuned-kinetics": lowerCamelCase__ : Optional[Any] = torch.Size([1, 400] ) lowerCamelCase__ : str = torch.tensor([-0.92_91, -0.40_61, -0.93_07] ) elif model_name == "videomae-small-finetuned-ssv2": lowerCamelCase__ : List[Any] = torch.Size([1, 174] ) lowerCamelCase__ : Optional[Any] = torch.tensor([0.26_71, -0.46_89, -0.82_35] ) elif model_name == "videomae-base": lowerCamelCase__ : Tuple = torch.Size([1, 1408, 1536] ) lowerCamelCase__ : List[str] = torch.tensor([[0.77_39, 0.79_68, 0.70_89], [0.67_01, 0.74_87, 0.62_09], [0.42_87, 0.51_58, 0.47_73]] ) elif model_name == "videomae-base-short": lowerCamelCase__ : Optional[Any] = torch.Size([1, 1408, 1536] ) lowerCamelCase__ : Dict = torch.tensor([[0.79_94, 0.96_12, 0.85_08], [0.74_01, 0.89_58, 0.83_02], [0.58_62, 0.74_68, 0.73_25]] ) # we verified the loss both for normalized and unnormalized targets for this one lowerCamelCase__ : Optional[int] = torch.tensor([0.51_42] ) if config.norm_pix_loss else torch.tensor([0.64_69] ) elif model_name == "videomae-large": lowerCamelCase__ : List[Any] = torch.Size([1, 1408, 1536] ) lowerCamelCase__ : str = torch.tensor([[0.71_49, 0.79_97, 0.69_66], [0.67_68, 0.78_69, 0.69_48], [0.51_39, 0.62_21, 0.56_05]] ) elif model_name == "videomae-large-finetuned-kinetics": lowerCamelCase__ : Tuple = torch.Size([1, 400] ) lowerCamelCase__ : Union[str, Any] = torch.tensor([0.07_71, 0.00_11, -0.36_25] ) elif model_name == "videomae-huge-finetuned-kinetics": lowerCamelCase__ : Union[str, Any] = torch.Size([1, 400] ) lowerCamelCase__ : Union[str, Any] = torch.tensor([0.24_33, 0.16_32, -0.48_94] ) elif model_name == "videomae-base-short-finetuned-kinetics": lowerCamelCase__ : Dict = torch.Size([1, 400] ) lowerCamelCase__ : Dict = torch.tensor([0.65_88, 0.09_90, -0.24_93] ) elif model_name == "videomae-base-finetuned-kinetics": lowerCamelCase__ : Tuple = torch.Size([1, 400] ) lowerCamelCase__ : Optional[Any] = torch.tensor([0.36_69, -0.06_88, -0.24_21] ) elif model_name == "videomae-base-short-ssv2": lowerCamelCase__ : Optional[int] = torch.Size([1, 1408, 1536] ) lowerCamelCase__ : Dict = torch.tensor([[0.47_12, 0.52_96, 0.57_86], [0.22_78, 0.27_29, 0.40_26], [0.03_52, 0.07_30, 0.25_06]] ) elif model_name == "videomae-base-short-finetuned-ssv2": lowerCamelCase__ : Dict = torch.Size([1, 174] ) lowerCamelCase__ : Union[str, Any] = torch.tensor([-0.05_37, -0.15_39, -0.32_66] ) elif model_name == "videomae-base-ssv2": lowerCamelCase__ : int = torch.Size([1, 1408, 1536] ) lowerCamelCase__ : List[str] = torch.tensor([[0.81_31, 0.87_27, 0.85_46], [0.73_66, 0.93_77, 0.88_70], [0.59_35, 0.88_74, 0.85_64]] ) elif model_name == "videomae-base-finetuned-ssv2": lowerCamelCase__ : List[str] = torch.Size([1, 174] ) lowerCamelCase__ : int = torch.tensor([0.19_61, -0.83_37, -0.63_89] ) else: raise ValueError(f"Model name not supported. Should be one of {model_names}" ) # verify logits assert logits.shape == expected_shape if "finetuned" in model_name: assert torch.allclose(logits[0, :3] , UpperCAmelCase , atol=1E-4 ) else: print('''Logits:''' , logits[0, :3, :3] ) assert torch.allclose(logits[0, :3, :3] , UpperCAmelCase , atol=1E-4 ) print('''Logits ok!''' ) # verify loss, if applicable if model_name == "videomae-base-short": lowerCamelCase__ : Optional[Any] = outputs.loss assert torch.allclose(UpperCAmelCase , UpperCAmelCase , atol=1E-4 ) print('''Loss ok!''' ) if pytorch_dump_folder_path is not None: print(f"Saving model and image processor to {pytorch_dump_folder_path}" ) image_processor.save_pretrained(UpperCAmelCase ) model.save_pretrained(UpperCAmelCase ) if push_to_hub: print('''Pushing to the hub...''' ) model.push_to_hub(UpperCAmelCase , organization='''nielsr''' ) if __name__ == "__main__": _A : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--checkpoint_url', default='https://drive.google.com/u/1/uc?id=1tEhLyskjb755TJ65ptsrafUG2llSwQE1&amp;export=download&amp;confirm=t&amp;uuid=aa3276eb-fb7e-482a-adec-dc7171df14c4', type=str, help=( 'URL of the original PyTorch checkpoint (on Google Drive) you\'d like to convert. Should be a direct' ' download link.' ), ) parser.add_argument( '--pytorch_dump_folder_path', default='/Users/nielsrogge/Documents/VideoMAE/Test', type=str, help='Path to the output PyTorch model directory.', ) parser.add_argument('--model_name', default='videomae-base', type=str, help='Name of the model.') parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.' ) _A : int = parser.parse_args() convert_videomae_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.model_name, args.push_to_hub)
142
from typing import Any, Dict, Optional import torch import torch.nn.functional as F from torch import nn from ..utils import maybe_allow_in_graph from .activations import get_activation from .attention_processor import Attention from .embeddings import CombinedTimestepLabelEmbeddings @maybe_allow_in_graph class __SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : Dict , A : int , A : int , A : int , A : Union[str, Any]=0.0 , A : Optional[int] = None , A : str = "geglu" , A : Optional[int] = None , A : bool = False , A : bool = False , A : bool = False , A : bool = False , A : bool = True , A : str = "layer_norm" , A : bool = False , ) ->Any: super().__init__() lowerCamelCase__ : int = only_cross_attention lowerCamelCase__ : Optional[Any] = (num_embeds_ada_norm is not None) and norm_type == '''ada_norm_zero''' lowerCamelCase__ : Union[str, Any] = (num_embeds_ada_norm is not None) and norm_type == '''ada_norm''' if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None: raise ValueError( F"`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to" F" define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}." ) # Define 3 blocks. Each block has its own normalization layer. # 1. Self-Attn if self.use_ada_layer_norm: lowerCamelCase__ : Optional[Any] = AdaLayerNorm(A , A ) elif self.use_ada_layer_norm_zero: lowerCamelCase__ : int = AdaLayerNormZero(A , A ) else: lowerCamelCase__ : Dict = nn.LayerNorm(A , elementwise_affine=A ) lowerCamelCase__ : Any = Attention( query_dim=A , heads=A , dim_head=A , dropout=A , bias=A , cross_attention_dim=cross_attention_dim if only_cross_attention else None , upcast_attention=A , ) # 2. Cross-Attn if cross_attention_dim is not None or double_self_attention: # We currently only use AdaLayerNormZero for self attention where there will only be one attention block. # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during # the second cross attention block. lowerCamelCase__ : Tuple = ( AdaLayerNorm(A , A ) if self.use_ada_layer_norm else nn.LayerNorm(A , elementwise_affine=A ) ) lowerCamelCase__ : int = Attention( query_dim=A , cross_attention_dim=cross_attention_dim if not double_self_attention else None , heads=A , dim_head=A , dropout=A , bias=A , upcast_attention=A , ) # is self-attn if encoder_hidden_states is none else: lowerCamelCase__ : Dict = None lowerCamelCase__ : Tuple = None # 3. Feed-forward lowerCamelCase__ : Optional[int] = nn.LayerNorm(A , elementwise_affine=A ) lowerCamelCase__ : Union[str, Any] = FeedForward(A , dropout=A , activation_fn=A , final_dropout=A ) # let chunk size default to None lowerCamelCase__ : str = None lowerCamelCase__ : Tuple = 0 def __lowerCamelCase ( self : Any , A : Optional[int] , A : int ) ->List[str]: # Sets chunk feed-forward lowerCamelCase__ : List[Any] = chunk_size lowerCamelCase__ : List[str] = dim def __lowerCamelCase ( self : str , A : torch.FloatTensor , A : Optional[torch.FloatTensor] = None , A : Optional[torch.FloatTensor] = None , A : Optional[torch.FloatTensor] = None , A : Optional[torch.LongTensor] = None , A : Dict[str, Any] = None , A : Optional[torch.LongTensor] = None , ) ->Tuple: # Notice that normalization is always applied before the real computation in the following blocks. # 1. Self-Attention if self.use_ada_layer_norm: lowerCamelCase__ : Union[str, Any] = self.norma(A , A ) elif self.use_ada_layer_norm_zero: lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ : Any = self.norma( A , A , A , hidden_dtype=hidden_states.dtype ) else: lowerCamelCase__ : List[str] = self.norma(A ) lowerCamelCase__ : str = cross_attention_kwargs if cross_attention_kwargs is not None else {} lowerCamelCase__ : Any = self.attna( A , encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None , attention_mask=A , **A , ) if self.use_ada_layer_norm_zero: lowerCamelCase__ : Any = gate_msa.unsqueeze(1 ) * attn_output lowerCamelCase__ : Optional[int] = attn_output + hidden_states # 2. Cross-Attention if self.attna is not None: lowerCamelCase__ : int = ( self.norma(A , A ) if self.use_ada_layer_norm else self.norma(A ) ) lowerCamelCase__ : int = self.attna( A , encoder_hidden_states=A , attention_mask=A , **A , ) lowerCamelCase__ : Any = attn_output + hidden_states # 3. Feed-forward lowerCamelCase__ : Union[str, Any] = self.norma(A ) if self.use_ada_layer_norm_zero: lowerCamelCase__ : Optional[int] = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None] if self._chunk_size is not None: # "feed_forward_chunk_size" can be used to save memory if norm_hidden_states.shape[self._chunk_dim] % self._chunk_size != 0: raise ValueError( F"`hidden_states` dimension to be chunked: {norm_hidden_states.shape[self._chunk_dim]} has to be divisible by chunk size: {self._chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`." ) lowerCamelCase__ : Optional[int] = norm_hidden_states.shape[self._chunk_dim] // self._chunk_size lowerCamelCase__ : Optional[int] = torch.cat( [self.ff(A ) for hid_slice in norm_hidden_states.chunk(A , dim=self._chunk_dim )] , dim=self._chunk_dim , ) else: lowerCamelCase__ : Optional[int] = self.ff(A ) if self.use_ada_layer_norm_zero: lowerCamelCase__ : Optional[Any] = gate_mlp.unsqueeze(1 ) * ff_output lowerCamelCase__ : List[Any] = ff_output + hidden_states return hidden_states class __SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : Any , A : int , A : Optional[int] = None , A : int = 4 , A : float = 0.0 , A : str = "geglu" , A : bool = False , ) ->int: super().__init__() lowerCamelCase__ : List[Any] = int(dim * mult ) lowerCamelCase__ : List[Any] = dim_out if dim_out is not None else dim if activation_fn == "gelu": lowerCamelCase__ : int = GELU(A , A ) if activation_fn == "gelu-approximate": lowerCamelCase__ : Optional[int] = GELU(A , A , approximate='''tanh''' ) elif activation_fn == "geglu": lowerCamelCase__ : Any = GEGLU(A , A ) elif activation_fn == "geglu-approximate": lowerCamelCase__ : int = ApproximateGELU(A , A ) lowerCamelCase__ : Union[str, Any] = nn.ModuleList([] ) # project in self.net.append(A ) # project dropout self.net.append(nn.Dropout(A ) ) # project out self.net.append(nn.Linear(A , A ) ) # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout if final_dropout: self.net.append(nn.Dropout(A ) ) def __lowerCamelCase ( self : Dict , A : List[Any] ) ->Optional[Any]: for module in self.net: lowerCamelCase__ : int = module(A ) return hidden_states class __SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : Tuple , A : int , A : int , A : str = "none" ) ->Optional[Any]: super().__init__() lowerCamelCase__ : List[Any] = nn.Linear(A , A ) lowerCamelCase__ : Any = approximate def __lowerCamelCase ( self : List[str] , A : Tuple ) ->str: if gate.device.type != "mps": return F.gelu(A , approximate=self.approximate ) # mps: gelu is not implemented for float16 return F.gelu(gate.to(dtype=torch.floataa ) , approximate=self.approximate ).to(dtype=gate.dtype ) def __lowerCamelCase ( self : List[str] , A : str ) ->Optional[int]: lowerCamelCase__ : List[str] = self.proj(A ) lowerCamelCase__ : Optional[int] = self.gelu(A ) return hidden_states class __SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : Tuple , A : int , A : int ) ->Dict: super().__init__() lowerCamelCase__ : Optional[Any] = nn.Linear(A , dim_out * 2 ) def __lowerCamelCase ( self : List[Any] , A : List[Any] ) ->Tuple: if gate.device.type != "mps": return F.gelu(A ) # mps: gelu is not implemented for float16 return F.gelu(gate.to(dtype=torch.floataa ) ).to(dtype=gate.dtype ) def __lowerCamelCase ( self : Any , A : Union[str, Any] ) ->Any: lowerCamelCase__ , lowerCamelCase__ : List[Any] = self.proj(A ).chunk(2 , dim=-1 ) return hidden_states * self.gelu(A ) class __SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : Any , A : int , A : int ) ->str: super().__init__() lowerCamelCase__ : Optional[int] = nn.Linear(A , A ) def __lowerCamelCase ( self : Union[str, Any] , A : Dict ) ->Optional[Any]: lowerCamelCase__ : List[str] = self.proj(A ) return x * torch.sigmoid(1.7_02 * x ) class __SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : int , A : Dict , A : Optional[Any] ) ->str: super().__init__() lowerCamelCase__ : List[str] = nn.Embedding(A , A ) lowerCamelCase__ : str = nn.SiLU() lowerCamelCase__ : int = nn.Linear(A , embedding_dim * 2 ) lowerCamelCase__ : Optional[Any] = nn.LayerNorm(A , elementwise_affine=A ) def __lowerCamelCase ( self : int , A : Union[str, Any] , A : Union[str, Any] ) ->Union[str, Any]: lowerCamelCase__ : Union[str, Any] = self.linear(self.silu(self.emb(A ) ) ) lowerCamelCase__ , lowerCamelCase__ : List[str] = torch.chunk(A , 2 ) lowerCamelCase__ : Any = self.norm(A ) * (1 + scale) + shift return x class __SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : str , A : Optional[Any] , A : int ) ->str: super().__init__() lowerCamelCase__ : Union[str, Any] = CombinedTimestepLabelEmbeddings(A , A ) lowerCamelCase__ : int = nn.SiLU() lowerCamelCase__ : List[str] = nn.Linear(A , 6 * embedding_dim , bias=A ) lowerCamelCase__ : str = nn.LayerNorm(A , elementwise_affine=A , eps=1e-6 ) def __lowerCamelCase ( self : List[str] , A : Any , A : List[Any] , A : Tuple , A : Dict=None ) ->Union[str, Any]: lowerCamelCase__ : List[Any] = self.linear(self.silu(self.emb(A , A , hidden_dtype=A ) ) ) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ : int = emb.chunk(6 , dim=1 ) lowerCamelCase__ : List[Any] = self.norm(A ) * (1 + scale_msa[:, None]) + shift_msa[:, None] return x, gate_msa, shift_mlp, scale_mlp, gate_mlp class __SCREAMING_SNAKE_CASE ( nn.Module ): def __init__( self : Any , A : int , A : int , A : int , A : Optional[str] = None , A : float = 1e-5 ) ->Any: super().__init__() lowerCamelCase__ : int = num_groups lowerCamelCase__ : List[str] = eps if act_fn is None: lowerCamelCase__ : Tuple = None else: lowerCamelCase__ : Dict = get_activation(A ) lowerCamelCase__ : Any = nn.Linear(A , out_dim * 2 ) def __lowerCamelCase ( self : List[str] , A : Optional[int] , A : str ) ->Tuple: if self.act: lowerCamelCase__ : Union[str, Any] = self.act(A ) lowerCamelCase__ : Optional[Any] = self.linear(A ) lowerCamelCase__ : Optional[Any] = emb[:, :, None, None] lowerCamelCase__ , lowerCamelCase__ : Union[str, Any] = emb.chunk(2 , dim=1 ) lowerCamelCase__ : str = F.group_norm(A , self.num_groups , eps=self.eps ) lowerCamelCase__ : Dict = x * (1 + scale) + shift return x
142
1
"""simple docstring""" from collections.abc import Sequence def lowercase (SCREAMING_SNAKE_CASE_ : Sequence[float] , SCREAMING_SNAKE_CASE_ : bool = False ) -> float: if not arr: return 0 SCREAMING_SNAKE_CASE = 0 if allow_empty_subarrays else float('-inf' ) SCREAMING_SNAKE_CASE = 0.0 for num in arr: SCREAMING_SNAKE_CASE = max(0 if allow_empty_subarrays else num , curr_sum + num ) SCREAMING_SNAKE_CASE = max(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) return max_sum if __name__ == "__main__": from doctest import testmod testmod() __UpperCamelCase = [-2, 1, -3, 4, -1, 2, 1, -5, 4] print(f'''{max_subarray_sum(nums) = }''')
355
"""simple docstring""" from collections.abc import Callable from math import pi, sqrt from random import uniform from statistics import mean def lowercase (SCREAMING_SNAKE_CASE_ : int ) -> List[str]: # A local function to see if a dot lands in the circle. def is_in_circle(SCREAMING_SNAKE_CASE_ : float , SCREAMING_SNAKE_CASE_ : float ) -> bool: SCREAMING_SNAKE_CASE = sqrt((x**2) + (y**2) ) # Our circle has a radius of 1, so a distance # greater than 1 would land outside the circle. return distance_from_centre <= 1 # The proportion of guesses that landed in the circle SCREAMING_SNAKE_CASE = mean( int(is_in_circle(uniform(-1.0 , 1.0 ) , uniform(-1.0 , 1.0 ) ) ) for _ in range(SCREAMING_SNAKE_CASE_ ) ) # The ratio of the area for circle to square is pi/4. SCREAMING_SNAKE_CASE = proportion * 4 print(F'The estimated value of pi is {pi_estimate}' ) print(F'The numpy value of pi is {pi}' ) print(F'The total error is {abs(pi - pi_estimate )}' ) def lowercase (SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Callable[[float], float] , SCREAMING_SNAKE_CASE_ : float = 0.0 , SCREAMING_SNAKE_CASE_ : float = 1.0 , ) -> float: return mean( function_to_integrate(uniform(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) for _ in range(SCREAMING_SNAKE_CASE_ ) ) * (max_value - min_value) def lowercase (SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : float = 0.0 , SCREAMING_SNAKE_CASE_ : float = 1.0 ) -> None: def identity_function(SCREAMING_SNAKE_CASE_ : float ) -> float: return x SCREAMING_SNAKE_CASE = area_under_curve_estimator( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE = (max_value * max_value - min_value * min_value) / 2 print('******************' ) print(F'Estimating area under y=x where x varies from {min_value} to {max_value}' ) print(F'Estimated value is {estimated_value}' ) print(F'Expected value is {expected_value}' ) print(F'Total error is {abs(estimated_value - expected_value )}' ) print('******************' ) def lowercase (SCREAMING_SNAKE_CASE_ : int ) -> None: def function_to_integrate(SCREAMING_SNAKE_CASE_ : float ) -> float: return sqrt(4.0 - x * x ) SCREAMING_SNAKE_CASE = area_under_curve_estimator( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , 0.0 , 2.0 ) print('******************' ) print('Estimating pi using area_under_curve_estimator' ) print(F'Estimated value is {estimated_value}' ) print(F'Expected value is {pi}' ) print(F'Total error is {abs(estimated_value - pi )}' ) print('******************' ) if __name__ == "__main__": import doctest doctest.testmod()
38
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A__ = logging.get_logger(__name__) A__ = { '''andreasmadsen/efficient_mlm_m0.40''': ( '''https://huggingface.co/andreasmadsen/efficient_mlm_m0.40/resolve/main/config.json''' ), } class a ( __lowerCamelCase ): __lowerCAmelCase : Union[str, Any] = """roberta-prelayernorm""" def __init__( self :List[Any] ,__lowercase :Tuple=5_0_2_6_5 ,__lowercase :Any=7_6_8 ,__lowercase :List[Any]=1_2 ,__lowercase :str=1_2 ,__lowercase :List[Any]=3_0_7_2 ,__lowercase :List[str]="gelu" ,__lowercase :Dict=0.1 ,__lowercase :List[str]=0.1 ,__lowercase :int=5_1_2 ,__lowercase :List[Any]=2 ,__lowercase :str=0.02 ,__lowercase :List[str]=1e-1_2 ,__lowercase :Any=1 ,__lowercase :List[str]=0 ,__lowercase :Union[str, Any]=2 ,__lowercase :int="absolute" ,__lowercase :Any=True ,__lowercase :Optional[Any]=None ,**__lowercase :List[str] ,): super().__init__(pad_token_id=__lowercase ,bos_token_id=__lowercase ,eos_token_id=__lowercase ,**__lowercase ) snake_case__ : Dict = vocab_size snake_case__ : Optional[Any] = hidden_size snake_case__ : Optional[Any] = num_hidden_layers snake_case__ : Optional[int] = num_attention_heads snake_case__ : str = hidden_act snake_case__ : str = intermediate_size snake_case__ : Dict = hidden_dropout_prob snake_case__ : Union[str, Any] = attention_probs_dropout_prob snake_case__ : List[str] = max_position_embeddings snake_case__ : Optional[Any] = type_vocab_size snake_case__ : Dict = initializer_range snake_case__ : Optional[Any] = layer_norm_eps snake_case__ : Dict = position_embedding_type snake_case__ : Union[str, Any] = use_cache snake_case__ : Optional[Any] = classifier_dropout class a ( __lowerCamelCase ): @property def __lowerCamelCase ( self :List[str] ): if self.task == "multiple-choice": snake_case__ : int = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: snake_case__ : Tuple = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ] )
230
import math import sys def _lowerCAmelCase ( __lowerCAmelCase ) -> str: """simple docstring""" snake_case__ : Optional[Any] = '''''' try: with open(__lowerCAmelCase , '''rb''' ) as binary_file: snake_case__ : int = binary_file.read() for dat in data: snake_case__ : Any = f"""{dat:08b}""" result += curr_byte return result except OSError: print('''File not accessible''' ) sys.exit() def _lowerCAmelCase ( __lowerCAmelCase ) -> str: """simple docstring""" snake_case__ : List[str] = {'''0''': '''0''', '''1''': '''1'''} snake_case__ , snake_case__ : List[Any] = '''''', '''''' snake_case__ : Tuple = len(__lowerCAmelCase ) for i in range(len(__lowerCAmelCase ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue snake_case__ : Tuple = lexicon[curr_string] result += last_match_id snake_case__ : Any = last_match_id + '''0''' if math.loga(__lowerCAmelCase ).is_integer(): snake_case__ : Tuple = {} for curr_key in list(__lowerCAmelCase ): snake_case__ : Union[str, Any] = lexicon.pop(__lowerCAmelCase ) snake_case__ : Optional[Any] = new_lex snake_case__ : Tuple = last_match_id + '''1''' index += 1 snake_case__ : Dict = '''''' return result def _lowerCAmelCase ( __lowerCAmelCase , __lowerCAmelCase ) -> None: """simple docstring""" snake_case__ : Dict = 8 try: with open(__lowerCAmelCase , '''wb''' ) as opened_file: snake_case__ : Union[str, Any] = [ 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[:-1]: opened_file.write(int(__lowerCAmelCase , 2 ).to_bytes(1 , byteorder='''big''' ) ) except OSError: print('''File not accessible''' ) sys.exit() def _lowerCAmelCase ( __lowerCAmelCase ) -> str: """simple docstring""" snake_case__ : Any = 0 for letter in data_bits: if letter == "1": break counter += 1 snake_case__ : Optional[int] = data_bits[counter:] snake_case__ : int = data_bits[counter + 1 :] return data_bits def _lowerCAmelCase ( __lowerCAmelCase , __lowerCAmelCase ) -> None: """simple docstring""" snake_case__ : Union[str, Any] = read_file_binary(__lowerCAmelCase ) snake_case__ : List[str] = remove_prefix(__lowerCAmelCase ) snake_case__ : Any = decompress_data(__lowerCAmelCase ) write_file_binary(__lowerCAmelCase , __lowerCAmelCase ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
230
1
"""simple docstring""" from .data_collator import ( DataCollatorForLanguageModeling, DataCollatorForPermutationLanguageModeling, DataCollatorForSeqaSeq, DataCollatorForSOP, DataCollatorForTokenClassification, DataCollatorForWholeWordMask, DataCollatorWithPadding, DefaultDataCollator, default_data_collator, ) from .metrics import glue_compute_metrics, xnli_compute_metrics from .processors import ( DataProcessor, InputExample, InputFeatures, SingleSentenceClassificationProcessor, SquadExample, SquadFeatures, SquadVaProcessor, SquadVaProcessor, glue_convert_examples_to_features, glue_output_modes, glue_processors, glue_tasks_num_labels, squad_convert_examples_to_features, xnli_output_modes, xnli_processors, xnli_tasks_num_labels, )
367
"""simple docstring""" from __future__ import annotations import inspect import unittest from math import floor import numpy as np from transformers import CvtConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFCvtForImageClassification, TFCvtModel from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class snake_case ( SCREAMING_SNAKE_CASE_ ): def UpperCAmelCase__ ( self) ->Any: a_ = self.config_class(**self.inputs_dict) self.parent.assertTrue(hasattr(__UpperCAmelCase , "embed_dim")) self.parent.assertTrue(hasattr(__UpperCAmelCase , "num_heads")) class snake_case : def __init__( self , __UpperCAmelCase , __UpperCAmelCase=13 , __UpperCAmelCase=64 , __UpperCAmelCase=3 , __UpperCAmelCase=[16, 48, 96] , __UpperCAmelCase=[1, 3, 6] , __UpperCAmelCase=[1, 2, 10] , __UpperCAmelCase=[7, 3, 3] , __UpperCAmelCase=[4, 2, 2] , __UpperCAmelCase=[2, 1, 1] , __UpperCAmelCase=[2, 2, 2] , __UpperCAmelCase=[False, False, True] , __UpperCAmelCase=[0.0, 0.0, 0.0] , __UpperCAmelCase=0.02 , __UpperCAmelCase=1E-12 , __UpperCAmelCase=True , __UpperCAmelCase=True , __UpperCAmelCase=2 , ) ->Optional[int]: a_ = parent a_ = batch_size a_ = image_size a_ = patch_sizes a_ = patch_stride a_ = patch_padding a_ = is_training a_ = use_labels a_ = num_labels a_ = num_channels a_ = embed_dim a_ = num_heads a_ = stride_kv a_ = depth a_ = cls_token a_ = attention_drop_rate a_ = initializer_range a_ = layer_norm_eps def UpperCAmelCase__ ( self) ->Any: a_ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) a_ = None if self.use_labels: # create a random int32 tensor of given shape a_ = ids_tensor([self.batch_size] , self.num_labels) a_ = self.get_config() return config, pixel_values, labels def UpperCAmelCase__ ( self) ->Union[str, Any]: return CvtConfig( image_size=self.image_size , num_labels=self.num_labels , num_channels=self.num_channels , embed_dim=self.embed_dim , num_heads=self.num_heads , patch_sizes=self.patch_sizes , patch_padding=self.patch_padding , patch_stride=self.patch_stride , stride_kv=self.stride_kv , depth=self.depth , cls_token=self.cls_token , attention_drop_rate=self.attention_drop_rate , initializer_range=self.initializer_range , ) def UpperCAmelCase__ ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase) ->Optional[Any]: a_ = TFCvtModel(config=__UpperCAmelCase) a_ = model(__UpperCAmelCase , training=__UpperCAmelCase) a_ = (self.image_size, self.image_size) a_ , a_ = image_size[0], image_size[1] for i in range(len(self.depth)): a_ = floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1) a_ = floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dim[-1], height, width)) def UpperCAmelCase__ ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase) ->str: a_ = self.num_labels a_ = TFCvtForImageClassification(__UpperCAmelCase) a_ = model(__UpperCAmelCase , labels=__UpperCAmelCase , training=__UpperCAmelCase) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def UpperCAmelCase__ ( self) ->Tuple: a_ = self.prepare_config_and_inputs() a_ , a_ , a_ = config_and_inputs a_ = {"pixel_values": pixel_values} return config, inputs_dict @require_tf class snake_case ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , unittest.TestCase ): a_ : Union[str, Any] = (TFCvtModel, TFCvtForImageClassification) if is_tf_available() else () a_ : List[Any] = ( {"""feature-extraction""": TFCvtModel, """image-classification""": TFCvtForImageClassification} if is_tf_available() else {} ) a_ : Any = False a_ : Dict = False a_ : Optional[int] = False a_ : List[Any] = False a_ : List[Any] = False def UpperCAmelCase__ ( self) ->List[str]: a_ = TFCvtModelTester(self) a_ = TFCvtConfigTester(self , config_class=__UpperCAmelCase , has_text_modality=__UpperCAmelCase , hidden_size=37) def UpperCAmelCase__ ( self) ->List[str]: self.config_tester.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() @unittest.skip(reason="Cvt does not output attentions") def UpperCAmelCase__ ( self) ->Dict: pass @unittest.skip(reason="Cvt does not use inputs_embeds") def UpperCAmelCase__ ( self) ->List[str]: pass @unittest.skip(reason="Cvt does not support input and output embeddings") def UpperCAmelCase__ ( self) ->Optional[Any]: pass @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices("GPU")) == 0 , reason="TF does not support backprop for grouped convolutions on CPU." , ) def UpperCAmelCase__ ( self) ->Dict: super().test_dataset_conversion() @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices("GPU")) == 0 , reason="TF does not support backprop for grouped convolutions on CPU." , ) @slow def UpperCAmelCase__ ( self) ->List[str]: super().test_keras_fit() @unittest.skip(reason="Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8") def UpperCAmelCase__ ( self) ->Dict: a_ = tf.keras.mixed_precision.Policy("mixed_float16") tf.keras.mixed_precision.set_global_policy(__UpperCAmelCase) super().test_keras_fit() tf.keras.mixed_precision.set_global_policy("float32") def UpperCAmelCase__ ( self) ->Optional[int]: a_ , a_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a_ = model_class(__UpperCAmelCase) a_ = inspect.signature(model.call) # signature.parameters is an OrderedDict => so arg_names order is deterministic a_ = [*signature.parameters.keys()] a_ = ["pixel_values"] self.assertListEqual(arg_names[:1] , __UpperCAmelCase) def UpperCAmelCase__ ( self) ->Optional[int]: def check_hidden_states_output(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase): a_ = model_class(__UpperCAmelCase) a_ = model(**self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase)) a_ = outputs.hidden_states a_ = len(self.model_tester.depth) self.assertEqual(len(__UpperCAmelCase) , __UpperCAmelCase) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-3:]) , [ self.model_tester.embed_dim[0], self.model_tester.image_size // 4, self.model_tester.image_size // 4, ] , ) 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(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] a_ = True check_hidden_states_output(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase) def UpperCAmelCase__ ( self) ->Dict: a_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__UpperCAmelCase) def UpperCAmelCase__ ( self) ->List[str]: a_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__UpperCAmelCase) @slow def UpperCAmelCase__ ( self) ->str: for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a_ = TFCvtModel.from_pretrained(__UpperCAmelCase) self.assertIsNotNone(__UpperCAmelCase) def UpperCamelCase ( ) ->Dict: """simple docstring""" a_ = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_tf @require_vision class snake_case ( unittest.TestCase ): @cached_property def UpperCAmelCase__ ( self) ->int: return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]) @slow def UpperCAmelCase__ ( self) ->Any: a_ = TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]) a_ = self.default_image_processor a_ = prepare_img() a_ = image_processor(images=__UpperCAmelCase , return_tensors="tf") # forward pass a_ = model(**__UpperCAmelCase) # verify the logits a_ = tf.TensorShape((1, 10_00)) self.assertEqual(outputs.logits.shape , __UpperCAmelCase) a_ = tf.constant([0.9_285, 0.9_015, -0.3_150]) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , __UpperCAmelCase , atol=1E-4))
303
0
import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoImageProcessor, ViTImageProcessor from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test sys.path.append(str(Path(__file__).parent.parent / 'utils')) from test_module.custom_image_processing import CustomImageProcessor # noqa E402 lowercase_ = get_tests_dir('fixtures') class __lowerCAmelCase ( unittest.TestCase ): def A__ ( self ) -> Optional[int]: '''simple docstring''' _lowercase =mock.Mock() _lowercase =500 _lowercase ={} _lowercase =HTTPError _lowercase ={} # Download this model to make sure it's in the cache. _lowercase =ViTImageProcessor.from_pretrained('hf-internal-testing/tiny-random-vit' ) # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch('requests.Session.request' , return_value=lowerCamelCase__ ) as mock_head: _lowercase =ViTImageProcessor.from_pretrained('hf-internal-testing/tiny-random-vit' ) # This check we did call the fake head request mock_head.assert_called() def A__ ( self ) -> List[Any]: '''simple docstring''' _lowercase =ViTImageProcessor.from_pretrained( 'https://huggingface.co/hf-internal-testing/tiny-random-vit/resolve/main/preprocessor_config.json' ) def A__ ( self ) -> Tuple: '''simple docstring''' with self.assertRaises(lowerCamelCase__ ): # config is in subfolder, the following should not work without specifying the subfolder _lowercase =AutoImageProcessor.from_pretrained('hf-internal-testing/stable-diffusion-all-variants' ) _lowercase =AutoImageProcessor.from_pretrained( 'hf-internal-testing/stable-diffusion-all-variants' , subfolder='feature_extractor' ) self.assertIsNotNone(lowerCamelCase__ ) @is_staging_test class __lowerCAmelCase ( unittest.TestCase ): @classmethod def A__ ( cls ) -> List[Any]: '''simple docstring''' _lowercase =TOKEN HfFolder.save_token(lowerCamelCase__ ) @classmethod def A__ ( cls ) -> Tuple: '''simple docstring''' try: delete_repo(token=cls._token , repo_id='test-image-processor' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='valid_org/test-image-processor-org' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='test-dynamic-image-processor' ) except HTTPError: pass def A__ ( self ) -> Tuple: '''simple docstring''' _lowercase =ViTImageProcessor.from_pretrained(lowerCamelCase__ ) image_processor.push_to_hub('test-image-processor' , use_auth_token=self._token ) _lowercase =ViTImageProcessor.from_pretrained(F'''{USER}/test-image-processor''' ) for k, v in image_processor.__dict__.items(): self.assertEqual(lowerCamelCase__ , getattr(lowerCamelCase__ , lowerCamelCase__ ) ) # Reset repo delete_repo(token=self._token , repo_id='test-image-processor' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained( lowerCamelCase__ , repo_id='test-image-processor' , push_to_hub=lowerCamelCase__ , use_auth_token=self._token ) _lowercase =ViTImageProcessor.from_pretrained(F'''{USER}/test-image-processor''' ) for k, v in image_processor.__dict__.items(): self.assertEqual(lowerCamelCase__ , getattr(lowerCamelCase__ , lowerCamelCase__ ) ) def A__ ( self ) -> Optional[Any]: '''simple docstring''' _lowercase =ViTImageProcessor.from_pretrained(lowerCamelCase__ ) image_processor.push_to_hub('valid_org/test-image-processor' , use_auth_token=self._token ) _lowercase =ViTImageProcessor.from_pretrained('valid_org/test-image-processor' ) for k, v in image_processor.__dict__.items(): self.assertEqual(lowerCamelCase__ , getattr(lowerCamelCase__ , lowerCamelCase__ ) ) # Reset repo delete_repo(token=self._token , repo_id='valid_org/test-image-processor' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained( lowerCamelCase__ , repo_id='valid_org/test-image-processor-org' , push_to_hub=lowerCamelCase__ , use_auth_token=self._token ) _lowercase =ViTImageProcessor.from_pretrained('valid_org/test-image-processor-org' ) for k, v in image_processor.__dict__.items(): self.assertEqual(lowerCamelCase__ , getattr(lowerCamelCase__ , lowerCamelCase__ ) ) def A__ ( self ) -> Dict: '''simple docstring''' CustomImageProcessor.register_for_auto_class() _lowercase =CustomImageProcessor.from_pretrained(lowerCamelCase__ ) image_processor.push_to_hub('test-dynamic-image-processor' , use_auth_token=self._token ) # This has added the proper auto_map field to the config self.assertDictEqual( image_processor.auto_map , {'AutoImageProcessor': 'custom_image_processing.CustomImageProcessor'} , ) _lowercase =AutoImageProcessor.from_pretrained( F'''{USER}/test-dynamic-image-processor''' , trust_remote_code=lowerCamelCase__ ) # Can't make an isinstance check because the new_image_processor is from the CustomImageProcessor class of a dynamic module self.assertEqual(new_image_processor.__class__.__name__ , 'CustomImageProcessor' )
205
import argparse import json import numpy import torch from transformers.models.xlm.tokenization_xlm import VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def _a ( SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : Any ): """simple docstring""" UpperCamelCase__ : List[Any] = torch.load(SCREAMING_SNAKE_CASE , map_location='''cpu''' ) UpperCamelCase__ : str = chkpt['''model'''] # We have the base model one level deeper than the original XLM repository UpperCamelCase__ : int = {} for k, v in state_dict.items(): if "pred_layer" in k: UpperCamelCase__ : Optional[int] = v else: UpperCamelCase__ : Tuple = v UpperCamelCase__ : Union[str, Any] = chkpt['''params'''] UpperCamelCase__ : Optional[Any] = {n: v for n, v in config.items() if not isinstance(SCREAMING_SNAKE_CASE , (torch.FloatTensor, numpy.ndarray) )} UpperCamelCase__ : Dict = chkpt['''dico_word2id'''] UpperCamelCase__ : Dict = {s + '''</w>''' if s.find('''@@''' ) == -1 and i > 13 else s.replace('''@@''' , '''''' ): i for s, i in vocab.items()} # Save pytorch-model UpperCamelCase__ : List[str] = pytorch_dump_folder_path + '''/''' + WEIGHTS_NAME UpperCamelCase__ : Optional[Any] = pytorch_dump_folder_path + '''/''' + CONFIG_NAME UpperCamelCase__ : Any = pytorch_dump_folder_path + '''/''' + VOCAB_FILES_NAMES['''vocab_file'''] print(F"Save PyTorch model to {pytorch_weights_dump_path}" ) torch.save(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) print(F"Save configuration file to {pytorch_config_dump_path}" ) with open(SCREAMING_SNAKE_CASE , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(SCREAMING_SNAKE_CASE , indent=2 ) + '''\n''' ) print(F"Save vocab file to {pytorch_config_dump_path}" ) with open(SCREAMING_SNAKE_CASE , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(SCREAMING_SNAKE_CASE , indent=2 ) + '''\n''' ) if __name__ == "__main__": __UpperCamelCase : Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--xlm_checkpoint_path", default=None, type=str, required=True, help="Path the official PyTorch dump." ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) __UpperCamelCase : Optional[int] = parser.parse_args() convert_xlm_checkpoint_to_pytorch(args.xlm_checkpoint_path, args.pytorch_dump_folder_path)
146
0
"""simple docstring""" def __UpperCAmelCase ( UpperCAmelCase_ : list ) -> list: '''simple docstring''' def merge(UpperCAmelCase_ : list , UpperCAmelCase_ : list ) -> list: def _merge(): while left and right: yield (left if left[0] <= right[0] else right).pop(0 ) yield from left yield from right return list(_merge() ) if len(UpperCAmelCase_ ) <= 1: return collection __snake_case : Optional[Any] = len(UpperCAmelCase_ ) // 2 return merge(merge_sort(collection[:mid] ) , merge_sort(collection[mid:] ) ) if __name__ == "__main__": import doctest doctest.testmod() _a : Tuple= input("Enter numbers separated by a comma:\n").strip() _a : List[Any]= [int(item) for item in user_input.split(",")] print(*merge_sort(unsorted), sep=",")
353
"""simple docstring""" import itertools import string from collections.abc import Generator, Iterable def __UpperCAmelCase ( UpperCAmelCase_ : Iterable[str] , UpperCAmelCase_ : int ) -> Generator[tuple[str, ...], None, None]: '''simple docstring''' __snake_case : Optional[int] = iter(UpperCAmelCase_ ) while True: __snake_case : Optional[int] = tuple(itertools.islice(UpperCAmelCase_ , UpperCAmelCase_ ) ) if not chunk: return yield chunk def __UpperCAmelCase ( UpperCAmelCase_ : str ) -> str: '''simple docstring''' __snake_case : Any = ''.join([c.upper() for c in dirty if c in string.ascii_letters] ) __snake_case : Union[str, Any] = '' if len(UpperCAmelCase_ ) < 2: return dirty for i in range(len(UpperCAmelCase_ ) - 1 ): clean += dirty[i] if dirty[i] == dirty[i + 1]: clean += "X" clean += dirty[-1] if len(UpperCAmelCase_ ) & 1: clean += "X" return clean def __UpperCAmelCase ( UpperCAmelCase_ : str ) -> list[str]: '''simple docstring''' __snake_case : List[str] = 'ABCDEFGHIKLMNOPQRSTUVWXYZ' # we're using a list instead of a '2d' array because it makes the math # for setting up the table and doing the actual encoding/decoding simpler __snake_case : Optional[int] = [] # copy key chars into the table if they are in `alphabet` ignoring duplicates for char in key.upper(): if char not in table and char in alphabet: table.append(UpperCAmelCase_ ) # fill the rest of the table in with the remaining alphabet chars for char in alphabet: if char not in table: table.append(UpperCAmelCase_ ) return table def __UpperCAmelCase ( UpperCAmelCase_ : str , UpperCAmelCase_ : str ) -> str: '''simple docstring''' __snake_case : str = generate_table(UpperCAmelCase_ ) __snake_case : Union[str, Any] = prepare_input(UpperCAmelCase_ ) __snake_case : Tuple = '' # https://en.wikipedia.org/wiki/Playfair_cipher#Description for chara, chara in chunker(UpperCAmelCase_ , 2 ): __snake_case , __snake_case : Any = divmod(table.index(UpperCAmelCase_ ) , 5 ) __snake_case , __snake_case : Tuple = divmod(table.index(UpperCAmelCase_ ) , 5 ) if rowa == rowa: ciphertext += table[rowa * 5 + (cola + 1) % 5] ciphertext += table[rowa * 5 + (cola + 1) % 5] elif cola == cola: ciphertext += table[((rowa + 1) % 5) * 5 + cola] ciphertext += table[((rowa + 1) % 5) * 5 + cola] else: # rectangle ciphertext += table[rowa * 5 + cola] ciphertext += table[rowa * 5 + cola] return ciphertext def __UpperCAmelCase ( UpperCAmelCase_ : str , UpperCAmelCase_ : str ) -> str: '''simple docstring''' __snake_case : Optional[int] = generate_table(UpperCAmelCase_ ) __snake_case : Any = '' # https://en.wikipedia.org/wiki/Playfair_cipher#Description for chara, chara in chunker(UpperCAmelCase_ , 2 ): __snake_case , __snake_case : Union[str, Any] = divmod(table.index(UpperCAmelCase_ ) , 5 ) __snake_case , __snake_case : Tuple = divmod(table.index(UpperCAmelCase_ ) , 5 ) if rowa == rowa: plaintext += table[rowa * 5 + (cola - 1) % 5] plaintext += table[rowa * 5 + (cola - 1) % 5] elif cola == cola: plaintext += table[((rowa - 1) % 5) * 5 + cola] plaintext += table[((rowa - 1) % 5) * 5 + cola] else: # rectangle plaintext += table[rowa * 5 + cola] plaintext += table[rowa * 5 + cola] return plaintext
95
0
from . import ( albert, align, altclip, audio_spectrogram_transformer, auto, autoformer, bark, bart, barthez, bartpho, beit, bert, bert_generation, bert_japanese, bertweet, big_bird, bigbird_pegasus, biogpt, bit, blenderbot, blenderbot_small, blip, blip_a, bloom, bridgetower, byta, camembert, canine, chinese_clip, clap, clip, clipseg, codegen, conditional_detr, convbert, convnext, convnextva, cpm, cpmant, ctrl, cvt, dataavec, deberta, deberta_va, decision_transformer, deformable_detr, deit, deprecated, deta, detr, dialogpt, dinat, distilbert, dit, donut, dpr, dpt, efficientformer, efficientnet, electra, encodec, encoder_decoder, ernie, ernie_m, esm, falcon, flaubert, flava, fnet, focalnet, fsmt, funnel, git, glpn, gpta, gpt_bigcode, gpt_neo, gpt_neox, gpt_neox_japanese, gpt_swa, gptj, gptsan_japanese, graphormer, groupvit, herbert, hubert, ibert, imagegpt, informer, instructblip, jukebox, layoutlm, layoutlmva, layoutlmva, layoutxlm, led, levit, lilt, llama, longformer, longta, luke, lxmert, mam_aaa, marian, markuplm, maskaformer, maskformer, mbart, mbartaa, mega, megatron_bert, megatron_gpta, mgp_str, mluke, mobilebert, mobilenet_va, mobilenet_va, mobilevit, mobilevitva, mpnet, mra, mta, musicgen, mvp, nat, nezha, nllb, nllb_moe, nystromformer, oneformer, open_llama, openai, opt, owlvit, pegasus, pegasus_x, perceiver, phobert, pixastruct, plbart, poolformer, prophetnet, qdqbert, rag, realm, reformer, regnet, rembert, resnet, roberta, roberta_prelayernorm, roc_bert, roformer, rwkv, sam, segformer, sew, sew_d, speech_encoder_decoder, speech_to_text, speech_to_text_a, speechta, splinter, squeezebert, swiftformer, swin, swinasr, swinva, switch_transformers, ta, table_transformer, tapas, time_series_transformer, timesformer, timm_backbone, transfo_xl, trocr, tvlt, umta, unispeech, unispeech_sat, upernet, videomae, vilt, vision_encoder_decoder, vision_text_dual_encoder, visual_bert, vit, vit_hybrid, vit_mae, vit_msn, vivit, wavaveca, wavaveca_conformer, wavaveca_phoneme, wavaveca_with_lm, wavlm, whisper, x_clip, xglm, xlm, xlm_prophetnet, xlm_roberta, xlm_roberta_xl, xlnet, xmod, yolos, yoso, )
328
def A_ ( snake_case : str ) -> int: '''simple docstring''' assert column_title.isupper() __UpperCamelCase = 0 __UpperCamelCase = len(snake_case ) - 1 __UpperCamelCase = 0 while index >= 0: __UpperCamelCase = (ord(column_title[index] ) - 64) * pow(26 , snake_case ) answer += value power += 1 index -= 1 return answer if __name__ == "__main__": from doctest import testmod testmod()
328
1
# HF Trainer benchmarking tool # # This tool can be used to run and compare multiple dimensions of the HF Trainers args. # # It then prints a report once in github format with all the information that needs to be shared # with others and second time in a console-friendly format, so it's easier to use for tuning things up. # # The main idea is: # # ./trainer-benchmark.py --base-cmd '<cmd args that don't change>' \ # --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1' \ # --target-metric-key train_samples_per_second # # The variations can be any command line argument that you want to compare and not just dtype as in # the example. # # --variations allows you to compare variations in multiple dimensions. # # as the first dimention has 2 options and the second 3 in our example, this will run the trainer 6 # times adding one of: # # 1. --tf32 0 --fp16 0 # 2. --tf32 0 --fp16 1 # 3. --tf32 0 --bf16 1 # 4. --tf32 1 --fp16 0 # 5. --tf32 1 --fp16 1 # 6. --tf32 1 --bf16 1 # # and print the results. This is just a cartesian product - and more than 2 dimensions can be used. # # If you want to rely on defaults, this: # --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1' # is identical to this: # --variations '--tf32 0|--tf32 1' '|--fp16|--bf16' # # the leading empty variation in the 2nd dimension is a valid variation. # # So here we get the following 6 variations: # # 1. --tf32 0 # 2. --tf32 0 --fp16 # 3. --tf32 0 --bf16 # 4. --tf32 1 # 5. --tf32 1 --fp16 # 6. --tf32 1 --bf16 # # In this particular case we don't know what the default tf32 setting is as it's normally # pytorch-version dependent). That's why it's best to do an explicit setting of each variation: # `--tf32 0|--tf32 1` # # Here is a full example of a train: # # CUDA_VISIBLE_DEVICES=0 python ./scripts/benchmark/trainer-benchmark.py \ # --base-cmd \ # ' examples/pytorch/translation/run_translation.py --model_name_or_path t5-small \ # --output_dir output_dir --do_train --label_smoothing 0.1 --logging_strategy no \ # --save_strategy no --per_device_train_batch_size 32 --max_source_length 512 \ # --max_target_length 512 --num_train_epochs 1 --overwrite_output_dir \ # --source_lang en --target_lang ro --dataset_name wmt16 --dataset_config "ro-en" \ # --source_prefix "translate English to Romanian: " --warmup_steps 50 \ # --max_train_samples 20000 --dataloader_num_workers 2 ' \ # --target-metric-key train_samples_per_second --repeat-times 1 --variations \ # '|--fp16|--bf16' '--tf32 0|--tf32 1' --report-metric-keys train_loss \ # --repeat-times 1 --base-variation '--tf32 0' # # and here is a possible output: # # # | Variation | Train | Diff | Train | # | | samples | % | loss | # | | per | | | # | | second | | | # |:----------------|----------:|-------:|--------:| # | --tf32 0 | 285.11 | 0 | 2.51 | # | --tf32 1 | 342.09 | 20 | 2.51 | # | --fp16 --tf32 0 | 423.49 | 49 | 2.51 | # | --fp16 --tf32 1 | 423.13 | 48 | 2.51 | # | --bf16 --tf32 0 | 416.80 | 46 | 2.52 | # | --bf16 --tf32 1 | 415.87 | 46 | 2.52 | # # # So you can quickly compare the different outcomes. # # Typically running each experiment once is enough, but if the environment is unstable you can # re-run each multiple times, e.g., 3 using --repeat-times 3 and it will report the averaged results. # # By default it'll use the lowest result as the base line to use as 100% and then compare the rest to # it as can be seen from the table above, but you can also specify which combination is the one to use as # the baseline, e.g., to change to another entry use: --base-variation '--tf32 1 --fp16 0' # # --target-metric-key is there to tell the program which metrics to compare - the different metric keys are # inside output_dir/all_results.json. e.g., to measure eval performance instead of train use: # --target-metric-key eval_samples_per_second # but of course you will need to adjust the --base-cmd value in the example to perform evaluation as # well (as currently it doesn't) # import argparse import datetime import io import itertools import json import math import os import platform import re import shlex import subprocess import sys from pathlib import Path from statistics import fmean import pandas as pd import torch from tqdm import tqdm import transformers __SCREAMING_SNAKE_CASE : List[str] = float('nan') class lowercase_ : def __init__( self , lowercase_ ): _snake_case : List[str] = sys.stdout _snake_case : List[Any] = open(lowercase_ , "a" ) def __getattr__( self , lowercase_ ): return getattr(self.stdout , lowercase_ ) def UpperCamelCase ( self , lowercase_ ): self.stdout.write(lowercase_ ) # strip tqdm codes self.file.write(re.sub(R"^.*\r" , "" , lowercase_ , 0 , re.M ) ) def snake_case (__lowercase=80 , __lowercase=False ) -> List[str]: '''simple docstring''' _snake_case : Dict = [] # deal with critical env vars _snake_case : List[str] = ["CUDA_VISIBLE_DEVICES"] for key in env_keys: _snake_case : List[str] = os.environ.get(__lowercase , __lowercase ) if val is not None: cmd.append(F"""{key}={val}""" ) # python executable (not always needed if the script is executable) _snake_case : Dict = sys.executable if full_python_path else sys.executable.split("/" )[-1] cmd.append(__lowercase ) # now the normal args cmd += list(map(shlex.quote , sys.argv ) ) # split up into up to MAX_WIDTH lines with shell multi-line escapes _snake_case : str = [] _snake_case : List[Any] = "" while len(__lowercase ) > 0: current_line += F"""{cmd.pop(0 )} """ if len(__lowercase ) == 0 or len(__lowercase ) + len(cmd[0] ) + 1 > max_width - 1: lines.append(__lowercase ) _snake_case : List[str] = "" return "\\\n".join(__lowercase ) def snake_case (__lowercase , __lowercase ) -> str: '''simple docstring''' _snake_case : Any = re.sub(r"[\\\n]+" , " " , args.base_cmd ) # remove --output_dir if any and set our own _snake_case : Union[str, Any] = re.sub("--output_dir\s+[^\s]+" , "" , args.base_cmd ) args.base_cmd += F""" --output_dir {output_dir}""" # ensure we have --overwrite_output_dir _snake_case : Optional[Any] = re.sub("--overwrite_output_dir\s+" , "" , args.base_cmd ) args.base_cmd += " --overwrite_output_dir" return [sys.executable] + shlex.split(args.base_cmd ) def snake_case (__lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase ) -> Dict: '''simple docstring''' if 0: import random from time import sleep sleep(0 ) return dict( {k: random.uniform(0 , 100 ) for k in metric_keys} , **{target_metric_key: random.choice([nan, 10.31, 100.2, 55.6666, 222.22222222] )} , ) _snake_case : Union[str, Any] = subprocess.run(__lowercase , capture_output=__lowercase , text=__lowercase ) if verbose: print("STDOUT" , result.stdout ) print("STDERR" , result.stderr ) # save the streams _snake_case : int = variation.replace(" " , "-" ) with open(Path(__lowercase ) / F"""log.{prefix}.stdout.txt""" , "w" ) as f: f.write(result.stdout ) with open(Path(__lowercase ) / F"""log.{prefix}.stderr.txt""" , "w" ) as f: f.write(result.stderr ) if result.returncode != 0: if verbose: print("failed" ) return {target_metric_key: nan} with io.open(F"""{output_dir}/all_results.json""" , "r" , encoding="utf-8" ) as f: _snake_case : List[str] = json.load(__lowercase ) # filter out just the keys we want return {k: v for k, v in metrics.items() if k in metric_keys} def snake_case (__lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , ) -> Tuple: '''simple docstring''' _snake_case : List[Any] = [] _snake_case : Optional[Any] = [] _snake_case : Union[str, Any] = F"""{id}: {variation:<{longest_variation_len}}""" _snake_case : Tuple = F"""{preamble}: """ _snake_case : str = set(report_metric_keys + [target_metric_key] ) for i in tqdm(range(__lowercase ) , desc=__lowercase , leave=__lowercase ): _snake_case : Tuple = process_run_single( __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase ) _snake_case : Tuple = single_run_metrics[target_metric_key] if not math.isnan(__lowercase ): metrics.append(__lowercase ) results.append(__lowercase ) outcome += "✓" else: outcome += "✘" _snake_case : Any = F"""\33[2K\r{outcome}""" if len(__lowercase ) > 0: _snake_case : str = {k: fmean([x[k] for x in metrics] ) for k in metrics[0].keys()} _snake_case : Optional[Any] = round(mean_metrics[target_metric_key] , 2 ) _snake_case : int = F"""{outcome} {mean_target}""" if len(__lowercase ) > 1: results_str += F""" {tuple(round(__lowercase , 2 ) for x in results )}""" print(__lowercase ) _snake_case : Any = variation return mean_metrics else: print(__lowercase ) return {variation_key: variation, target_metric_key: nan} def snake_case () -> Optional[int]: '''simple docstring''' _snake_case : Union[str, Any] = torch.cuda.get_device_properties(torch.device("cuda" ) ) return F""" Datetime : {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S' )} Software: transformers: {transformers.__version__} torch : {torch.__version__} cuda : {torch.version.cuda} python : {platform.python_version()} Hardware: {torch.cuda.device_count()} GPUs : {properties.name}, {properties.total_memory/2**30:0.2f}GB """ def snake_case (__lowercase , __lowercase , __lowercase , __lowercase , __lowercase ) -> List[str]: '''simple docstring''' _snake_case : Union[str, Any] = pd.DataFrame(__lowercase ) _snake_case : Union[str, Any] = "variation" _snake_case : str = "diff_%" _snake_case : List[str] = nan if base_variation is not None and len(df[df[variation_key] == base_variation] ): # this may still return nan _snake_case : Dict = df.loc[df[variation_key] == base_variation][target_metric_key].item() if math.isnan(__lowercase ): # as a fallback, use the minimal value as the sentinel _snake_case : List[Any] = df.loc[df[target_metric_key] != nan][target_metric_key].min() # create diff column if possible if not math.isnan(__lowercase ): _snake_case : Any = df.apply( lambda __lowercase : round(100 * (r[target_metric_key] - sentinel_value) / sentinel_value ) if not math.isnan(r[target_metric_key] ) else 0 , axis="columns" , ) # re-order columns _snake_case : List[Any] = [variation_key, target_metric_key, diff_key, *report_metric_keys] _snake_case : Optional[int] = df.reindex(__lowercase , axis="columns" ) # reorder cols # capitalize _snake_case : List[str] = df.rename(str.capitalize , axis="columns" ) # make the cols as narrow as possible _snake_case : Tuple = df.rename(lambda __lowercase : c.replace("_" , "<br>" ) , axis="columns" ) _snake_case : Union[str, Any] = df.rename(lambda __lowercase : c.replace("_" , "\n" ) , axis="columns" ) _snake_case : Optional[int] = ["", "Copy between the cut-here-lines and paste as is to github or a forum"] report += ["----------8<-----------------8<--------"] report += ["*** Results:", df_github.to_markdown(index=__lowercase , floatfmt=".2f" )] report += ["```"] report += ["*** Setup:", get_versions()] report += ["*** The benchmark command line was:", get_original_command()] report += ["```"] report += ["----------8<-----------------8<--------"] report += ["*** Results (console):", df_console.to_markdown(index=__lowercase , floatfmt=".2f" )] print("\n\n".join(__lowercase ) ) def snake_case () -> List[str]: '''simple docstring''' _snake_case : int = argparse.ArgumentParser() parser.add_argument( "--base-cmd" , default=__lowercase , type=__lowercase , required=__lowercase , help="Base cmd" , ) parser.add_argument( "--variations" , default=__lowercase , type=__lowercase , nargs="+" , required=__lowercase , help="Multi-dimensional variations, example: '|--fp16|--bf16' '|--tf32'" , ) parser.add_argument( "--base-variation" , default=__lowercase , type=__lowercase , help="Baseline variation to compare to. if None the minimal target value will be used to compare against" , ) parser.add_argument( "--target-metric-key" , default=__lowercase , type=__lowercase , required=__lowercase , help="Target metric key in output_dir/all_results.json, e.g., train_samples_per_second" , ) parser.add_argument( "--report-metric-keys" , default="" , type=__lowercase , help="Report metric keys - other metric keys from output_dir/all_results.json to report, e.g., train_loss. Use a single argument e.g., 'train_loss train_samples" , ) parser.add_argument( "--repeat-times" , default=1 , type=__lowercase , help="How many times to re-run each variation - an average will be reported" , ) parser.add_argument( "--output_dir" , default="output_benchmark" , type=__lowercase , help="The output directory where all the benchmark reports will go to and additionally this directory will be used to override --output_dir in the script that is being benchmarked" , ) parser.add_argument( "--verbose" , default=__lowercase , action="store_true" , help="Whether to show the outputs of each run or just the benchmark progress" , ) _snake_case : Tuple = parser.parse_args() _snake_case : Union[str, Any] = args.output_dir Path(__lowercase ).mkdir(exist_ok=__lowercase ) _snake_case : str = get_base_command(__lowercase , __lowercase ) # split each dimension into its --foo variations _snake_case : Optional[int] = [list(map(str.strip , re.split(r"\|" , __lowercase ) ) ) for x in args.variations] # build a cartesian product of dimensions and convert those back into cmd-line arg strings, # while stripping white space for inputs that were empty _snake_case : Tuple = list(map(str.strip , map(" ".join , itertools.product(*__lowercase ) ) ) ) _snake_case : Union[str, Any] = max(len(__lowercase ) for x in variations ) # split wanted keys _snake_case : Union[str, Any] = args.report_metric_keys.split() # capture prints into a log file for convenience _snake_case : int = F"""benchmark-report-{datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S' )}.txt""" print(F"""\nNote: each run's output is also logged under {output_dir}/log.*.std*.txt""" ) print(F"""and this script's output is also piped into {report_fn}""" ) _snake_case : Optional[Any] = Tee(__lowercase ) print(F"""\n*** Running {len(__lowercase )} benchmarks:""" ) print(F"""Base command: {' '.join(__lowercase )}""" ) _snake_case : Optional[int] = "variation" _snake_case : Any = [] for id, variation in enumerate(tqdm(__lowercase , desc="Total completion: " , leave=__lowercase ) ): _snake_case : Union[str, Any] = base_cmd + variation.split() results.append( process_run( id + 1 , __lowercase , __lowercase , __lowercase , __lowercase , args.target_metric_key , __lowercase , args.repeat_times , __lowercase , args.verbose , ) ) process_results(__lowercase , args.target_metric_key , __lowercase , args.base_variation , __lowercase ) if __name__ == "__main__": main()
284
def snake_case (__lowercase ) -> list[int]: '''simple docstring''' if num <= 0: raise ValueError("Input must be a positive integer" ) _snake_case : Any = [True] * (num + 1) _snake_case : str = 2 while p * p <= num: if primes[p]: for i in range(p * p , num + 1 , __lowercase ): _snake_case : Optional[int] = False p += 1 return [prime for prime in range(2 , num + 1 ) if primes[prime]] if __name__ == "__main__": import doctest doctest.testmod() __SCREAMING_SNAKE_CASE : Any = int(input('Enter a positive integer: ').strip()) print(prime_sieve_eratosthenes(user_num))
284
1
"""simple docstring""" import json import os from functools import lru_cache from typing import List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging __A : Union[str, Any] = logging.get_logger(__name__) __A : Any = {"vocab_file": "vocab.json", "merges_file": "merges.txt"} __A : Any = { "vocab_file": { "allenai/longformer-base-4096": "https://huggingface.co/allenai/longformer-base-4096/resolve/main/vocab.json", "allenai/longformer-large-4096": ( "https://huggingface.co/allenai/longformer-large-4096/resolve/main/vocab.json" ), "allenai/longformer-large-4096-finetuned-triviaqa": ( "https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/vocab.json" ), "allenai/longformer-base-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/vocab.json" ), "allenai/longformer-large-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/vocab.json" ), }, "merges_file": { "allenai/longformer-base-4096": "https://huggingface.co/allenai/longformer-base-4096/resolve/main/merges.txt", "allenai/longformer-large-4096": ( "https://huggingface.co/allenai/longformer-large-4096/resolve/main/merges.txt" ), "allenai/longformer-large-4096-finetuned-triviaqa": ( "https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/merges.txt" ), "allenai/longformer-base-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/merges.txt" ), "allenai/longformer-large-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/merges.txt" ), }, } __A : List[str] = { "allenai/longformer-base-4096": 4096, "allenai/longformer-large-4096": 4096, "allenai/longformer-large-4096-finetuned-triviaqa": 4096, "allenai/longformer-base-4096-extra.pos.embd.only": 4096, "allenai/longformer-large-4096-extra.pos.embd.only": 4096, } @lru_cache() # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode def lowercase ( ): '''simple docstring''' _UpperCAmelCase = ( list(range(ord('''!''' ) , ord('''~''' ) + 1 ) ) + list(range(ord('''¡''' ) , ord('''¬''' ) + 1 ) ) + list(range(ord('''®''' ) , ord('''ÿ''' ) + 1 ) ) ) _UpperCAmelCase = bs[:] _UpperCAmelCase = 0 for b in range(2**8 ): if b not in bs: bs.append(_SCREAMING_SNAKE_CASE ) cs.append(2**8 + n ) n += 1 _UpperCAmelCase = [chr(_SCREAMING_SNAKE_CASE ) for n in cs] return dict(zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) def lowercase ( _SCREAMING_SNAKE_CASE : str ): '''simple docstring''' _UpperCAmelCase = set() _UpperCAmelCase = word[0] for char in word[1:]: pairs.add((prev_char, char) ) _UpperCAmelCase = char return pairs class _a ( lowerCAmelCase): """simple docstring""" UpperCamelCase__ = VOCAB_FILES_NAMES UpperCamelCase__ = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase__ = ["""input_ids""", """attention_mask"""] def __init__( self : Tuple , __UpperCamelCase : str , __UpperCamelCase : int , __UpperCamelCase : Tuple="replace" , __UpperCamelCase : int="<s>" , __UpperCamelCase : Optional[Any]="</s>" , __UpperCamelCase : Optional[Any]="</s>" , __UpperCamelCase : Dict="<s>" , __UpperCamelCase : List[str]="<unk>" , __UpperCamelCase : Tuple="<pad>" , __UpperCamelCase : Any="<mask>" , __UpperCamelCase : List[Any]=False , **__UpperCamelCase : Optional[Any] , )->str: _UpperCAmelCase = AddedToken(__UpperCamelCase , lstrip=__UpperCamelCase , rstrip=__UpperCamelCase ) if isinstance(__UpperCamelCase , __UpperCamelCase ) else bos_token _UpperCAmelCase = AddedToken(__UpperCamelCase , lstrip=__UpperCamelCase , rstrip=__UpperCamelCase ) if isinstance(__UpperCamelCase , __UpperCamelCase ) else eos_token _UpperCAmelCase = AddedToken(__UpperCamelCase , lstrip=__UpperCamelCase , rstrip=__UpperCamelCase ) if isinstance(__UpperCamelCase , __UpperCamelCase ) else sep_token _UpperCAmelCase = AddedToken(__UpperCamelCase , lstrip=__UpperCamelCase , rstrip=__UpperCamelCase ) if isinstance(__UpperCamelCase , __UpperCamelCase ) else cls_token _UpperCAmelCase = AddedToken(__UpperCamelCase , lstrip=__UpperCamelCase , rstrip=__UpperCamelCase ) if isinstance(__UpperCamelCase , __UpperCamelCase ) else unk_token _UpperCAmelCase = AddedToken(__UpperCamelCase , lstrip=__UpperCamelCase , rstrip=__UpperCamelCase ) if isinstance(__UpperCamelCase , __UpperCamelCase ) else pad_token # Mask token behave like a normal word, i.e. include the space before it _UpperCAmelCase = AddedToken(__UpperCamelCase , lstrip=__UpperCamelCase , rstrip=__UpperCamelCase ) if isinstance(__UpperCamelCase , __UpperCamelCase ) else mask_token super().__init__( errors=__UpperCamelCase , bos_token=__UpperCamelCase , eos_token=__UpperCamelCase , unk_token=__UpperCamelCase , sep_token=__UpperCamelCase , cls_token=__UpperCamelCase , pad_token=__UpperCamelCase , mask_token=__UpperCamelCase , add_prefix_space=__UpperCamelCase , **__UpperCamelCase , ) with open(__UpperCamelCase , encoding='''utf-8''' ) as vocab_handle: _UpperCAmelCase = json.load(__UpperCamelCase ) _UpperCAmelCase = {v: k for k, v in self.encoder.items()} _UpperCAmelCase = errors # how to handle errors in decoding _UpperCAmelCase = bytes_to_unicode() _UpperCAmelCase = {v: k for k, v in self.byte_encoder.items()} with open(__UpperCamelCase , encoding='''utf-8''' ) as merges_handle: _UpperCAmelCase = merges_handle.read().split('''\n''' )[1:-1] _UpperCAmelCase = [tuple(merge.split() ) for merge in bpe_merges] _UpperCAmelCase = dict(zip(__UpperCamelCase , range(len(__UpperCamelCase ) ) ) ) _UpperCAmelCase = {} _UpperCAmelCase = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions _UpperCAmelCase = re.compile(r'''\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+''' ) @property def lowercase__ ( self : Any )->List[Any]: return len(self.encoder ) def lowercase__ ( self : str )->Optional[int]: return dict(self.encoder , **self.added_tokens_encoder ) def lowercase__ ( self : Any , __UpperCamelCase : str )->Optional[int]: if token in self.cache: return self.cache[token] _UpperCAmelCase = tuple(__UpperCamelCase ) _UpperCAmelCase = get_pairs(__UpperCamelCase ) if not pairs: return token while True: _UpperCAmelCase = min(__UpperCamelCase , key=lambda __UpperCamelCase : self.bpe_ranks.get(__UpperCamelCase , float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break _UpperCAmelCase , _UpperCAmelCase = bigram _UpperCAmelCase = [] _UpperCAmelCase = 0 while i < len(__UpperCamelCase ): try: _UpperCAmelCase = word.index(__UpperCamelCase , __UpperCamelCase ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) _UpperCAmelCase = j if word[i] == first and i < len(__UpperCamelCase ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 _UpperCAmelCase = tuple(__UpperCamelCase ) _UpperCAmelCase = new_word if len(__UpperCamelCase ) == 1: break else: _UpperCAmelCase = get_pairs(__UpperCamelCase ) _UpperCAmelCase = ''' '''.join(__UpperCamelCase ) _UpperCAmelCase = word return word def lowercase__ ( self : List[Any] , __UpperCamelCase : Union[str, Any] )->Union[str, Any]: _UpperCAmelCase = [] for token in re.findall(self.pat , __UpperCamelCase ): _UpperCAmelCase = ''''''.join( self.byte_encoder[b] for b in token.encode('''utf-8''' ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(__UpperCamelCase ).split(''' ''' ) ) return bpe_tokens def lowercase__ ( self : Tuple , __UpperCamelCase : Dict )->str: return self.encoder.get(__UpperCamelCase , self.encoder.get(self.unk_token ) ) def lowercase__ ( self : List[str] , __UpperCamelCase : List[Any] )->Any: return self.decoder.get(__UpperCamelCase ) def lowercase__ ( self : Optional[int] , __UpperCamelCase : int )->Dict: _UpperCAmelCase = ''''''.join(__UpperCamelCase ) _UpperCAmelCase = bytearray([self.byte_decoder[c] for c in text] ).decode('''utf-8''' , errors=self.errors ) return text def lowercase__ ( self : Union[str, Any] , __UpperCamelCase : str , __UpperCamelCase : Optional[str] = None )->Tuple[str]: if not os.path.isdir(__UpperCamelCase ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return _UpperCAmelCase = os.path.join( __UpperCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) _UpperCAmelCase = os.path.join( __UpperCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(__UpperCamelCase , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=__UpperCamelCase , ensure_ascii=__UpperCamelCase ) + '''\n''' ) _UpperCAmelCase = 0 with open(__UpperCamelCase , '''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 __UpperCamelCase : 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(__UpperCamelCase ) + '''\n''' ) index += 1 return vocab_file, merge_file def lowercase__ ( self : Dict , __UpperCamelCase : List[int] , __UpperCamelCase : Optional[List[int]] = None )->List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] _UpperCAmelCase = [self.cls_token_id] _UpperCAmelCase = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def lowercase__ ( self : Tuple , __UpperCamelCase : List[int] , __UpperCamelCase : Optional[List[int]] = None , __UpperCamelCase : bool = False )->List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__UpperCamelCase , token_ids_a=__UpperCamelCase , already_has_special_tokens=__UpperCamelCase ) if token_ids_a is None: return [1] + ([0] * len(__UpperCamelCase )) + [1] return [1] + ([0] * len(__UpperCamelCase )) + [1, 1] + ([0] * len(__UpperCamelCase )) + [1] def lowercase__ ( self : str , __UpperCamelCase : List[int] , __UpperCamelCase : Optional[List[int]] = None )->List[int]: _UpperCAmelCase = [self.sep_token_id] _UpperCAmelCase = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def lowercase__ ( self : int , __UpperCamelCase : Optional[Any] , __UpperCamelCase : Dict=False , **__UpperCamelCase : Dict )->Union[str, Any]: _UpperCAmelCase = kwargs.pop('''add_prefix_space''' , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(__UpperCamelCase ) > 0 and not text[0].isspace()): _UpperCAmelCase = ''' ''' + text return (text, kwargs)
260
"""simple docstring""" from __future__ import annotations import math def lowercase ( _SCREAMING_SNAKE_CASE : int ): '''simple docstring''' if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(_SCREAMING_SNAKE_CASE ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def lowercase ( _SCREAMING_SNAKE_CASE : int ): '''simple docstring''' _UpperCAmelCase = str(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = [n] for i in range(1 , len(_SCREAMING_SNAKE_CASE ) ): list_nums.append(int(str_num[i:] ) ) list_nums.append(int(str_num[:-i] ) ) return list_nums def lowercase ( _SCREAMING_SNAKE_CASE : int ): '''simple docstring''' if len(str(_SCREAMING_SNAKE_CASE ) ) > 3: if not is_prime(int(str(_SCREAMING_SNAKE_CASE )[-3:] ) ) or not is_prime(int(str(_SCREAMING_SNAKE_CASE )[:3] ) ): return False return True def lowercase ( _SCREAMING_SNAKE_CASE : int = 11 ): '''simple docstring''' _UpperCAmelCase = [] _UpperCAmelCase = 13 while len(_SCREAMING_SNAKE_CASE ) != count: if validate(_SCREAMING_SNAKE_CASE ): _UpperCAmelCase = list_truncated_nums(_SCREAMING_SNAKE_CASE ) if all(is_prime(_SCREAMING_SNAKE_CASE ) for i in list_nums ): list_truncated_primes.append(_SCREAMING_SNAKE_CASE ) num += 2 return list_truncated_primes def lowercase ( ): '''simple docstring''' return sum(compute_truncated_primes(11 ) ) if __name__ == "__main__": print(f'''{sum(compute_truncated_primes(11)) = }''')
260
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { """google/pegasus-large""": """https://huggingface.co/google/pegasus-large/resolve/main/config.json""", # See all PEGASUS models at https://huggingface.co/models?filter=pegasus } class _snake_case (__SCREAMING_SNAKE_CASE): __A : Tuple ="pegasus" __A : Tuple =["past_key_values"] __A : int ={"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"} def __init__( self ,_snake_case=5_02_65 ,_snake_case=10_24 ,_snake_case=12 ,_snake_case=40_96 ,_snake_case=16 ,_snake_case=12 ,_snake_case=40_96 ,_snake_case=16 ,_snake_case=0.0 ,_snake_case=0.0 ,_snake_case=True ,_snake_case=True ,_snake_case="gelu" ,_snake_case=10_24 ,_snake_case=0.1 ,_snake_case=0.0 ,_snake_case=0.0 ,_snake_case=0.02 ,_snake_case=0 ,_snake_case=False ,_snake_case=0 ,_snake_case=1 ,_snake_case=1 ,**_snake_case ,): UpperCAmelCase_ : Dict = vocab_size UpperCAmelCase_ : Optional[int] = max_position_embeddings UpperCAmelCase_ : List[Any] = d_model UpperCAmelCase_ : Optional[int] = encoder_ffn_dim UpperCAmelCase_ : int = encoder_layers UpperCAmelCase_ : Any = encoder_attention_heads UpperCAmelCase_ : Union[str, Any] = decoder_ffn_dim UpperCAmelCase_ : Optional[int] = decoder_layers UpperCAmelCase_ : Dict = decoder_attention_heads UpperCAmelCase_ : Dict = dropout UpperCAmelCase_ : str = attention_dropout UpperCAmelCase_ : Dict = activation_dropout UpperCAmelCase_ : Optional[int] = activation_function UpperCAmelCase_ : str = init_std UpperCAmelCase_ : Any = encoder_layerdrop UpperCAmelCase_ : Optional[int] = decoder_layerdrop UpperCAmelCase_ : Union[str, Any] = use_cache UpperCAmelCase_ : Union[str, Any] = encoder_layers UpperCAmelCase_ : str = scale_embedding # scale factor will be sqrt(d_model) if True super().__init__( pad_token_id=_snake_case ,eos_token_id=_snake_case ,is_encoder_decoder=_snake_case ,decoder_start_token_id=_snake_case ,forced_eos_token_id=_snake_case ,**_snake_case ,) @property def UpperCamelCase__ ( self ): return self.encoder_attention_heads @property def UpperCamelCase__ ( self ): return self.d_model
67
'''simple docstring''' import os from pathlib import Path def a__ ( ) -> Union[str, Any]: """simple docstring""" from torch.utils.cpp_extension import load UpperCAmelCase_ : Union[str, Any] = Path(_SCREAMING_SNAKE_CASE ).resolve().parent.parent.parent / "kernels" / "deformable_detr" UpperCAmelCase_ : Any = [ root / filename for filename in [ "vision.cpp", os.path.join("cpu" , "ms_deform_attn_cpu.cpp" ), os.path.join("cuda" , "ms_deform_attn_cuda.cu" ), ] ] load( "MultiScaleDeformableAttention" , _SCREAMING_SNAKE_CASE , with_cuda=_SCREAMING_SNAKE_CASE , extra_include_paths=[str(_SCREAMING_SNAKE_CASE )] , extra_cflags=["-DWITH_CUDA=1"] , extra_cuda_cflags=[ "-DCUDA_HAS_FP16=1", "-D__CUDA_NO_HALF_OPERATORS__", "-D__CUDA_NO_HALF_CONVERSIONS__", "-D__CUDA_NO_HALF2_OPERATORS__", ] , ) import MultiScaleDeformableAttention as MSDA return MSDA
67
1
"""simple docstring""" from __future__ import annotations def __a ( __lowerCamelCase, __lowerCamelCase ): UpperCAmelCase_ , UpperCAmelCase_ : str = set(__lowerCamelCase ), [start] while stack: UpperCAmelCase_ : Any = stack.pop() explored.add(__lowerCamelCase ) # Differences from BFS: # 1) pop last element instead of first one # 2) add adjacent elements to stack without exploring them for adj in reversed(graph[v] ): if adj not in explored: stack.append(__lowerCamelCase ) return explored _a = { 'A': ['B', 'C', 'D'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F'], 'D': ['B', 'D'], 'E': ['B', 'F'], 'F': ['C', 'E', 'G'], 'G': ['F'], } if __name__ == "__main__": import doctest doctest.testmod() print(depth_first_search(G, 'A'))
61
"""simple docstring""" from ...utils import is_torch_available, is_transformers_available if is_transformers_available() and is_torch_available(): from .pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings, VQDiffusionPipeline
61
1
"""simple docstring""" from ..utils import DummyObject, requires_backends class snake_case_( metaclass=a__ ): __UpperCamelCase = ['''keras_nlp'''] def __init__( self : Optional[Any] , *UpperCamelCase_ : Dict , **UpperCamelCase_ : List[str] ): requires_backends(self , ['''keras_nlp'''] )
354
"""simple docstring""" import warnings from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch from ...models import UNetaDModel from ...schedulers import RePaintScheduler from ...utils import PIL_INTERPOLATION, logging, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput snake_case__ : List[str] = logging.get_logger(__name__) # pylint: disable=invalid-name def _snake_case ( _snake_case : Union[List, PIL.Image.Image, torch.Tensor] ): warnings.warn( '''The preprocess method is deprecated and will be removed in a future version. Please''' ''' use VaeImageProcessor.preprocess instead''' , _snake_case , ) if isinstance(_snake_case , torch.Tensor ): return image elif isinstance(_snake_case , PIL.Image.Image ): lowerCAmelCase : Optional[int] = [image] if isinstance(image[0] , PIL.Image.Image ): lowerCAmelCase, lowerCAmelCase : int = image[0].size lowerCAmelCase, lowerCAmelCase : Optional[int] = (x - x % 8 for x in (w, h)) # resize to integer multiple of 8 lowerCAmelCase : Union[str, Any] = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION['''lanczos'''] ) )[None, :] for i in image] lowerCAmelCase : int = np.concatenate(_snake_case , axis=0 ) lowerCAmelCase : Optional[Any] = np.array(_snake_case ).astype(np.floataa ) / 255.0 lowerCAmelCase : List[Any] = image.transpose(0 , 3 , 1 , 2 ) lowerCAmelCase : List[str] = 2.0 * image - 1.0 lowerCAmelCase : List[Any] = torch.from_numpy(_snake_case ) elif isinstance(image[0] , torch.Tensor ): lowerCAmelCase : Any = torch.cat(_snake_case , dim=0 ) return image def _snake_case ( _snake_case : Union[List, PIL.Image.Image, torch.Tensor] ): if isinstance(_snake_case , torch.Tensor ): return mask elif isinstance(_snake_case , PIL.Image.Image ): lowerCAmelCase : str = [mask] if isinstance(mask[0] , PIL.Image.Image ): lowerCAmelCase, lowerCAmelCase : int = mask[0].size lowerCAmelCase, lowerCAmelCase : Dict = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 lowerCAmelCase : List[str] = [np.array(m.convert('''L''' ).resize((w, h) , resample=PIL_INTERPOLATION['''nearest'''] ) )[None, :] for m in mask] lowerCAmelCase : Optional[int] = np.concatenate(_snake_case , axis=0 ) lowerCAmelCase : Dict = mask.astype(np.floataa ) / 255.0 lowerCAmelCase : List[str] = 0 lowerCAmelCase : Optional[int] = 1 lowerCAmelCase : List[Any] = torch.from_numpy(_snake_case ) elif isinstance(mask[0] , torch.Tensor ): lowerCAmelCase : Optional[int] = torch.cat(_snake_case , dim=0 ) return mask class snake_case_( a__ ): __UpperCamelCase = 42 __UpperCamelCase = 42 def __init__( self : List[Any] , UpperCamelCase_ : List[str] , UpperCamelCase_ : Optional[Any] ): super().__init__() self.register_modules(unet=UpperCamelCase_ , scheduler=UpperCamelCase_ ) @torch.no_grad() def __call__( self : Union[str, Any] , UpperCamelCase_ : Union[torch.Tensor, PIL.Image.Image] , UpperCamelCase_ : Union[torch.Tensor, PIL.Image.Image] , UpperCamelCase_ : int = 2_5_0 , UpperCamelCase_ : float = 0.0 , UpperCamelCase_ : int = 1_0 , UpperCamelCase_ : int = 1_0 , UpperCamelCase_ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCamelCase_ : Optional[str] = "pil" , UpperCamelCase_ : bool = True , ): lowerCAmelCase : Optional[Any] = image lowerCAmelCase : Tuple = _preprocess_image(UpperCamelCase_ ) lowerCAmelCase : int = original_image.to(device=self.device , dtype=self.unet.dtype ) lowerCAmelCase : Optional[Any] = _preprocess_mask(UpperCamelCase_ ) lowerCAmelCase : str = mask_image.to(device=self.device , dtype=self.unet.dtype ) lowerCAmelCase : Union[str, Any] = original_image.shape[0] # sample gaussian noise to begin the loop if isinstance(UpperCamelCase_ , UpperCamelCase_ ) and len(UpperCamelCase_ ) != batch_size: raise ValueError( F'''You have passed a list of generators of length {len(UpperCamelCase_ )}, but requested an effective batch''' F''' size of {batch_size}. Make sure the batch size matches the length of the generators.''' ) lowerCAmelCase : Union[str, Any] = original_image.shape lowerCAmelCase : str = randn_tensor(UpperCamelCase_ , generator=UpperCamelCase_ , device=self.device , dtype=self.unet.dtype ) # set step values self.scheduler.set_timesteps(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , self.device ) lowerCAmelCase : Optional[int] = eta lowerCAmelCase : List[str] = self.scheduler.timesteps[0] + 1 lowerCAmelCase : List[str] = generator[0] if isinstance(UpperCamelCase_ , UpperCamelCase_ ) else generator for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): if t < t_last: # predict the noise residual lowerCAmelCase : Union[str, Any] = self.unet(UpperCamelCase_ , UpperCamelCase_ ).sample # compute previous image: x_t -> x_t-1 lowerCAmelCase : str = self.scheduler.step(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ).prev_sample else: # compute the reverse: x_t-1 -> x_t lowerCAmelCase : Optional[Any] = self.scheduler.undo_step(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase : List[Any] = t lowerCAmelCase : int = (image / 2 + 0.5).clamp(0 , 1 ) lowerCAmelCase : Union[str, Any] = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": lowerCAmelCase : Tuple = self.numpy_to_pil(UpperCamelCase_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=UpperCamelCase_ )
314
0
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class UpperCAmelCase ( a__ , a__ , a__ , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline SCREAMING_SNAKE_CASE = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS SCREAMING_SNAKE_CASE = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS SCREAMING_SNAKE_CASE = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess SCREAMING_SNAKE_CASE = frozenset([] ) def _lowerCAmelCase( self ) -> Tuple: torch.manual_seed(0 ) lowercase__ : Tuple = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=__lowerCAmelCase , ) lowercase__ : Dict = PNDMScheduler(skip_prk_steps=__lowerCAmelCase ) torch.manual_seed(0 ) lowercase__ : Dict = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) lowercase__ : str = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act='''gelu''' , projection_dim=512 , ) lowercase__ : str = CLIPTextModel(__lowerCAmelCase ) lowercase__ : Dict = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) lowercase__ : Union[str, Any] = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''safety_checker''': None, '''feature_extractor''': None, } return components def _lowerCAmelCase( self , __lowerCAmelCase , __lowerCAmelCase=0 ) -> Any: # TODO: use tensor inputs instead of PIL, this is here just to leave the old expected_slices untouched lowercase__ : Optional[Any] = floats_tensor((1, 3, 32, 32) , rng=random.Random(__lowerCAmelCase ) ).to(__lowerCAmelCase ) lowercase__ : List[str] = image.cpu().permute(0 , 2 , 3 , 1 )[0] lowercase__ : Any = Image.fromarray(np.uinta(__lowerCAmelCase ) ).convert('''RGB''' ).resize((64, 64) ) lowercase__ : List[Any] = Image.fromarray(np.uinta(image + 4 ) ).convert('''RGB''' ).resize((64, 64) ) if str(__lowerCAmelCase ).startswith('''mps''' ): lowercase__ : List[str] = torch.manual_seed(__lowerCAmelCase ) else: lowercase__ : Any = torch.Generator(device=__lowerCAmelCase ).manual_seed(__lowerCAmelCase ) lowercase__ : List[str] = { '''prompt''': '''A painting of a squirrel eating a burger''', '''image''': init_image, '''mask_image''': mask_image, '''generator''': generator, '''num_inference_steps''': 2, '''guidance_scale''': 6.0, '''output_type''': '''numpy''', } return inputs def _lowerCAmelCase( self ) -> Optional[int]: lowercase__ : Any = '''cpu''' # ensure determinism for the device-dependent torch.Generator lowercase__ : Any = self.get_dummy_components() lowercase__ : Union[str, Any] = StableDiffusionInpaintPipeline(**__lowerCAmelCase ) lowercase__ : str = sd_pipe.to(__lowerCAmelCase ) sd_pipe.set_progress_bar_config(disable=__lowerCAmelCase ) lowercase__ : str = self.get_dummy_inputs(__lowerCAmelCase ) lowercase__ : Dict = sd_pipe(**__lowerCAmelCase ).images lowercase__ : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) lowercase__ : Optional[Any] = np.array([0.4_7_2_7, 0.5_7_3_5, 0.3_9_4_1, 0.5_4_4_6, 0.5_9_2_6, 0.4_3_9_4, 0.5_0_6_2, 0.4_6_5_4, 0.4_4_7_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _lowerCAmelCase( self ) -> str: super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def _lowerCAmelCase( self ) -> int: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowerCAmelCase( self ) -> str: lowercase__ : Optional[Any] = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/sd2-inpaint/init_image.png''' ) lowercase__ : Dict = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png''' ) lowercase__ : Any = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint''' '''/yellow_cat_sitting_on_a_park_bench.npy''' ) lowercase__ : Dict = '''stabilityai/stable-diffusion-2-inpainting''' lowercase__ : Union[str, Any] = StableDiffusionInpaintPipeline.from_pretrained(__lowerCAmelCase , safety_checker=__lowerCAmelCase ) pipe.to(__lowerCAmelCase ) pipe.set_progress_bar_config(disable=__lowerCAmelCase ) pipe.enable_attention_slicing() lowercase__ : Optional[Any] = '''Face of a yellow cat, high resolution, sitting on a park bench''' lowercase__ : int = torch.manual_seed(0 ) lowercase__ : Union[str, Any] = pipe( prompt=__lowerCAmelCase , image=__lowerCAmelCase , mask_image=__lowerCAmelCase , generator=__lowerCAmelCase , output_type='''np''' , ) lowercase__ : Tuple = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 9E-3 def _lowerCAmelCase( self ) -> str: lowercase__ : List[Any] = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/sd2-inpaint/init_image.png''' ) lowercase__ : Optional[int] = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png''' ) lowercase__ : Any = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint''' '''/yellow_cat_sitting_on_a_park_bench_fp16.npy''' ) lowercase__ : Union[str, Any] = '''stabilityai/stable-diffusion-2-inpainting''' lowercase__ : Tuple = StableDiffusionInpaintPipeline.from_pretrained( __lowerCAmelCase , torch_dtype=torch.floataa , safety_checker=__lowerCAmelCase , ) pipe.to(__lowerCAmelCase ) pipe.set_progress_bar_config(disable=__lowerCAmelCase ) pipe.enable_attention_slicing() lowercase__ : Any = '''Face of a yellow cat, high resolution, sitting on a park bench''' lowercase__ : Tuple = torch.manual_seed(0 ) lowercase__ : Tuple = pipe( prompt=__lowerCAmelCase , image=__lowerCAmelCase , mask_image=__lowerCAmelCase , generator=__lowerCAmelCase , output_type='''np''' , ) lowercase__ : str = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 5E-1 def _lowerCAmelCase( self ) -> Dict: torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() lowercase__ : int = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/sd2-inpaint/init_image.png''' ) lowercase__ : str = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png''' ) lowercase__ : Any = '''stabilityai/stable-diffusion-2-inpainting''' lowercase__ : Optional[Any] = PNDMScheduler.from_pretrained(__lowerCAmelCase , subfolder='''scheduler''' ) lowercase__ : Optional[int] = StableDiffusionInpaintPipeline.from_pretrained( __lowerCAmelCase , safety_checker=__lowerCAmelCase , scheduler=__lowerCAmelCase , torch_dtype=torch.floataa , ) pipe.to(__lowerCAmelCase ) pipe.set_progress_bar_config(disable=__lowerCAmelCase ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() lowercase__ : List[Any] = '''Face of a yellow cat, high resolution, sitting on a park bench''' lowercase__ : Union[str, Any] = torch.manual_seed(0 ) lowercase__ : List[Any] = pipe( prompt=__lowerCAmelCase , image=__lowerCAmelCase , mask_image=__lowerCAmelCase , generator=__lowerCAmelCase , num_inference_steps=2 , output_type='''np''' , ) lowercase__ : Optional[Any] = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.6_5 * 10**9
198
'''simple docstring''' import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing the experiment tracking capability, # and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To help focus on the differences in the code, building `DataLoaders` # was refactored into its own function. # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## __a: Optional[Any] = 16 __a: Any = 32 def __UpperCamelCase ( UpperCAmelCase , UpperCAmelCase = 16 ): lowercase__ : Dict = AutoTokenizer.from_pretrained('''bert-base-cased''' ) lowercase__ : Optional[int] = load_dataset('''glue''' , '''mrpc''' ) def tokenize_function(UpperCAmelCase ): # max_length=None => use the model max length (it's actually the default) lowercase__ : Optional[Any] = tokenizer(examples['''sentence1'''] , examples['''sentence2'''] , truncation=UpperCAmelCase , max_length=UpperCAmelCase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): lowercase__ : List[Any] = datasets.map( UpperCAmelCase , batched=UpperCAmelCase , remove_columns=['''idx''', '''sentence1''', '''sentence2'''] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library lowercase__ : str = tokenized_datasets.rename_column('''label''' , '''labels''' ) def collate_fn(UpperCAmelCase ): # On TPU it's best to pad everything to the same length or training will be very slow. lowercase__ : List[str] = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": lowercase__ : List[str] = 16 elif accelerator.mixed_precision != "no": lowercase__ : Dict = 8 else: lowercase__ : Optional[int] = None return tokenizer.pad( UpperCAmelCase , padding='''longest''' , max_length=UpperCAmelCase , pad_to_multiple_of=UpperCAmelCase , return_tensors='''pt''' , ) # Instantiate dataloaders. lowercase__ : str = DataLoader( tokenized_datasets['''train'''] , shuffle=UpperCAmelCase , collate_fn=UpperCAmelCase , batch_size=UpperCAmelCase ) lowercase__ : Optional[int] = DataLoader( tokenized_datasets['''validation'''] , shuffle=UpperCAmelCase , collate_fn=UpperCAmelCase , batch_size=UpperCAmelCase ) return train_dataloader, eval_dataloader # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""", None) == "1": from accelerate.test_utils.training import mocked_dataloaders __a: Tuple = mocked_dataloaders # noqa: F811 def __UpperCamelCase ( UpperCAmelCase , UpperCAmelCase ): # For testing only if os.environ.get('''TESTING_MOCKED_DATALOADERS''' , UpperCAmelCase ) == "1": lowercase__ : Optional[int] = 2 # Initialize Accelerator # New Code # # We pass in "all" to `log_with` to grab all available trackers in the environment # Note: If using a custom `Tracker` class, should be passed in here such as: # >>> log_with = ["all", MyCustomTrackerClassInstance()] if args.with_tracking: lowercase__ : Union[str, Any] = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , log_with='''all''' , project_dir=args.project_dir ) else: lowercase__ : Any = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs lowercase__ : int = config['''lr'''] lowercase__ : Optional[int] = int(config['''num_epochs'''] ) lowercase__ : Optional[Any] = int(config['''seed'''] ) lowercase__ : int = int(config['''batch_size'''] ) set_seed(UpperCAmelCase ) lowercase__ , lowercase__ : str = get_dataloaders(UpperCAmelCase , UpperCAmelCase ) lowercase__ : Union[str, Any] = evaluate.load('''glue''' , '''mrpc''' ) # If the batch size is too big we use gradient accumulation lowercase__ : Any = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: lowercase__ : Union[str, Any] = batch_size // MAX_GPU_BATCH_SIZE lowercase__ : Any = MAX_GPU_BATCH_SIZE # Instantiate the model (we build the model here so that the seed also control new weights initialization) lowercase__ : Optional[int] = AutoModelForSequenceClassification.from_pretrained('''bert-base-cased''' , return_dict=UpperCAmelCase ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). lowercase__ : List[str] = model.to(accelerator.device ) # Instantiate optimizer lowercase__ : List[Any] = AdamW(params=model.parameters() , lr=UpperCAmelCase ) # Instantiate scheduler lowercase__ : List[str] = get_linear_schedule_with_warmup( optimizer=UpperCAmelCase , num_warmup_steps=100 , num_training_steps=(len(UpperCAmelCase ) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ : List[str] = accelerator.prepare( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) # New Code # # We need to initialize the trackers we use. Overall configurations can also be stored if args.with_tracking: lowercase__ : Optional[Any] = os.path.split(UpperCAmelCase )[-1].split('''.''' )[0] accelerator.init_trackers(UpperCAmelCase , UpperCAmelCase ) # Now we train the model for epoch in range(UpperCAmelCase ): model.train() # New Code # # For our tracking example, we will log the total loss of each epoch if args.with_tracking: lowercase__ : str = 0 for step, batch in enumerate(UpperCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) lowercase__ : List[str] = model(**UpperCAmelCase ) lowercase__ : List[str] = outputs.loss # New Code # if args.with_tracking: total_loss += loss.detach().float() lowercase__ : List[str] = loss / gradient_accumulation_steps accelerator.backward(UpperCAmelCase ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(UpperCAmelCase ): # We could avoid this line since we set the accelerator with `device_placement=True` (the default). batch.to(accelerator.device ) with torch.no_grad(): lowercase__ : List[str] = model(**UpperCAmelCase ) lowercase__ : Optional[int] = outputs.logits.argmax(dim=-1 ) lowercase__ , lowercase__ : Optional[int] = accelerator.gather_for_metrics((predictions, batch['''labels''']) ) metric.add_batch( predictions=UpperCAmelCase , references=UpperCAmelCase , ) lowercase__ : int = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F"""epoch {epoch}:""" , UpperCAmelCase ) # New Code # # To actually log, we call `Accelerator.log` # The values passed can be of `str`, `int`, `float` or `dict` of `str` to `float`/`int` if args.with_tracking: accelerator.log( { '''accuracy''': eval_metric['''accuracy'''], '''f1''': eval_metric['''f1'''], '''train_loss''': total_loss.item() / len(UpperCAmelCase ), '''epoch''': epoch, } , step=UpperCAmelCase , ) # New Code # # When a run is finished, you should call `accelerator.end_training()` # to close all of the open trackers if args.with_tracking: accelerator.end_training() def __UpperCamelCase ( ): lowercase__ : Any = argparse.ArgumentParser(description='''Simple example of training script.''' ) parser.add_argument( '''--mixed_precision''' , type=UpperCAmelCase , default=UpperCAmelCase , choices=['''no''', '''fp16''', '''bf16''', '''fp8'''] , help='''Whether to use mixed precision. Choose''' '''between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.''' '''and an Nvidia Ampere GPU.''' , ) parser.add_argument('''--cpu''' , action='''store_true''' , help='''If passed, will train on the CPU.''' ) parser.add_argument( '''--with_tracking''' , action='''store_true''' , help='''Whether to load in all available experiment trackers from the environment and use them for logging.''' , ) parser.add_argument( '''--project_dir''' , type=UpperCAmelCase , default='''logs''' , help='''Location on where to store experiment tracking logs` and relevent project information''' , ) lowercase__ : str = parser.parse_args() lowercase__ : Tuple = {'''lr''': 2E-5, '''num_epochs''': 3, '''seed''': 42, '''batch_size''': 16} training_function(UpperCAmelCase , UpperCAmelCase ) if __name__ == "__main__": main()
198
1
'''simple docstring''' def lowerCamelCase__ ( __lowerCamelCase : int , __lowerCamelCase : list[int] , __lowerCamelCase : int ): '''simple docstring''' def count_of_possible_combinations(__lowerCamelCase : int ) -> int: if target < 0: return 0 if target == 0: return 1 return sum(count_of_possible_combinations(target - item ) for item in array ) return count_of_possible_combinations(__lowerCamelCase ) def lowerCamelCase__ ( __lowerCamelCase : int , __lowerCamelCase : list[int] , __lowerCamelCase : int ): '''simple docstring''' def count_of_possible_combinations_with_dp_array( __lowerCamelCase : int , __lowerCamelCase : list[int] ) -> int: if target < 0: return 0 if target == 0: return 1 if dp_array[target] != -1: return dp_array[target] _UpperCAmelCase : str =sum( count_of_possible_combinations_with_dp_array(target - item , __lowerCamelCase ) for item in array ) _UpperCAmelCase : Optional[Any] =answer return answer _UpperCAmelCase : int =[-1] * (target + 1) return count_of_possible_combinations_with_dp_array(__lowerCamelCase , __lowerCamelCase ) def lowerCamelCase__ ( __lowerCamelCase : int , __lowerCamelCase : list[int] , __lowerCamelCase : int ): '''simple docstring''' _UpperCAmelCase : Tuple =[0] * (target + 1) _UpperCAmelCase : Dict =1 for i in range(1 , target + 1 ): for j in range(__lowerCamelCase ): if i - array[j] >= 0: dp_array[i] += dp_array[i - array[j]] return dp_array[target] if __name__ == "__main__": import doctest doctest.testmod() lowercase =3 lowercase =5 lowercase =[1, 2, 5] print(combination_sum_iv(n, array, target))
242
'''simple docstring''' import inspect from typing import Optional, Union import numpy as np import PIL import torch from torch.nn import functional as F from torchvision import transforms from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, DPMSolverMultistepScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput from diffusers.utils import ( PIL_INTERPOLATION, randn_tensor, ) def lowerCamelCase__ ( __lowerCamelCase : Any , __lowerCamelCase : List[str] , __lowerCamelCase : Tuple ): '''simple docstring''' if isinstance(__lowerCamelCase , torch.Tensor ): return image elif isinstance(__lowerCamelCase , PIL.Image.Image ): _UpperCAmelCase : List[Any] =[image] if isinstance(image[0] , PIL.Image.Image ): _UpperCAmelCase : List[Any] =[np.array(i.resize((w, h) , resample=PIL_INTERPOLATION['lanczos'] ) )[None, :] for i in image] _UpperCAmelCase : List[str] =np.concatenate(__lowerCamelCase , axis=0 ) _UpperCAmelCase : Optional[Any] =np.array(__lowerCamelCase ).astype(np.floataa ) / 2_55.0 _UpperCAmelCase : List[Any] =image.transpose(0 , 3 , 1 , 2 ) _UpperCAmelCase : str =2.0 * image - 1.0 _UpperCAmelCase : Optional[Any] =torch.from_numpy(__lowerCamelCase ) elif isinstance(image[0] , torch.Tensor ): _UpperCAmelCase : List[Any] =torch.cat(__lowerCamelCase , dim=0 ) return image def lowerCamelCase__ ( __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Any , __lowerCamelCase : Tuple , __lowerCamelCase : Optional[int]=0.99_95 ): '''simple docstring''' if not isinstance(__lowerCamelCase , np.ndarray ): _UpperCAmelCase : Optional[Any] =True _UpperCAmelCase : int =va.device _UpperCAmelCase : List[Any] =va.cpu().numpy() _UpperCAmelCase : Tuple =va.cpu().numpy() _UpperCAmelCase : Any =np.sum(va * va / (np.linalg.norm(__lowerCamelCase ) * np.linalg.norm(__lowerCamelCase )) ) if np.abs(__lowerCamelCase ) > DOT_THRESHOLD: _UpperCAmelCase : Union[str, Any] =(1 - t) * va + t * va else: _UpperCAmelCase : Optional[int] =np.arccos(__lowerCamelCase ) _UpperCAmelCase : Tuple =np.sin(__lowerCamelCase ) _UpperCAmelCase : str =theta_a * t _UpperCAmelCase : List[Any] =np.sin(__lowerCamelCase ) _UpperCAmelCase : List[str] =np.sin(theta_a - theta_t ) / sin_theta_a _UpperCAmelCase : str =sin_theta_t / sin_theta_a _UpperCAmelCase : int =sa * va + sa * va if inputs_are_torch: _UpperCAmelCase : Union[str, Any] =torch.from_numpy(__lowerCamelCase ).to(__lowerCamelCase ) return va def lowerCamelCase__ ( __lowerCamelCase : Optional[Any] , __lowerCamelCase : List[str] ): '''simple docstring''' _UpperCAmelCase : Union[str, Any] =F.normalize(__lowerCamelCase , dim=-1 ) _UpperCAmelCase : List[Any] =F.normalize(__lowerCamelCase , dim=-1 ) return (x - y).norm(dim=-1 ).div(2 ).arcsin().pow(2 ).mul(2 ) def lowerCamelCase__ ( __lowerCamelCase : List[str] , __lowerCamelCase : Union[str, Any] ): '''simple docstring''' for param in model.parameters(): _UpperCAmelCase : Dict =value class __magic_name__ ( lowerCAmelCase ): def __init__( self , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case=None , snake_case=None , snake_case=None , ) -> List[Any]: '''simple docstring''' super().__init__() self.register_modules( vae=snake_case , text_encoder=snake_case , clip_model=snake_case , tokenizer=snake_case , unet=snake_case , scheduler=snake_case , feature_extractor=snake_case , coca_model=snake_case , coca_tokenizer=snake_case , coca_transform=snake_case , ) _UpperCAmelCase : List[Any] =( feature_extractor.size if isinstance(feature_extractor.size , snake_case) else feature_extractor.size['shortest_edge'] ) _UpperCAmelCase : str =transforms.Normalize(mean=feature_extractor.image_mean , std=feature_extractor.image_std) set_requires_grad(self.text_encoder , snake_case) set_requires_grad(self.clip_model , snake_case) def lowerCAmelCase ( self , snake_case = "auto") -> List[Any]: '''simple docstring''' if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory _UpperCAmelCase : Union[str, Any] =self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(snake_case) def lowerCAmelCase ( self) -> int: '''simple docstring''' self.enable_attention_slicing(snake_case) def lowerCAmelCase ( self) -> Tuple: '''simple docstring''' set_requires_grad(self.vae , snake_case) def lowerCAmelCase ( self) -> Union[str, Any]: '''simple docstring''' set_requires_grad(self.vae , snake_case) def lowerCAmelCase ( self) -> List[Any]: '''simple docstring''' set_requires_grad(self.unet , snake_case) def lowerCAmelCase ( self) -> Optional[Any]: '''simple docstring''' set_requires_grad(self.unet , snake_case) def lowerCAmelCase ( self , snake_case , snake_case , snake_case) -> Tuple: '''simple docstring''' # get the original timestep using init_timestep _UpperCAmelCase : Union[str, Any] =min(int(num_inference_steps * strength) , snake_case) _UpperCAmelCase : Any =max(num_inference_steps - init_timestep , 0) _UpperCAmelCase : int =self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def lowerCAmelCase ( self , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case=None) -> Optional[int]: '''simple docstring''' if not isinstance(snake_case , torch.Tensor): raise ValueError(f"`image` has to be of type `torch.Tensor` but is {type(snake_case)}") _UpperCAmelCase : str =image.to(device=snake_case , dtype=snake_case) if isinstance(snake_case , snake_case): _UpperCAmelCase : Optional[Any] =[ self.vae.encode(image[i : i + 1]).latent_dist.sample(generator[i]) for i in range(snake_case) ] _UpperCAmelCase : Tuple =torch.cat(snake_case , dim=0) else: _UpperCAmelCase : List[Any] =self.vae.encode(snake_case).latent_dist.sample(snake_case) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor _UpperCAmelCase : Optional[int] =0.1_82_15 * init_latents _UpperCAmelCase : List[str] =init_latents.repeat_interleave(snake_case , dim=0) _UpperCAmelCase : Union[str, Any] =randn_tensor(init_latents.shape , generator=snake_case , device=snake_case , dtype=snake_case) # get latents _UpperCAmelCase : Optional[int] =self.scheduler.add_noise(snake_case , snake_case , snake_case) _UpperCAmelCase : List[Any] =init_latents return latents def lowerCAmelCase ( self , snake_case) -> List[Any]: '''simple docstring''' _UpperCAmelCase : Union[str, Any] =self.coca_transform(snake_case).unsqueeze(0) with torch.no_grad(), torch.cuda.amp.autocast(): _UpperCAmelCase : str =self.coca_model.generate(transformed_image.to(device=self.device , dtype=self.coca_model.dtype)) _UpperCAmelCase : Tuple =self.coca_tokenizer.decode(generated[0].cpu().numpy()) return generated.split('<end_of_text>')[0].replace('<start_of_text>' , '').rstrip(' .,') def lowerCAmelCase ( self , snake_case , snake_case) -> Optional[int]: '''simple docstring''' _UpperCAmelCase : Any =self.feature_extractor.preprocess(snake_case) _UpperCAmelCase : Optional[Any] =torch.from_numpy(clip_image_input['pixel_values'][0]).unsqueeze(0).to(self.device).half() _UpperCAmelCase : Dict =self.clip_model.get_image_features(snake_case) _UpperCAmelCase : int =image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=snake_case) _UpperCAmelCase : List[str] =image_embeddings_clip.repeat_interleave(snake_case , dim=0) return image_embeddings_clip @torch.enable_grad() def lowerCAmelCase ( self , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , ) -> Optional[Any]: '''simple docstring''' _UpperCAmelCase : Dict =latents.detach().requires_grad_() _UpperCAmelCase : str =self.scheduler.scale_model_input(snake_case , snake_case) # predict the noise residual _UpperCAmelCase : int =self.unet(snake_case , snake_case , encoder_hidden_states=snake_case).sample if isinstance(self.scheduler , (PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler)): _UpperCAmelCase : Optional[int] =self.scheduler.alphas_cumprod[timestep] _UpperCAmelCase : Any =1 - alpha_prod_t # compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf _UpperCAmelCase : str =(latents - beta_prod_t ** 0.5 * noise_pred) / alpha_prod_t ** 0.5 _UpperCAmelCase : Union[str, Any] =torch.sqrt(snake_case) _UpperCAmelCase : List[str] =pred_original_sample * (fac) + latents * (1 - fac) elif isinstance(self.scheduler , snake_case): _UpperCAmelCase : Optional[int] =self.scheduler.sigmas[index] _UpperCAmelCase : Tuple =latents - sigma * noise_pred else: raise ValueError(f"scheduler type {type(self.scheduler)} not supported") # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor _UpperCAmelCase : Tuple =1 / 0.1_82_15 * sample _UpperCAmelCase : Optional[Any] =self.vae.decode(snake_case).sample _UpperCAmelCase : Tuple =(image / 2 + 0.5).clamp(0 , 1) _UpperCAmelCase : int =transforms.Resize(self.feature_extractor_size)(snake_case) _UpperCAmelCase : Optional[int] =self.normalize(snake_case).to(latents.dtype) _UpperCAmelCase : str =self.clip_model.get_image_features(snake_case) _UpperCAmelCase : str =image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=snake_case) _UpperCAmelCase : Optional[int] =spherical_dist_loss(snake_case , snake_case).mean() * clip_guidance_scale _UpperCAmelCase : List[str] =-torch.autograd.grad(snake_case , snake_case)[0] if isinstance(self.scheduler , snake_case): _UpperCAmelCase : Optional[Any] =latents.detach() + grads * (sigma**2) _UpperCAmelCase : str =noise_pred_original else: _UpperCAmelCase : str =noise_pred_original - torch.sqrt(snake_case) * grads return noise_pred, latents @torch.no_grad() def __call__( self , snake_case , snake_case , snake_case = None , snake_case = None , snake_case = 5_1_2 , snake_case = 5_1_2 , snake_case = 0.6 , snake_case = 5_0 , snake_case = 7.5 , snake_case = 1 , snake_case = 0.0 , snake_case = 1_0_0 , snake_case = None , snake_case = "pil" , snake_case = True , snake_case = 0.8 , snake_case = 0.1 , snake_case = 0.1 , ) -> List[str]: '''simple docstring''' if isinstance(snake_case , snake_case) and len(snake_case) != batch_size: raise ValueError(f"You have passed {batch_size} batch_size, but only {len(snake_case)} generators.") if height % 8 != 0 or width % 8 != 0: raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.") if isinstance(snake_case , torch.Generator) and batch_size > 1: _UpperCAmelCase : List[str] =[generator] + [None] * (batch_size - 1) _UpperCAmelCase : Tuple =[ ('model', self.coca_model is None), ('tokenizer', self.coca_tokenizer is None), ('transform', self.coca_transform is None), ] _UpperCAmelCase : Tuple =[x[0] for x in coca_is_none if x[1]] _UpperCAmelCase : Union[str, Any] =', '.join(snake_case) # generate prompts with coca model if prompt is None if content_prompt is None: if len(snake_case): raise ValueError( f"Content prompt is None and CoCa [{coca_is_none_str}] is None." f"Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.") _UpperCAmelCase : Optional[int] =self.get_image_description(snake_case) if style_prompt is None: if len(snake_case): raise ValueError( f"Style prompt is None and CoCa [{coca_is_none_str}] is None." f" Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.") _UpperCAmelCase : List[str] =self.get_image_description(snake_case) # get prompt text embeddings for content and style _UpperCAmelCase : Optional[Any] =self.tokenizer( snake_case , padding='max_length' , max_length=self.tokenizer.model_max_length , truncation=snake_case , return_tensors='pt' , ) _UpperCAmelCase : Dict =self.text_encoder(content_text_input.input_ids.to(self.device))[0] _UpperCAmelCase : Optional[int] =self.tokenizer( snake_case , padding='max_length' , max_length=self.tokenizer.model_max_length , truncation=snake_case , return_tensors='pt' , ) _UpperCAmelCase : Tuple =self.text_encoder(style_text_input.input_ids.to(self.device))[0] _UpperCAmelCase : List[Any] =slerp(snake_case , snake_case , snake_case) # duplicate text embeddings for each generation per prompt _UpperCAmelCase : Optional[Any] =text_embeddings.repeat_interleave(snake_case , dim=0) # set timesteps _UpperCAmelCase : Any ='offset' in set(inspect.signature(self.scheduler.set_timesteps).parameters.keys()) _UpperCAmelCase : int ={} if accepts_offset: _UpperCAmelCase : Union[str, Any] =1 self.scheduler.set_timesteps(snake_case , **snake_case) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand self.scheduler.timesteps.to(self.device) _UpperCAmelCase , _UpperCAmelCase : int =self.get_timesteps(snake_case , snake_case , self.device) _UpperCAmelCase : Dict =timesteps[:1].repeat(snake_case) # Preprocess image _UpperCAmelCase : int =preprocess(snake_case , snake_case , snake_case) _UpperCAmelCase : Tuple =self.prepare_latents( snake_case , snake_case , snake_case , text_embeddings.dtype , self.device , snake_case) _UpperCAmelCase : Optional[Any] =preprocess(snake_case , snake_case , snake_case) _UpperCAmelCase : List[Any] =self.prepare_latents( snake_case , snake_case , snake_case , text_embeddings.dtype , self.device , snake_case) _UpperCAmelCase : List[Any] =slerp(snake_case , snake_case , snake_case) if clip_guidance_scale > 0: _UpperCAmelCase : Optional[int] =self.get_clip_image_embeddings(snake_case , snake_case) _UpperCAmelCase : int =self.get_clip_image_embeddings(snake_case , snake_case) _UpperCAmelCase : Dict =slerp( snake_case , snake_case , snake_case) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. _UpperCAmelCase : int =guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: _UpperCAmelCase : Union[str, Any] =content_text_input.input_ids.shape[-1] _UpperCAmelCase : List[str] =self.tokenizer([''] , padding='max_length' , max_length=snake_case , return_tensors='pt') _UpperCAmelCase : Union[str, Any] =self.text_encoder(uncond_input.input_ids.to(self.device))[0] # duplicate unconditional embeddings for each generation per prompt _UpperCAmelCase : List[Any] =uncond_embeddings.repeat_interleave(snake_case , dim=0) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes _UpperCAmelCase : Any =torch.cat([uncond_embeddings, text_embeddings]) # get the initial random noise unless the user supplied it # Unlike in other pipelines, latents need to be generated in the target device # for 1-to-1 results reproducibility with the CompVis implementation. # However this currently doesn't work in `mps`. _UpperCAmelCase : str =(batch_size, self.unet.config.in_channels, height // 8, width // 8) _UpperCAmelCase : Union[str, Any] =text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not work reproducibly on mps _UpperCAmelCase : int =torch.randn(snake_case , generator=snake_case , device='cpu' , dtype=snake_case).to( self.device) else: _UpperCAmelCase : Optional[int] =torch.randn(snake_case , generator=snake_case , device=self.device , dtype=snake_case) else: if latents.shape != latents_shape: raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {latents_shape}") _UpperCAmelCase : List[str] =latents.to(self.device) # scale the initial noise by the standard deviation required by the scheduler _UpperCAmelCase : str =latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] _UpperCAmelCase : List[str] ='eta' in set(inspect.signature(self.scheduler.step).parameters.keys()) _UpperCAmelCase : Union[str, Any] ={} if accepts_eta: _UpperCAmelCase : Optional[int] =eta # check if the scheduler accepts generator _UpperCAmelCase : Union[str, Any] ='generator' in set(inspect.signature(self.scheduler.step).parameters.keys()) if accepts_generator: _UpperCAmelCase : Dict =generator with self.progress_bar(total=snake_case): for i, t in enumerate(snake_case): # expand the latents if we are doing classifier free guidance _UpperCAmelCase : Dict =torch.cat([latents] * 2) if do_classifier_free_guidance else latents _UpperCAmelCase : Optional[int] =self.scheduler.scale_model_input(snake_case , snake_case) # predict the noise residual _UpperCAmelCase : Optional[int] =self.unet(snake_case , snake_case , encoder_hidden_states=snake_case).sample # perform classifier free guidance if do_classifier_free_guidance: _UpperCAmelCase , _UpperCAmelCase : int =noise_pred.chunk(2) _UpperCAmelCase : Dict =noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # perform clip guidance if clip_guidance_scale > 0: _UpperCAmelCase : Tuple =( text_embeddings.chunk(2)[1] if do_classifier_free_guidance else text_embeddings ) _UpperCAmelCase , _UpperCAmelCase : Optional[int] =self.cond_fn( snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , snake_case , ) # compute the previous noisy sample x_t -> x_t-1 _UpperCAmelCase : List[str] =self.scheduler.step(snake_case , snake_case , snake_case , **snake_case).prev_sample # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor _UpperCAmelCase : Optional[Any] =1 / 0.1_82_15 * latents _UpperCAmelCase : Optional[int] =self.vae.decode(snake_case).sample _UpperCAmelCase : str =(image / 2 + 0.5).clamp(0 , 1) _UpperCAmelCase : Union[str, Any] =image.cpu().permute(0 , 2 , 3 , 1).numpy() if output_type == "pil": _UpperCAmelCase : List[str] =self.numpy_to_pil(snake_case) if not return_dict: return (image, None) return StableDiffusionPipelineOutput(images=snake_case , nsfw_content_detected=snake_case)
242
1
# Copyright 2022 The HuggingFace Team and The OpenBMB Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available snake_case_ = { 'configuration_cpmant': ['CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'CpmAntConfig'], 'tokenization_cpmant': ['CpmAntTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ = [ 'CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST', 'CpmAntForCausalLM', 'CpmAntModel', 'CpmAntPreTrainedModel', ] if TYPE_CHECKING: from .configuration_cpmant import CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP, CpmAntConfig from .tokenization_cpmant import CpmAntTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_cpmant import ( CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST, CpmAntForCausalLM, CpmAntModel, CpmAntPreTrainedModel, ) else: import sys snake_case_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
24
from __future__ import annotations def a__ ( UpperCAmelCase : int , UpperCAmelCase : int ) -> list[str]: if partitions <= 0: raise ValueError('''partitions must be a positive number!''' ) if partitions > number_of_bytes: raise ValueError('''partitions can not > number_of_bytes!''' ) UpperCAmelCase : str = number_of_bytes // partitions UpperCAmelCase : Dict = [] for i in range(UpperCAmelCase ): UpperCAmelCase : int = i * bytes_per_partition + 1 UpperCAmelCase : Optional[int] = ( number_of_bytes if i == partitions - 1 else (i + 1) * bytes_per_partition ) allocation_list.append(f'''{start_bytes}-{end_bytes}''' ) return allocation_list if __name__ == "__main__": import doctest doctest.testmod()
336
0
import logging import os import sys from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import SeqaSeqTrainer from seqaseq_training_args import SeqaSeqTrainingArguments import transformers from transformers import ( AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer, HfArgumentParser, MBartTokenizer, MBartTokenizerFast, set_seed, ) from transformers.trainer_utils import EvaluationStrategy, is_main_process from transformers.training_args import ParallelMode from utils import ( SeqaSeqDataCollator, SeqaSeqDataset, assert_all_frozen, build_compute_metrics_fn, check_output_dir, freeze_embeds, freeze_params, lmap, save_json, use_task_specific_params, write_txt_file, ) snake_case_ = logging.getLogger(__name__) @dataclass class A_ : """simple docstring""" __UpperCamelCase = field( metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""} ) __UpperCamelCase = field( default=A__ , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""} ) __UpperCamelCase = field( default=A__ , metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""} ) __UpperCamelCase = field( default=A__ , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} , ) __UpperCamelCase = field(default=A__ , metadata={"""help""": """Whether tp freeze the encoder."""} ) __UpperCamelCase = field(default=A__ , metadata={"""help""": """Whether to freeze the embeddings."""} ) @dataclass class A_ : """simple docstring""" __UpperCamelCase = field( metadata={"""help""": """The input data dir. Should contain the .tsv files (or other data files) for the task."""} ) __UpperCamelCase = field( default="""summarization""" , metadata={"""help""": """Task name, summarization (or summarization_{dataset} for pegasus) or translation"""} , ) __UpperCamelCase = field( default=10_24 , metadata={ """help""": ( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) __UpperCamelCase = field( default=1_28 , metadata={ """help""": ( """The maximum total sequence length for target text after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) __UpperCamelCase = field( default=1_42 , metadata={ """help""": ( """The maximum total sequence length for validation target text after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded. """ """This argument is also used to override the ``max_length`` param of ``model.generate``, which is used """ """during ``evaluate`` and ``predict``.""" ) } , ) __UpperCamelCase = field( default=1_42 , metadata={ """help""": ( """The maximum total sequence length for test target text after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) __UpperCamelCase = field(default=-1 , metadata={"""help""": """# training examples. -1 means use all."""} ) __UpperCamelCase = field(default=-1 , metadata={"""help""": """# validation examples. -1 means use all."""} ) __UpperCamelCase = field(default=-1 , metadata={"""help""": """# test examples. -1 means use all."""} ) __UpperCamelCase = field(default=A__ , metadata={"""help""": """Source language id for translation."""} ) __UpperCamelCase = field(default=A__ , metadata={"""help""": """Target language id for translation."""} ) __UpperCamelCase = field(default=A__ , metadata={"""help""": """# num_beams to use for evaluation."""} ) __UpperCamelCase = field( default=A__ , metadata={"""help""": """If only pad tokens should be ignored. This assumes that `config.pad_token_id` is defined."""} , ) def _lowerCAmelCase ( lowercase_ , lowercase_ , lowercase_ ): logger.info(F"""***** {split} metrics *****""" ) for key in sorted(metrics.keys() ): logger.info(F""" {key} = {metrics[key]}""" ) save_json(lowercase__ , os.path.join(lowercase__ , F"""{split}_results.json""" ) ) def _lowerCAmelCase ( ): UpperCAmelCase = HfArgumentParser((ModelArguments, DataTrainingArguments, SeqaSeqTrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('.json' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. UpperCAmelCase = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: UpperCAmelCase = parser.parse_args_into_dataclasses() check_output_dir(lowercase__ ) # Setup logging logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( 'Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s' , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.parallel_mode == ParallelMode.DISTRIBUTED ) , training_args.fpaa , ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() logger.info('Training/evaluation parameters %s' , lowercase__ ) # Set seed set_seed(training_args.seed ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. UpperCAmelCase = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) UpperCAmelCase = ("""encoder_layerdrop""", """decoder_layerdrop""", """dropout""", """attention_dropout""") for p in extra_model_params: if getattr(lowercase__ , lowercase__ , lowercase__ ): assert hasattr(lowercase__ , lowercase__ ), F"""({config.__class__.__name__}) doesn't have a `{p}` attribute""" setattr(lowercase__ , lowercase__ , getattr(lowercase__ , lowercase__ ) ) UpperCAmelCase = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) UpperCAmelCase = AutoModelForSeqaSeqLM.from_pretrained( model_args.model_name_or_path , from_tf='.ckpt' in model_args.model_name_or_path , config=lowercase__ , cache_dir=model_args.cache_dir , ) # use task specific params use_task_specific_params(lowercase__ , data_args.task ) # set num_beams for evaluation if data_args.eval_beams is None: UpperCAmelCase = model.config.num_beams # set decoder_start_token_id for MBart if model.config.decoder_start_token_id is None and isinstance(lowercase__ , (MBartTokenizer, MBartTokenizerFast) ): assert ( data_args.tgt_lang is not None and data_args.src_lang is not None ), "mBart requires --tgt_lang and --src_lang" if isinstance(lowercase__ , lowercase__ ): UpperCAmelCase = tokenizer.lang_code_to_id[data_args.tgt_lang] else: UpperCAmelCase = tokenizer.convert_tokens_to_ids(data_args.tgt_lang ) if model_args.freeze_embeds: freeze_embeds(lowercase__ ) if model_args.freeze_encoder: freeze_params(model.get_encoder() ) assert_all_frozen(model.get_encoder() ) UpperCAmelCase = SeqaSeqDataset # Get datasets UpperCAmelCase = ( dataset_class( lowercase__ , type_path='train' , data_dir=data_args.data_dir , n_obs=data_args.n_train , max_target_length=data_args.max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '' , ) if training_args.do_train else None ) UpperCAmelCase = ( dataset_class( lowercase__ , type_path='val' , data_dir=data_args.data_dir , n_obs=data_args.n_val , max_target_length=data_args.val_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '' , ) if training_args.do_eval or training_args.evaluation_strategy != EvaluationStrategy.NO else None ) UpperCAmelCase = ( dataset_class( lowercase__ , type_path='test' , data_dir=data_args.data_dir , n_obs=data_args.n_test , max_target_length=data_args.test_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '' , ) if training_args.do_predict else None ) # Initialize our Trainer UpperCAmelCase = ( build_compute_metrics_fn(data_args.task , lowercase__ ) if training_args.predict_with_generate else None ) UpperCAmelCase = SeqaSeqTrainer( model=lowercase__ , args=lowercase__ , data_args=lowercase__ , train_dataset=lowercase__ , eval_dataset=lowercase__ , data_collator=SeqaSeqDataCollator( lowercase__ , lowercase__ , model.config.decoder_start_token_id , training_args.tpu_num_cores ) , compute_metrics=lowercase__ , tokenizer=lowercase__ , ) UpperCAmelCase = {} # Training if training_args.do_train: logger.info('*** Train ***' ) UpperCAmelCase = trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) UpperCAmelCase = train_result.metrics UpperCAmelCase = data_args.n_train trainer.save_model() # this also saves the tokenizer if trainer.is_world_process_zero(): handle_metrics('train' , lowercase__ , training_args.output_dir ) all_metrics.update(lowercase__ ) # Need to save the state, since Trainer.save_model saves only the tokenizer with the model trainer.state.save_to_json(os.path.join(training_args.output_dir , 'trainer_state.json' ) ) # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) tokenizer.save_pretrained(training_args.output_dir ) # Evaluation if training_args.do_eval: logger.info('*** Evaluate ***' ) UpperCAmelCase = trainer.evaluate(metric_key_prefix='val' ) UpperCAmelCase = data_args.n_val UpperCAmelCase = round(metrics['val_loss'] , 4 ) if trainer.is_world_process_zero(): handle_metrics('val' , lowercase__ , training_args.output_dir ) all_metrics.update(lowercase__ ) if training_args.do_predict: logger.info('*** Predict ***' ) UpperCAmelCase = trainer.predict(test_dataset=lowercase__ , metric_key_prefix='test' ) UpperCAmelCase = test_output.metrics UpperCAmelCase = data_args.n_test if trainer.is_world_process_zero(): UpperCAmelCase = round(metrics['test_loss'] , 4 ) handle_metrics('test' , lowercase__ , training_args.output_dir ) all_metrics.update(lowercase__ ) if training_args.predict_with_generate: UpperCAmelCase = tokenizer.batch_decode( test_output.predictions , skip_special_tokens=lowercase__ , clean_up_tokenization_spaces=lowercase__ ) UpperCAmelCase = lmap(str.strip , lowercase__ ) write_txt_file(lowercase__ , os.path.join(training_args.output_dir , 'test_generations.txt' ) ) if trainer.is_world_process_zero(): save_json(lowercase__ , os.path.join(training_args.output_dir , 'all_results.json' ) ) return all_metrics def _lowerCAmelCase ( lowercase_ ): main() if __name__ == "__main__": main()
351
"""simple docstring""" def _lowerCAmelCase ( lowercase_ ): if not isinstance(lowercase_ , lowercase_ ): UpperCAmelCase = F"""Input value of [number={number}] must be an integer""" raise TypeError(lowercase_ ) if number < 1: UpperCAmelCase = F"""Input value of [number={number}] must be > 0""" raise ValueError(lowercase_ ) UpperCAmelCase = 1 for i in range(1 , lowercase_ ): current_number *= 4 * i - 2 current_number //= i + 1 return current_number if __name__ == "__main__": import doctest doctest.testmod()
181
0
from sklearn.metrics import matthews_corrcoef import datasets A : int = '\nCompute the Matthews correlation coefficient (MCC)\n\nThe Matthews correlation coefficient is used in machine learning as a\nmeasure of the quality of binary and multiclass classifications. It takes\ninto account true and false positives and negatives and is generally\nregarded as a balanced measure which can be used even if the classes are of\nvery different sizes. The MCC is in essence a correlation coefficient value\nbetween -1 and +1. A coefficient of +1 represents a perfect prediction, 0\nan average random prediction and -1 an inverse prediction. The statistic\nis also known as the phi coefficient. [source: Wikipedia]\n' A : Dict = '\nArgs:\n predictions (list of int): Predicted labels, as returned by a model.\n references (list of int): Ground truth labels.\n sample_weight (list of int, float, or bool): Sample weights. Defaults to `None`.\nReturns:\n matthews_correlation (dict containing float): Matthews correlation.\nExamples:\n Example 1, a basic example with only predictions and references as inputs:\n >>> matthews_metric = datasets.load_metric("matthews_correlation")\n >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n ... predictions=[1, 2, 2, 0, 3, 3])\n >>> print(round(results[\'matthews_correlation\'], 2))\n 0.54\n\n Example 2, the same example as above, but also including sample weights:\n >>> matthews_metric = datasets.load_metric("matthews_correlation")\n >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n ... predictions=[1, 2, 2, 0, 3, 3],\n ... sample_weight=[0.5, 3, 1, 1, 1, 2])\n >>> print(round(results[\'matthews_correlation\'], 2))\n 0.1\n\n Example 3, the same example as above, but with sample weights that cause a negative correlation:\n >>> matthews_metric = datasets.load_metric("matthews_correlation")\n >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n ... predictions=[1, 2, 2, 0, 3, 3],\n ... sample_weight=[0.5, 1, 0, 0, 0, 1])\n >>> print(round(results[\'matthews_correlation\'], 2))\n -0.25\n' A : Optional[int] = '\\n@article{scikit-learn,\n title={Scikit-learn: Machine Learning in {P}ython},\n author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.\n and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.\n and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and\n Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},\n journal={Journal of Machine Learning Research},\n volume={12},\n pages={2825--2830},\n year={2011}\n}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __A( datasets.Metric ): def SCREAMING_SNAKE_CASE_ ( self ) -> Any: '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''int32''' ), '''references''': datasets.Value('''int32''' ), } ) , reference_urls=[ '''https://scikit-learn.org/stable/modules/generated/sklearn.metrics.matthews_corrcoef.html''' ] , ) def SCREAMING_SNAKE_CASE_ ( self , _snake_case , _snake_case , _snake_case=None ) -> Any: '''simple docstring''' return { "matthews_correlation": float(matthews_corrcoef(_snake_case , _snake_case , sample_weight=_snake_case ) ), }
6
"""simple docstring""" import importlib import shutil import threading import warnings from typing import List import fsspec import fsspec.asyn from . import compression from .hffilesystem import HfFileSystem _SCREAMING_SNAKE_CASE : Any = importlib.util.find_spec('''s3fs''') is not None if _has_safs: from .safilesystem import SaFileSystem # noqa: F401 _SCREAMING_SNAKE_CASE : List[compression.BaseCompressedFileFileSystem] = [ compression.BzaFileSystem, compression.GzipFileSystem, compression.LzaFileSystem, compression.XzFileSystem, compression.ZstdFileSystem, ] # Register custom filesystems for fs_class in COMPRESSION_FILESYSTEMS + [HfFileSystem]: if fs_class.protocol in fsspec.registry and fsspec.registry[fs_class.protocol] is not fs_class: warnings.warn(F'''A filesystem protocol was already set for {fs_class.protocol} and will be overwritten.''') fsspec.register_implementation(fs_class.protocol, fs_class, clobber=True) def lowerCamelCase__ ( _lowerCamelCase : str ) -> str: if "://" in dataset_path: lowerCamelCase_ = dataset_path.split('://' )[1] return dataset_path def lowerCamelCase__ ( _lowerCamelCase : fsspec.AbstractFileSystem ) -> bool: if fs is not None and fs.protocol != "file": return True else: return False def lowerCamelCase__ ( _lowerCamelCase : fsspec.AbstractFileSystem , _lowerCamelCase : str , _lowerCamelCase : str ) -> int: lowerCamelCase_ = not is_remote_filesystem(_lowerCamelCase ) if is_local: # LocalFileSystem.mv does copy + rm, it is more efficient to simply move a local directory shutil.move(fs._strip_protocol(_lowerCamelCase ) , fs._strip_protocol(_lowerCamelCase ) ) else: fs.mv(_lowerCamelCase , _lowerCamelCase , recursive=_lowerCamelCase ) def lowerCamelCase__ ( ) -> None: if hasattr(fsspec.asyn , 'reset_lock' ): # for future fsspec>2022.05.0 fsspec.asyn.reset_lock() else: lowerCamelCase_ = None lowerCamelCase_ = None lowerCamelCase_ = threading.Lock()
183
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 YolosImageProcessor class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def __init__( self , UpperCAmelCase , UpperCAmelCase=7 , UpperCAmelCase=3 , UpperCAmelCase=30 , UpperCAmelCase=400 , UpperCAmelCase=True , UpperCAmelCase=None , UpperCAmelCase=True , UpperCAmelCase=[0.5, 0.5, 0.5] , UpperCAmelCase=[0.5, 0.5, 0.5] , UpperCAmelCase=True , UpperCAmelCase=1 / 255 , UpperCAmelCase=True , ) -> Optional[int]: '''simple docstring''' lowercase_ = size if size is not None else {"shortest_edge": 18, "longest_edge": 1333} lowercase_ = parent lowercase_ = batch_size lowercase_ = num_channels lowercase_ = min_resolution lowercase_ = max_resolution lowercase_ = do_resize lowercase_ = size lowercase_ = do_normalize lowercase_ = image_mean lowercase_ = image_std lowercase_ = do_rescale lowercase_ = rescale_factor lowercase_ = do_pad def A__ ( self ) -> List[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 A__ ( self , UpperCAmelCase , UpperCAmelCase=False ) -> int: '''simple docstring''' if not batched: lowercase_ = image_inputs[0] if isinstance(UpperCAmelCase , Image.Image ): lowercase_ , lowercase_ = image.size else: lowercase_ , lowercase_ = image.shape[1], image.shape[2] if w < h: lowercase_ = int(self.size["shortest_edge"] * h / w ) lowercase_ = self.size["shortest_edge"] elif w > h: lowercase_ = self.size["shortest_edge"] lowercase_ = int(self.size["shortest_edge"] * w / h ) else: lowercase_ = self.size["shortest_edge"] lowercase_ = self.size["shortest_edge"] else: lowercase_ = [] for image in image_inputs: lowercase_ , lowercase_ = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) lowercase_ = max(UpperCAmelCase , key=lambda UpperCAmelCase : item[0] )[0] lowercase_ = max(UpperCAmelCase , key=lambda UpperCAmelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class __lowerCamelCase ( snake_case_ , unittest.TestCase ): """simple docstring""" lowerCAmelCase__ = YolosImageProcessor if is_vision_available() else None def A__ ( self ) -> Tuple: '''simple docstring''' lowercase_ = YolosImageProcessingTester(self ) @property def A__ ( self ) -> Optional[int]: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def A__ ( self ) -> Optional[int]: '''simple docstring''' lowercase_ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(UpperCAmelCase , "image_mean" ) ) self.assertTrue(hasattr(UpperCAmelCase , "image_std" ) ) self.assertTrue(hasattr(UpperCAmelCase , "do_normalize" ) ) self.assertTrue(hasattr(UpperCAmelCase , "do_resize" ) ) self.assertTrue(hasattr(UpperCAmelCase , "size" ) ) def A__ ( self ) -> Tuple: '''simple docstring''' lowercase_ = 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 , UpperCAmelCase ) lowercase_ = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=UpperCAmelCase ) self.assertEqual(image_processor.size , {"shortest_edge": 42, "longest_edge": 84} ) self.assertEqual(image_processor.do_pad , UpperCAmelCase ) def A__ ( self ) -> Optional[Any]: '''simple docstring''' pass def A__ ( self ) -> Dict: '''simple docstring''' lowercase_ = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowercase_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase , Image.Image ) # Test not batched input lowercase_ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values lowercase_ , lowercase_ = self.image_processor_tester.get_expected_values(UpperCAmelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched lowercase_ , lowercase_ = self.image_processor_tester.get_expected_values(UpperCAmelCase , batched=UpperCAmelCase ) lowercase_ = image_processing(UpperCAmelCase , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def A__ ( self ) -> List[str]: '''simple docstring''' lowercase_ = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowercase_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase , numpify=UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase , np.ndarray ) # Test not batched input lowercase_ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values lowercase_ , lowercase_ = self.image_processor_tester.get_expected_values(UpperCAmelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched lowercase_ = image_processing(UpperCAmelCase , return_tensors="pt" ).pixel_values lowercase_ , lowercase_ = self.image_processor_tester.get_expected_values(UpperCAmelCase , batched=UpperCAmelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def A__ ( self ) -> str: '''simple docstring''' lowercase_ = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowercase_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase , torchify=UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase , torch.Tensor ) # Test not batched input lowercase_ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values lowercase_ , lowercase_ = self.image_processor_tester.get_expected_values(UpperCAmelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched lowercase_ = image_processing(UpperCAmelCase , return_tensors="pt" ).pixel_values lowercase_ , lowercase_ = self.image_processor_tester.get_expected_values(UpperCAmelCase , batched=UpperCAmelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def A__ ( self ) -> Optional[int]: '''simple docstring''' lowercase_ = self.image_processing_class(**self.image_processor_dict ) lowercase_ = self.image_processing_class(do_resize=UpperCAmelCase , do_normalize=UpperCAmelCase , do_rescale=UpperCAmelCase ) # create random PyTorch tensors lowercase_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase , torchify=UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase , torch.Tensor ) # Test whether the method "pad" and calling the image processor return the same tensors lowercase_ = image_processing_a.pad(UpperCAmelCase , return_tensors="pt" ) lowercase_ = image_processing_a(UpperCAmelCase , return_tensors="pt" ) self.assertTrue( torch.allclose(encoded_images_with_method["pixel_values"] , encoded_images["pixel_values"] , atol=1e-4 ) ) @slow def A__ ( self ) -> List[Any]: '''simple docstring''' lowercase_ = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_annotations.txt" , "r" ) as f: lowercase_ = json.loads(f.read() ) lowercase_ = {"image_id": 39769, "annotations": target} # encode them lowercase_ = YolosImageProcessor.from_pretrained("hustvl/yolos-small" ) lowercase_ = image_processing(images=UpperCAmelCase , annotations=UpperCAmelCase , return_tensors="pt" ) # verify pixel values lowercase_ = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding["pixel_values"].shape , UpperCAmelCase ) lowercase_ = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , UpperCAmelCase , atol=1e-4 ) ) # verify area lowercase_ = torch.tensor([5887.9600, 11250.2061, 489353.8438, 837122.7500, 147967.5156, 165732.3438] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , UpperCAmelCase ) ) # verify boxes lowercase_ = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , UpperCAmelCase ) lowercase_ = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , UpperCAmelCase , atol=1e-3 ) ) # verify image_id lowercase_ = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , UpperCAmelCase ) ) # verify is_crowd lowercase_ = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , UpperCAmelCase ) ) # verify class_labels lowercase_ = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , UpperCAmelCase ) ) # verify orig_size lowercase_ = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , UpperCAmelCase ) ) # verify size lowercase_ = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , UpperCAmelCase ) ) @slow def A__ ( self ) -> int: '''simple docstring''' lowercase_ = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt" , "r" ) as f: lowercase_ = json.loads(f.read() ) lowercase_ = {"file_name": "000000039769.png", "image_id": 39769, "segments_info": target} lowercase_ = pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic" ) # encode them lowercase_ = YolosImageProcessor(format="coco_panoptic" ) lowercase_ = image_processing(images=UpperCAmelCase , annotations=UpperCAmelCase , masks_path=UpperCAmelCase , return_tensors="pt" ) # verify pixel values lowercase_ = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding["pixel_values"].shape , UpperCAmelCase ) lowercase_ = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , UpperCAmelCase , atol=1e-4 ) ) # verify area lowercase_ = torch.tensor([147979.6875, 165527.0469, 484638.5938, 11292.9375, 5879.6562, 7634.1147] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , UpperCAmelCase ) ) # verify boxes lowercase_ = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , UpperCAmelCase ) lowercase_ = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , UpperCAmelCase , atol=1e-3 ) ) # verify image_id lowercase_ = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , UpperCAmelCase ) ) # verify is_crowd lowercase_ = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , UpperCAmelCase ) ) # verify class_labels lowercase_ = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , UpperCAmelCase ) ) # verify masks lowercase_ = 822873 self.assertEqual(encoding["labels"][0]["masks"].sum().item() , UpperCAmelCase ) # verify orig_size lowercase_ = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , UpperCAmelCase ) ) # verify size lowercase_ = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , UpperCAmelCase ) )
351
from dataclasses import dataclass from typing import Optional import torch from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .attention import BasicTransformerBlock from .modeling_utils import ModelMixin @dataclass class __lowerCamelCase ( snake_case_ ): """simple docstring""" lowerCAmelCase__ = 42 class __lowerCamelCase ( snake_case_ , snake_case_ ): """simple docstring""" @register_to_config def __init__( self , UpperCAmelCase = 16 , UpperCAmelCase = 88 , UpperCAmelCase = None , UpperCAmelCase = None , UpperCAmelCase = 1 , UpperCAmelCase = 0.0 , UpperCAmelCase = 32 , UpperCAmelCase = None , UpperCAmelCase = False , UpperCAmelCase = None , UpperCAmelCase = "geglu" , UpperCAmelCase = True , UpperCAmelCase = True , ) -> Union[str, Any]: '''simple docstring''' super().__init__() lowercase_ = num_attention_heads lowercase_ = attention_head_dim lowercase_ = num_attention_heads * attention_head_dim lowercase_ = in_channels lowercase_ = torch.nn.GroupNorm(num_groups=UpperCAmelCase , num_channels=UpperCAmelCase , eps=1e-6 , affine=UpperCAmelCase ) lowercase_ = nn.Linear(UpperCAmelCase , UpperCAmelCase ) # 3. Define transformers blocks lowercase_ = nn.ModuleList( [ BasicTransformerBlock( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , dropout=UpperCAmelCase , cross_attention_dim=UpperCAmelCase , activation_fn=UpperCAmelCase , attention_bias=UpperCAmelCase , double_self_attention=UpperCAmelCase , norm_elementwise_affine=UpperCAmelCase , ) for d in range(UpperCAmelCase ) ] ) lowercase_ = nn.Linear(UpperCAmelCase , UpperCAmelCase ) def A__ ( self , UpperCAmelCase , UpperCAmelCase=None , UpperCAmelCase=None , UpperCAmelCase=None , UpperCAmelCase=1 , UpperCAmelCase=None , UpperCAmelCase = True , ) -> Optional[Any]: '''simple docstring''' lowercase_ , lowercase_ , lowercase_ , lowercase_ = hidden_states.shape lowercase_ = batch_frames // num_frames lowercase_ = hidden_states lowercase_ = hidden_states[None, :].reshape(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) lowercase_ = hidden_states.permute(0 , 2 , 1 , 3 , 4 ) lowercase_ = self.norm(UpperCAmelCase ) lowercase_ = hidden_states.permute(0 , 3 , 4 , 2 , 1 ).reshape(batch_size * height * width , UpperCAmelCase , UpperCAmelCase ) lowercase_ = self.proj_in(UpperCAmelCase ) # 2. Blocks for block in self.transformer_blocks: lowercase_ = block( UpperCAmelCase , encoder_hidden_states=UpperCAmelCase , timestep=UpperCAmelCase , cross_attention_kwargs=UpperCAmelCase , class_labels=UpperCAmelCase , ) # 3. Output lowercase_ = self.proj_out(UpperCAmelCase ) lowercase_ = ( hidden_states[None, None, :] .reshape(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) .permute(0 , 3 , 4 , 1 , 2 ) .contiguous() ) lowercase_ = hidden_states.reshape(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) lowercase_ = hidden_states + residual if not return_dict: return (output,) return TransformerTemporalModelOutput(sample=UpperCAmelCase )
297
0
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 A__ : """simple docstring""" def __init__( self , lowercase , lowercase=14 , lowercase=7 , lowercase=True , lowercase=True , lowercase=True , lowercase=True , lowercase=True , lowercase=99 , lowercase=32 , lowercase=5 , lowercase=4 , lowercase=37 , lowercase="gelu" , lowercase=0.1 , lowercase=0.1 , lowercase=512 , lowercase=16 , lowercase=2 , lowercase=0.02 , lowercase=3 , lowercase=4 , lowercase=None , ) -> List[Any]: '''simple docstring''' a__ : Dict = parent a__ : List[Any] = batch_size a__ : Union[str, Any] = seq_length a__ : Optional[Any] = is_training a__ : Dict = use_token_type_ids a__ : Any = use_input_mask a__ : Optional[int] = use_labels a__ : str = use_mc_token_ids a__ : int = vocab_size a__ : Dict = hidden_size a__ : Optional[int] = num_hidden_layers a__ : Optional[Any] = num_attention_heads a__ : Any = intermediate_size a__ : List[Any] = hidden_act a__ : Dict = hidden_dropout_prob a__ : List[str] = attention_probs_dropout_prob a__ : str = max_position_embeddings a__ : str = type_vocab_size a__ : Union[str, Any] = type_sequence_label_size a__ : List[Any] = initializer_range a__ : Dict = num_labels a__ : int = num_choices a__ : Any = scope a__ : Optional[int] = self.vocab_size - 1 def __lowercase ( self) -> Union[str, Any]: '''simple docstring''' a__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) a__ : int = None if self.use_input_mask: a__ : int = random_attention_mask([self.batch_size, self.seq_length]) a__ : List[Any] = None if self.use_token_type_ids: a__ : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size) a__ : Any = None if self.use_mc_token_ids: a__ : Union[str, Any] = ids_tensor([self.batch_size, self.num_choices] , self.seq_length) a__ : Optional[Any] = None a__ : List[Any] = None a__ : Dict = None if self.use_labels: a__ : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size) a__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels) a__ : List[Any] = ids_tensor([self.batch_size] , self.num_choices) a__ : str = self.get_config() a__ : int = 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 __lowercase ( self) -> Dict: '''simple docstring''' 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 __lowercase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , *lowercase) -> Optional[int]: '''simple docstring''' a__ : str = CTRLModel(config=lowercase) model.to(lowercase) model.eval() model(lowercase , token_type_ids=lowercase , head_mask=lowercase) model(lowercase , token_type_ids=lowercase) a__ : str = model(lowercase) 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 __lowercase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , *lowercase) -> str: '''simple docstring''' a__ : Dict = CTRLLMHeadModel(lowercase) model.to(lowercase) model.eval() a__ : Tuple = model(lowercase , token_type_ids=lowercase , labels=lowercase) self.parent.assertEqual(result.loss.shape , ()) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def __lowercase ( self) -> List[str]: '''simple docstring''' a__ : Dict = self.prepare_config_and_inputs() ( ( a__ ) , ( a__ ) , ( a__ ) , ( a__ ) , ( a__ ) , ( a__ ) , ( a__ ) , ( a__ ) , ( a__ ) , ) : Optional[int] = config_and_inputs a__ : Union[str, Any] = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'head_mask': head_mask} return config, inputs_dict def __lowercase ( self , lowercase , lowercase , lowercase , lowercase , *lowercase) -> List[str]: '''simple docstring''' a__ : Any = self.num_labels a__ : List[Any] = CTRLForSequenceClassification(lowercase) model.to(lowercase) model.eval() a__ : str = ids_tensor([self.batch_size] , self.type_sequence_label_size) a__ : Dict = model(lowercase , token_type_ids=lowercase , labels=lowercase) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) @require_torch class A__ ( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ): """simple docstring""" __A : List[str] = (CTRLModel, CTRLLMHeadModel, CTRLForSequenceClassification) if is_torch_available() else () __A : int = (CTRLLMHeadModel,) if is_torch_available() else () __A : Dict = ( { '''feature-extraction''': CTRLModel, '''text-classification''': CTRLForSequenceClassification, '''text-generation''': CTRLLMHeadModel, '''zero-shot''': CTRLForSequenceClassification, } if is_torch_available() else {} ) __A : Union[str, Any] = True __A : Any = False __A : Optional[Any] = False def __lowercase ( self , lowercase , lowercase , lowercase , lowercase , lowercase) -> Any: '''simple docstring''' 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 __lowercase ( self) -> Optional[int]: '''simple docstring''' a__ : Any = CTRLModelTester(self) a__ : Optional[Any] = ConfigTester(self , config_class=lowercase , n_embd=37) def __lowercase ( self) -> List[str]: '''simple docstring''' super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() torch.cuda.empty_cache() def __lowercase ( self) -> List[str]: '''simple docstring''' self.config_tester.run_common_tests() def __lowercase ( self) -> Union[str, Any]: '''simple docstring''' a__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_ctrl_model(*lowercase) def __lowercase ( self) -> Tuple: '''simple docstring''' a__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*lowercase) @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.') def __lowercase ( self) -> Tuple: '''simple docstring''' pass @slow def __lowercase ( self) -> Optional[int]: '''simple docstring''' for model_name in CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a__ : Optional[int] = CTRLModel.from_pretrained(lowercase) self.assertIsNotNone(lowercase) @unittest.skip('The model doesn\'t support left padding') # and it's not used enough to be worth fixing :) def __lowercase ( self) -> Tuple: '''simple docstring''' pass @require_torch class A__ ( unittest.TestCase ): """simple docstring""" def __lowercase ( self) -> Union[str, Any]: '''simple docstring''' super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() torch.cuda.empty_cache() @slow def __lowercase ( self) -> Tuple: '''simple docstring''' a__ : List[Any] = CTRLLMHeadModel.from_pretrained('ctrl') model.to(lowercase) a__ : int = torch.tensor( [[1_1859, 0, 1611, 8]] , dtype=torch.long , device=lowercase) # Legal the president is a__ : List[str] = [ 1_1859, 0, 1611, 8, 5, 150, 2_6449, 2, 19, 348, 469, 3, 2595, 48, 2_0740, 24_6533, 24_6533, 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__ : str = model.generate(lowercase , do_sample=lowercase) self.assertListEqual(output_ids[0].tolist() , lowercase)
99
import math import random def A_ ( A__ , A__ = False ) -> float: if deriv: return value * (1 - value) return 1 / (1 + math.exp(-value )) # Initial Value lowercase : Optional[Any] = 0.02 def A_ ( A__ , A__ ) -> float: a__ : int = float(2 * (random.randint(1 , 100 )) - 1 ) for _ in range(A__ ): # Forward propagation a__ : Union[str, Any] = sigmoid_function(INITIAL_VALUE * weight ) # How much did we miss? a__ : Optional[Any] = (expected / 100) - layer_a # Error delta a__ : Optional[int] = layer_1_error * sigmoid_function(A__ , A__ ) # Update weight weight += INITIAL_VALUE * layer_1_delta return layer_a * 100 if __name__ == "__main__": import doctest doctest.testmod() lowercase : Dict = int(input("""Expected value: """)) lowercase : Dict = int(input("""Number of propagations: """)) print(forward_propagation(expected, number_propagations))
99
1
"""simple docstring""" from __future__ import annotations from typing import Any class SCREAMING_SNAKE_CASE (UpperCAmelCase ): pass class SCREAMING_SNAKE_CASE : def __init__( self : List[str] , a : Any )-> None: """simple docstring""" lowercase__ = data lowercase__ = None def __iter__( self : str )-> Optional[Any]: """simple docstring""" lowercase__ = self lowercase__ = [] while node: if node in visited: raise ContainsLoopError visited.append(a ) yield node.data lowercase__ = node.next_node @property def SCREAMING_SNAKE_CASE_ ( self : Tuple )-> bool: """simple docstring""" try: list(self ) return False except ContainsLoopError: return True if __name__ == "__main__": lowercase_ = Node(1) lowercase_ = Node(2) lowercase_ = Node(3) lowercase_ = Node(4) print(root_node.has_loop) # False lowercase_ = root_node.next_node print(root_node.has_loop) # True lowercase_ = Node(5) lowercase_ = Node(6) lowercase_ = Node(5) lowercase_ = Node(6) print(root_node.has_loop) # False lowercase_ = Node(1) print(root_node.has_loop) # False
353
from collections.abc import Iterator, MutableMapping from dataclasses import dataclass from typing import Generic, TypeVar lowercase_ = TypeVar("""KEY""") lowercase_ = TypeVar("""VAL""") @dataclass(frozen=UpperCAmelCase , slots=UpperCAmelCase ) class SCREAMING_SNAKE_CASE (Generic[KEY, VAL] ): _UpperCamelCase : KEY _UpperCamelCase : VAL class SCREAMING_SNAKE_CASE (_Item ): def __init__( self : Optional[int] )-> None: """simple docstring""" super().__init__(a , a ) def __bool__( self : str )-> bool: """simple docstring""" return False lowercase_ = _DeletedItem() class SCREAMING_SNAKE_CASE (MutableMapping[KEY, VAL] ): def __init__( self : Tuple , a : int = 8 , a : float = 0.75 )-> None: """simple docstring""" lowercase__ = initial_block_size lowercase__ = [None] * initial_block_size assert 0.0 < capacity_factor < 1.0 lowercase__ = capacity_factor lowercase__ = 0 def SCREAMING_SNAKE_CASE_ ( self : Any , a : KEY )-> int: """simple docstring""" return hash(a ) % len(self._buckets ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , a : int )-> int: """simple docstring""" return (ind + 1) % len(self._buckets ) def SCREAMING_SNAKE_CASE_ ( self : Any , a : int , a : KEY , a : VAL )-> bool: """simple docstring""" lowercase__ = self._buckets[ind] if not stored: lowercase__ = _Item(a , a ) self._len += 1 return True elif stored.key == key: lowercase__ = _Item(a , a ) return True else: return False def SCREAMING_SNAKE_CASE_ ( self : str )-> bool: """simple docstring""" lowercase__ = len(self._buckets ) * self._capacity_factor return len(self ) >= int(a ) def SCREAMING_SNAKE_CASE_ ( self : Tuple )-> bool: """simple docstring""" if len(self._buckets ) <= self._initial_block_size: return False lowercase__ = len(self._buckets ) * self._capacity_factor / 2 return len(self ) < limit def SCREAMING_SNAKE_CASE_ ( self : List[str] , a : int )-> None: """simple docstring""" lowercase__ = self._buckets lowercase__ = [None] * new_size lowercase__ = 0 for item in old_buckets: if item: self._add_item(item.key , item.val ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] )-> None: """simple docstring""" self._resize(len(self._buckets ) * 2 ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] )-> None: """simple docstring""" self._resize(len(self._buckets ) // 2 ) def SCREAMING_SNAKE_CASE_ ( self : Any , a : KEY )-> Iterator[int]: """simple docstring""" lowercase__ = self._get_bucket_index(a ) for _ in range(len(self._buckets ) ): yield ind lowercase__ = self._get_next_ind(a ) def SCREAMING_SNAKE_CASE_ ( self : Tuple , a : KEY , a : VAL )-> None: """simple docstring""" for ind in self._iterate_buckets(a ): if self._try_set(a , a , a ): break def __setitem__( self : List[Any] , a : KEY , a : VAL )-> None: """simple docstring""" if self._is_full(): self._size_up() self._add_item(a , a ) def __delitem__( self : str , a : KEY )-> None: """simple docstring""" for ind in self._iterate_buckets(a ): lowercase__ = self._buckets[ind] if item is None: raise KeyError(a ) if item is _deleted: continue if item.key == key: lowercase__ = _deleted self._len -= 1 break if self._is_sparse(): self._size_down() def __getitem__( self : List[str] , a : KEY )-> VAL: """simple docstring""" for ind in self._iterate_buckets(a ): lowercase__ = self._buckets[ind] if item is None: break if item is _deleted: continue if item.key == key: return item.val raise KeyError(a ) def __len__( self : Tuple )-> int: """simple docstring""" return self._len def __iter__( self : int )-> Iterator[KEY]: """simple docstring""" yield from (item.key for item in self._buckets if item) def __repr__( self : Union[str, Any] )-> str: """simple docstring""" lowercase__ = ' ,'.join( f"""{item.key}: {item.val}""" for item in self._buckets if item ) return f"""HashMap({val_string})"""
269
0
'''simple docstring''' import argparse import requests import torch # pip3 install salesforce-lavis # I'm actually installing a slightly modified version: pip3 install git+https://github.com/nielsrogge/LAVIS.git@fix_lavis from lavis.models import load_model_and_preprocess from PIL import Image from transformers import ( AutoTokenizer, BlipaConfig, BlipaForConditionalGeneration, BlipaProcessor, BlipaVisionConfig, BlipImageProcessor, OPTConfig, TaConfig, ) from transformers.utils.constants import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD def __lowerCamelCase ( ) -> Dict: UpperCAmelCase : Union[str, Any] = """https://storage.googleapis.com/sfr-vision-language-research/LAVIS/assets/merlion.png""" UpperCAmelCase : Optional[int] = Image.open(requests.get(_lowercase , stream=_lowercase ).raw ).convert("""RGB""" ) return image def __lowerCamelCase ( _lowercase ) -> int: UpperCAmelCase : List[Any] = [] # fmt: off # vision encoder rename_keys.append(("""visual_encoder.cls_token""", """vision_model.embeddings.class_embedding""") ) rename_keys.append(("""visual_encoder.pos_embed""", """vision_model.embeddings.position_embedding""") ) rename_keys.append(("""visual_encoder.patch_embed.proj.weight""", """vision_model.embeddings.patch_embedding.weight""") ) rename_keys.append(("""visual_encoder.patch_embed.proj.bias""", """vision_model.embeddings.patch_embedding.bias""") ) rename_keys.append(("""ln_vision.weight""", """vision_model.post_layernorm.weight""") ) rename_keys.append(("""ln_vision.bias""", """vision_model.post_layernorm.bias""") ) for i in range(config.vision_config.num_hidden_layers ): rename_keys.append((F'''visual_encoder.blocks.{i}.norm1.weight''', F'''vision_model.encoder.layers.{i}.layer_norm1.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.norm1.bias''', F'''vision_model.encoder.layers.{i}.layer_norm1.bias''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.norm2.weight''', F'''vision_model.encoder.layers.{i}.layer_norm2.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.norm2.bias''', F'''vision_model.encoder.layers.{i}.layer_norm2.bias''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.attn.qkv.weight''', F'''vision_model.encoder.layers.{i}.self_attn.qkv.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.attn.proj.weight''', F'''vision_model.encoder.layers.{i}.self_attn.projection.weight''',) ) rename_keys.append((F'''visual_encoder.blocks.{i}.attn.proj.bias''', F'''vision_model.encoder.layers.{i}.self_attn.projection.bias''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.mlp.fc1.weight''', F'''vision_model.encoder.layers.{i}.mlp.fc1.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.mlp.fc1.bias''', F'''vision_model.encoder.layers.{i}.mlp.fc1.bias''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.mlp.fc2.weight''', F'''vision_model.encoder.layers.{i}.mlp.fc2.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.mlp.fc2.bias''', F'''vision_model.encoder.layers.{i}.mlp.fc2.bias''') ) # QFormer rename_keys.append(("""Qformer.bert.embeddings.LayerNorm.weight""", """qformer.layernorm.weight""") ) rename_keys.append(("""Qformer.bert.embeddings.LayerNorm.bias""", """qformer.layernorm.bias""") ) # fmt: on return rename_keys def __lowerCamelCase ( _lowercase , _lowercase , _lowercase ) -> Dict: UpperCAmelCase : List[Any] = dct.pop(_lowercase ) UpperCAmelCase : Union[str, Any] = val def __lowerCamelCase ( _lowercase , _lowercase ) -> List[str]: for i in range(config.vision_config.num_hidden_layers ): # read in original q and v biases UpperCAmelCase : Any = state_dict.pop(F'''visual_encoder.blocks.{i}.attn.q_bias''' ) UpperCAmelCase : Tuple = state_dict.pop(F'''visual_encoder.blocks.{i}.attn.v_bias''' ) # next, set bias in the state dict UpperCAmelCase : Union[str, Any] = torch.cat((q_bias, torch.zeros_like(_lowercase , requires_grad=_lowercase ), v_bias) ) UpperCAmelCase : Any = qkv_bias def __lowerCamelCase ( _lowercase , _lowercase ) -> str: UpperCAmelCase : Tuple = 3_6_4 if """coco""" in model_name else 2_2_4 UpperCAmelCase : Any = BlipaVisionConfig(image_size=_lowercase ).to_dict() # make sure the models have proper bos_token_id and eos_token_id set (important for generation) # seems like flan-T5 models don't have bos_token_id properly set? if "opt-2.7b" in model_name: UpperCAmelCase : Optional[int] = OPTConfig.from_pretrained("""facebook/opt-2.7b""" , eos_token_id=_lowercase ).to_dict() elif "opt-6.7b" in model_name: UpperCAmelCase : str = OPTConfig.from_pretrained("""facebook/opt-6.7b""" , eos_token_id=_lowercase ).to_dict() elif "t5-xl" in model_name: UpperCAmelCase : Optional[Any] = TaConfig.from_pretrained("""google/flan-t5-xl""" , dense_act_fn="""gelu""" , bos_token_id=1 ).to_dict() elif "t5-xxl" in model_name: UpperCAmelCase : Tuple = TaConfig.from_pretrained("""google/flan-t5-xxl""" , dense_act_fn="""gelu""" , bos_token_id=1 ).to_dict() UpperCAmelCase : Dict = BlipaConfig(vision_config=_lowercase , text_config=_lowercase ) return config, image_size @torch.no_grad() def __lowerCamelCase ( _lowercase , _lowercase=None , _lowercase=False ) -> Dict: UpperCAmelCase : Dict = ( AutoTokenizer.from_pretrained("""facebook/opt-2.7b""" ) if """opt""" in model_name else AutoTokenizer.from_pretrained("""google/flan-t5-xl""" ) ) UpperCAmelCase : int = tokenizer("""\n""" , add_special_tokens=_lowercase ).input_ids[0] UpperCAmelCase , UpperCAmelCase : Any = get_blipa_config(_lowercase , eos_token_id=_lowercase ) UpperCAmelCase : int = BlipaForConditionalGeneration(_lowercase ).eval() UpperCAmelCase : int = { """blip2-opt-2.7b""": ("""blip2_opt""", """pretrain_opt2.7b"""), """blip2-opt-6.7b""": ("""blip2_opt""", """pretrain_opt6.7b"""), """blip2-opt-2.7b-coco""": ("""blip2_opt""", """caption_coco_opt2.7b"""), """blip2-opt-6.7b-coco""": ("""blip2_opt""", """caption_coco_opt6.7b"""), """blip2-flan-t5-xl""": ("""blip2_t5""", """pretrain_flant5xl"""), """blip2-flan-t5-xl-coco""": ("""blip2_t5""", """caption_coco_flant5xl"""), """blip2-flan-t5-xxl""": ("""blip2_t5""", """pretrain_flant5xxl"""), } UpperCAmelCase , UpperCAmelCase : Optional[Any] = model_name_to_original[model_name] # load original model print("""Loading original model...""" ) UpperCAmelCase : Any = """cuda""" if torch.cuda.is_available() else """cpu""" UpperCAmelCase , UpperCAmelCase , UpperCAmelCase : str = load_model_and_preprocess( name=_lowercase , model_type=_lowercase , is_eval=_lowercase , device=_lowercase ) original_model.eval() print("""Done!""" ) # update state dict keys UpperCAmelCase : Optional[int] = original_model.state_dict() UpperCAmelCase : str = create_rename_keys(_lowercase ) for src, dest in rename_keys: rename_key(_lowercase , _lowercase , _lowercase ) # some keys can be renamed efficiently for key, val in state_dict.copy().items(): UpperCAmelCase : int = state_dict.pop(_lowercase ) if key.startswith("""Qformer.bert""" ): UpperCAmelCase : Tuple = key.replace("""Qformer.bert""" , """qformer""" ) if "attention.self" in key: UpperCAmelCase : List[Any] = key.replace("""self""" , """attention""" ) if "opt_proj" in key: UpperCAmelCase : Dict = key.replace("""opt_proj""" , """language_projection""" ) if "t5_proj" in key: UpperCAmelCase : Optional[Any] = key.replace("""t5_proj""" , """language_projection""" ) if key.startswith("""opt""" ): UpperCAmelCase : Dict = key.replace("""opt""" , """language""" ) if key.startswith("""t5""" ): UpperCAmelCase : Any = key.replace("""t5""" , """language""" ) UpperCAmelCase : Tuple = val # read in qv biases read_in_q_v_bias(_lowercase , _lowercase ) UpperCAmelCase , UpperCAmelCase : List[str] = hf_model.load_state_dict(_lowercase , strict=_lowercase ) assert len(_lowercase ) == 0 assert unexpected_keys == ["qformer.embeddings.position_ids"] UpperCAmelCase : List[str] = load_demo_image() UpperCAmelCase : Dict = vis_processors["""eval"""](_lowercase ).unsqueeze(0 ).to(_lowercase ) UpperCAmelCase : Optional[int] = tokenizer(["""\n"""] , return_tensors="""pt""" ).input_ids.to(_lowercase ) # create processor UpperCAmelCase : Union[str, Any] = BlipImageProcessor( size={"""height""": image_size, """width""": image_size} , image_mean=_lowercase , image_std=_lowercase ) UpperCAmelCase : int = BlipaProcessor(image_processor=_lowercase , tokenizer=_lowercase ) UpperCAmelCase : Union[str, Any] = processor(images=_lowercase , return_tensors="""pt""" ).pixel_values.to(_lowercase ) # make sure processor creates exact same pixel values assert torch.allclose(_lowercase , _lowercase ) original_model.to(_lowercase ) hf_model.to(_lowercase ) with torch.no_grad(): if "opt" in model_name: UpperCAmelCase : Optional[Any] = original_model({"""image""": original_pixel_values, """text_input""": [""""""]} ).logits UpperCAmelCase : str = hf_model(_lowercase , _lowercase ).logits else: UpperCAmelCase : Tuple = original_model( {"""image""": original_pixel_values, """text_input""": ["""\n"""], """text_output""": ["""\n"""]} ).logits UpperCAmelCase : List[str] = input_ids.masked_fill(input_ids == tokenizer.pad_token_id , -1_0_0 ) UpperCAmelCase : List[str] = hf_model(_lowercase , _lowercase , labels=_lowercase ).logits assert original_logits.shape == logits.shape print("""First values of original logits:""" , original_logits[0, :3, :3] ) print("""First values of HF logits:""" , logits[0, :3, :3] ) # assert values if model_name == "blip2-flan-t5-xl": UpperCAmelCase : str = torch.tensor( [[-41.5850, -4.4440, -8.9922], [-47.4322, -5.9143, -1.7340]] , device=_lowercase ) assert torch.allclose(logits[0, :3, :3] , _lowercase , atol=1e-4 ) elif model_name == "blip2-flan-t5-xl-coco": UpperCAmelCase : Tuple = torch.tensor( [[-57.0109, -9.8967, -12.6280], [-68.6578, -12.7191, -10.5065]] , device=_lowercase ) else: # cast to same type UpperCAmelCase : Optional[Any] = logits.dtype assert torch.allclose(original_logits.to(_lowercase ) , _lowercase , atol=1e-2 ) print("""Looks ok!""" ) print("""Generating a caption...""" ) UpperCAmelCase : Tuple = """""" UpperCAmelCase : Tuple = tokenizer(_lowercase , return_tensors="""pt""" ).input_ids.to(_lowercase ) UpperCAmelCase : str = original_model.generate({"""image""": original_pixel_values} ) UpperCAmelCase : Optional[int] = hf_model.generate( _lowercase , _lowercase , do_sample=_lowercase , num_beams=5 , max_length=3_0 , min_length=1 , top_p=0.9 , repetition_penalty=1.0 , length_penalty=1.0 , temperature=1 , ) print("""Original generation:""" , _lowercase ) UpperCAmelCase : Optional[int] = input_ids.shape[1] UpperCAmelCase : Optional[Any] = processor.batch_decode(outputs[:, prompt_length:] , skip_special_tokens=_lowercase ) UpperCAmelCase : str = [text.strip() for text in output_text] print("""HF generation:""" , _lowercase ) if pytorch_dump_folder_path is not None: processor.save_pretrained(_lowercase ) hf_model.save_pretrained(_lowercase ) if push_to_hub: processor.push_to_hub(F'''nielsr/{model_name}''' ) hf_model.push_to_hub(F'''nielsr/{model_name}''' ) if __name__ == "__main__": a : Optional[Any] = argparse.ArgumentParser() a : List[str] = [ """blip2-opt-2.7b""", """blip2-opt-6.7b""", """blip2-opt-2.7b-coco""", """blip2-opt-6.7b-coco""", """blip2-flan-t5-xl""", """blip2-flan-t5-xl-coco""", """blip2-flan-t5-xxl""", ] parser.add_argument( """--model_name""", default="""blip2-opt-2.7b""", choices=choices, type=str, help="""Path to hf config.json of model to convert""", ) parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Whether to push the model and processor to the hub after converting""", ) a : List[str] = parser.parse_args() convert_blipa_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
265
'''simple docstring''' from operator import delitem, getitem, setitem import pytest from data_structures.hashing.hash_map import HashMap def __lowerCamelCase ( _lowercase ) -> Optional[Any]: return getitem, k def __lowerCamelCase ( _lowercase , _lowercase ) -> List[str]: return setitem, k, v def __lowerCamelCase ( _lowercase ) -> int: return delitem, k def __lowerCamelCase ( _lowercase , _lowercase , *_lowercase ) -> Optional[Any]: try: return fun(_lowercase , *_lowercase ), None except Exception as e: return None, e a : List[str] = ( _set("""key_a""", """val_a"""), _set("""key_b""", """val_b"""), ) a : List[Any] = [ _set("""key_a""", """val_a"""), _set("""key_a""", """val_b"""), ] a : int = [ _set("""key_a""", """val_a"""), _set("""key_b""", """val_b"""), _del("""key_a"""), _del("""key_b"""), _set("""key_a""", """val_a"""), _del("""key_a"""), ] a : List[Any] = [ _get("""key_a"""), _del("""key_a"""), _set("""key_a""", """val_a"""), _del("""key_a"""), _del("""key_a"""), _get("""key_a"""), ] a : Tuple = [ *[_set(x, x) for x in range(5)], # guaranteed upsize ] a : Optional[Any] = [ *[_set(x, x) for x in range(5)], # guaranteed upsize *[_del(x) for x in range(5)], _set("""key_a""", """val_b"""), ] @pytest.mark.parametrize( """operations""" , ( pytest.param(_add_items , id="""add items""" ), pytest.param(_overwrite_items , id="""overwrite items""" ), pytest.param(_delete_items , id="""delete items""" ), pytest.param(_access_absent_items , id="""access absent items""" ), pytest.param(_add_with_resize_up , id="""add with resize up""" ), pytest.param(_add_with_resize_down , id="""add with resize down""" ), ) , ) def __lowerCamelCase ( _lowercase ) -> Optional[int]: UpperCAmelCase : List[str] = HashMap(initial_block_size=4 ) UpperCAmelCase : Dict = {} for _, (fun, *args) in enumerate(_lowercase ): UpperCAmelCase , UpperCAmelCase : Union[str, Any] = _run_operation(_lowercase , _lowercase , *_lowercase ) UpperCAmelCase , UpperCAmelCase : Any = _run_operation(_lowercase , _lowercase , *_lowercase ) assert my_res == py_res assert str(_lowercase ) == str(_lowercase ) assert set(_lowercase ) == set(_lowercase ) assert len(_lowercase ) == len(_lowercase ) assert set(my.items() ) == set(py.items() ) def __lowerCamelCase ( ) -> List[Any]: def is_public(_lowercase ) -> bool: return not name.startswith("""_""" ) UpperCAmelCase : int = {name for name in dir({} ) if is_public(_lowercase )} UpperCAmelCase : Any = {name for name in dir(HashMap() ) if is_public(_lowercase )} assert dict_public_names > hash_public_names
265
1
import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation lowerCamelCase_ : Any = logging.get_logger(__name__) lowerCamelCase_ : Any = {"""tokenizer_file""": """tokenizer.json"""} lowerCamelCase_ : Tuple = { """tokenizer_file""": { """bigscience/tokenizer""": """https://huggingface.co/bigscience/tokenizer/blob/main/tokenizer.json""", """bigscience/bloom-560m""": """https://huggingface.co/bigscience/bloom-560m/blob/main/tokenizer.json""", """bigscience/bloom-1b1""": """https://huggingface.co/bigscience/bloom-1b1/blob/main/tokenizer.json""", """bigscience/bloom-1b7""": """https://huggingface.co/bigscience/bloom-1b7/blob/main/tokenizer.json""", """bigscience/bloom-3b""": """https://huggingface.co/bigscience/bloom-3b/blob/main/tokenizer.json""", """bigscience/bloom-7b1""": """https://huggingface.co/bigscience/bloom-7b1/blob/main/tokenizer.json""", """bigscience/bloom""": """https://huggingface.co/bigscience/bloom/blob/main/tokenizer.json""", }, } class _UpperCamelCase ( _A ): '''simple docstring''' __UpperCamelCase : str = VOCAB_FILES_NAMES __UpperCamelCase : Optional[Any] = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase : Union[str, Any] = ["""input_ids""", """attention_mask"""] __UpperCamelCase : Dict = None def __init__( self : Any , snake_case_ : Optional[int]=None , snake_case_ : str=None , snake_case_ : Optional[Any]=None , snake_case_ : str="<unk>" , snake_case_ : Optional[Any]="<s>" , snake_case_ : List[Any]="</s>" , snake_case_ : Union[str, Any]="<pad>" , snake_case_ : Any=False , snake_case_ : List[Any]=False , **snake_case_ : Optional[Any] , ): super().__init__( snake_case_ , snake_case_ , tokenizer_file=snake_case_ , unk_token=snake_case_ , bos_token=snake_case_ , eos_token=snake_case_ , pad_token=snake_case_ , add_prefix_space=snake_case_ , clean_up_tokenization_spaces=snake_case_ , **snake_case_ , ) UpperCamelCase_: Tuple = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("""add_prefix_space""" , snake_case_ ) != add_prefix_space: UpperCamelCase_: Union[str, Any] = getattr(snake_case_ , pre_tok_state.pop("""type""" ) ) UpperCamelCase_: List[str] = add_prefix_space UpperCamelCase_: Dict = pre_tok_class(**snake_case_ ) UpperCamelCase_: Dict = add_prefix_space def lowerCAmelCase__ ( self : Union[str, Any] , *snake_case_ : Optional[int] , **snake_case_ : Optional[int] ): UpperCamelCase_: str = kwargs.get("""is_split_into_words""" , snake_case_ ) if not (self.add_prefix_space or not is_split_into_words): raise Exception( f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with''' """ pretokenized inputs.""" ) return super()._batch_encode_plus(*snake_case_ , **snake_case_ ) def lowerCAmelCase__ ( self : Optional[Any] , *snake_case_ : List[Any] , **snake_case_ : Any ): UpperCamelCase_: Union[str, Any] = kwargs.get("""is_split_into_words""" , snake_case_ ) if not (self.add_prefix_space or not is_split_into_words): raise Exception( f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with''' """ pretokenized inputs.""" ) return super()._encode_plus(*snake_case_ , **snake_case_ ) def lowerCAmelCase__ ( self : Dict , snake_case_ : str , snake_case_ : Optional[str] = None ): UpperCamelCase_: Dict = self._tokenizer.model.save(snake_case_ , name=snake_case_ ) return tuple(snake_case_ ) def lowerCAmelCase__ ( self : Dict , snake_case_ : "Conversation" ): UpperCamelCase_: List[Any] = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(snake_case_ , add_special_tokens=snake_case_ ) + [self.eos_token_id] ) if len(snake_case_ ) > self.model_max_length: UpperCamelCase_: Tuple = input_ids[-self.model_max_length :] return input_ids
223
import json import os import tempfile import datasets from utils import generate_example_dataset, get_duration lowerCamelCase_ : Any = 5_00_00 lowerCamelCase_ : Any = 50_00 lowerCamelCase_ , lowerCamelCase_ : Tuple = os.path.split(__file__) lowerCamelCase_ : int = os.path.join(RESULTS_BASEPATH, """results""", RESULTS_FILENAME.replace(""".py""", """.json""")) @get_duration def A__ ( lowerCamelCase , lowerCamelCase ) -> Tuple: for i in range(lowerCamelCase ): UpperCamelCase_: Dict = dataset[i] @get_duration def A__ ( lowerCamelCase , lowerCamelCase , lowerCamelCase ) -> Tuple: for i in range(0 , len(lowerCamelCase ) , lowerCamelCase ): UpperCamelCase_: List[Any] = dataset[i : i + batch_size] @get_duration def A__ ( lowerCamelCase , lowerCamelCase , lowerCamelCase ) -> Any: with dataset.formatted_as(type=lowerCamelCase ): for i in range(lowerCamelCase ): UpperCamelCase_: List[str] = dataset[i] @get_duration def A__ ( lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ) -> Optional[int]: with dataset.formatted_as(type=lowerCamelCase ): for i in range(0 , lowerCamelCase , lowerCamelCase ): UpperCamelCase_: Union[str, Any] = dataset[i : i + batch_size] def A__ ( ) -> Tuple: UpperCamelCase_: int = {"""num examples""": SPEED_TEST_N_EXAMPLES} UpperCamelCase_: Union[str, Any] = [ (read, {"""length""": SMALL_TEST}), (read, {"""length""": SPEED_TEST_N_EXAMPLES}), (read_batch, {"""length""": SPEED_TEST_N_EXAMPLES, """batch_size""": 10}), (read_batch, {"""length""": SPEED_TEST_N_EXAMPLES, """batch_size""": 1_00}), (read_batch, {"""length""": SPEED_TEST_N_EXAMPLES, """batch_size""": 10_00}), (read_formatted, {"""type""": """numpy""", """length""": SMALL_TEST}), (read_formatted, {"""type""": """pandas""", """length""": SMALL_TEST}), (read_formatted, {"""type""": """torch""", """length""": SMALL_TEST}), (read_formatted, {"""type""": """tensorflow""", """length""": SMALL_TEST}), (read_formatted_batch, {"""type""": """numpy""", """length""": SMALL_TEST, """batch_size""": 10}), (read_formatted_batch, {"""type""": """numpy""", """length""": SMALL_TEST, """batch_size""": 10_00}), ] UpperCamelCase_: Tuple = [ (read, {"""length""": SMALL_TEST}), (read, {"""length""": SPEED_TEST_N_EXAMPLES}), (read_batch, {"""length""": SPEED_TEST_N_EXAMPLES, """batch_size""": 10}), (read_batch, {"""length""": SPEED_TEST_N_EXAMPLES, """batch_size""": 1_00}), (read_batch, {"""length""": SPEED_TEST_N_EXAMPLES, """batch_size""": 10_00}), (read_formatted, {"""type""": """numpy""", """length""": SMALL_TEST}), (read_formatted_batch, {"""type""": """numpy""", """length""": SMALL_TEST, """batch_size""": 10}), (read_formatted_batch, {"""type""": """numpy""", """length""": SMALL_TEST, """batch_size""": 10_00}), ] with tempfile.TemporaryDirectory() as tmp_dir: print("""generating dataset""" ) UpperCamelCase_: int = datasets.Features( {"""list""": datasets.Sequence(datasets.Value("""float32""" ) ), """numbers""": datasets.Value("""float32""" )} ) UpperCamelCase_: Optional[int] = generate_example_dataset( os.path.join(lowerCamelCase , """dataset.arrow""" ) , lowerCamelCase , num_examples=lowerCamelCase , seq_shapes={"""list""": (1_00,)} , ) print("""first set of iterations""" ) for func, kwargs in functions: print(func.__name__ , str(lowerCamelCase ) ) UpperCamelCase_: List[Any] = func(lowerCamelCase , **lowerCamelCase ) print("""shuffling dataset""" ) UpperCamelCase_: Dict = dataset.shuffle() print("""Second set of iterations (after shuffling""" ) for func, kwargs in functions_shuffled: print("""shuffled """ , func.__name__ , str(lowerCamelCase ) ) UpperCamelCase_: List[Any] = func( lowerCamelCase , **lowerCamelCase ) with open(lowerCamelCase , """wb""" ) as f: f.write(json.dumps(lowerCamelCase ).encode("""utf-8""" ) ) if __name__ == "__main__": # useful to run the profiler benchmark_iterating()
223
1
"""simple docstring""" import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING lowerCamelCase_ : Dict = { 'facebook/mask2former-swin-small-coco-instance': ( 'https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json' ) # See all Mask2Former models at https://huggingface.co/models?filter=mask2former } lowerCamelCase_ : List[Any] = logging.get_logger(__name__) class _UpperCAmelCase ( UpperCAmelCase__ ): '''simple docstring''' lowercase_ : Optional[int] = """mask2former""" lowercase_ : Union[str, Any] = ["""swin"""] lowercase_ : Optional[Any] = {"""hidden_size""": """hidden_dim"""} def __init__( self , snake_case_ = None , snake_case_ = 2_5_6 , snake_case_ = 2_5_6 , snake_case_ = 2_5_6 , snake_case_ = 1_0_2_4 , snake_case_ = "relu" , snake_case_ = 6 , snake_case_ = 1_0 , snake_case_ = 8 , snake_case_ = 0.0 , snake_case_ = 2_0_4_8 , snake_case_ = False , snake_case_ = False , snake_case_ = 4 , snake_case_ = 2_5_5 , snake_case_ = 1_0_0 , snake_case_ = 0.1 , snake_case_ = 2.0 , snake_case_ = 5.0 , snake_case_ = 5.0 , snake_case_ = 1_2_5_4_4 , snake_case_ = 3.0 , snake_case_ = 0.75 , snake_case_ = 0.02 , snake_case_ = 1.0 , snake_case_ = True , snake_case_ = [4, 8, 1_6, 3_2] , snake_case_ = None , **snake_case_ , ): """simple docstring""" if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.' ) A_ : Tuple = CONFIG_MAPPING['swin']( image_size=2_2_4 , in_channels=3 , patch_size=4 , embed_dim=9_6 , depths=[2, 2, 1_8, 2] , num_heads=[3, 6, 1_2, 2_4] , window_size=7 , drop_path_rate=0.3 , use_absolute_embeddings=snake_case_ , out_features=['stage1', 'stage2', 'stage3', 'stage4'] , ) if isinstance(snake_case_ , snake_case_ ): A_ : Optional[int] = backbone_config.pop('model_type' ) A_ : List[str] = CONFIG_MAPPING[backbone_model_type] A_ : List[str] = config_class.from_dict(snake_case_ ) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( F"""Backbone {backbone_config.model_type} is not a supported model and may not be compatible with Mask2Former. """ F"""Supported model types: {",".join(self.backbones_supported )}""" ) A_ : Tuple = backbone_config A_ : Any = feature_size A_ : int = mask_feature_size A_ : Tuple = hidden_dim A_ : int = encoder_feedforward_dim A_ : Optional[Any] = activation_function A_ : Optional[Any] = encoder_layers A_ : Optional[Any] = decoder_layers A_ : List[str] = num_attention_heads A_ : Dict = dropout A_ : List[str] = dim_feedforward A_ : Tuple = pre_norm A_ : List[str] = enforce_input_projection A_ : str = common_stride A_ : int = ignore_value A_ : Optional[int] = num_queries A_ : List[Any] = no_object_weight A_ : str = class_weight A_ : List[str] = mask_weight A_ : Optional[Any] = dice_weight A_ : List[str] = train_num_points A_ : Any = oversample_ratio A_ : List[str] = importance_sample_ratio A_ : int = init_std A_ : Tuple = init_xavier_std A_ : int = use_auxiliary_loss A_ : List[str] = feature_strides A_ : List[str] = output_auxiliary_logits A_ : Tuple = decoder_layers super().__init__(**snake_case_ ) @classmethod def lowerCamelCase_ ( cls , snake_case_ , **snake_case_ ): """simple docstring""" return cls( backbone_config=snake_case_ , **snake_case_ , ) def lowerCamelCase_ ( self ): """simple docstring""" A_ : Tuple = copy.deepcopy(self.__dict__ ) A_ : Union[str, Any] = self.backbone_config.to_dict() A_ : Optional[int] = self.__class__.model_type return output
286
"""simple docstring""" import gzip import hashlib import json import multiprocessing import os import re import shutil import time from pathlib import Path import numpy as np from arguments import PreprocessingArguments from datasets import load_dataset from minhash_deduplication import deduplicate_dataset from transformers import AutoTokenizer, HfArgumentParser lowerCamelCase_ : Any = re.compile(r'\s+') def UpperCAmelCase__ ( _UpperCAmelCase ): """simple docstring""" return {"hash": hashlib.mda(re.sub(_UpperCAmelCase , '' , example['content'] ).encode('utf-8' ) ).hexdigest()} def UpperCAmelCase__ ( _UpperCAmelCase ): """simple docstring""" A_ : List[str] = [len(_UpperCAmelCase ) for line in example['content'].splitlines()] return {"line_mean": np.mean(_UpperCAmelCase ), "line_max": max(_UpperCAmelCase )} def UpperCAmelCase__ ( _UpperCAmelCase ): """simple docstring""" A_ : Any = np.mean([c.isalnum() for c in example['content']] ) return {"alpha_frac": alpha_frac} def UpperCAmelCase__ ( _UpperCAmelCase , _UpperCAmelCase ): """simple docstring""" if example["hash"] in uniques: uniques.remove(example['hash'] ) return True else: return False def UpperCAmelCase__ ( _UpperCAmelCase , _UpperCAmelCase=5 ): """simple docstring""" A_ : Optional[int] = ['auto-generated', 'autogenerated', 'automatically generated'] A_ : List[str] = example['content'].splitlines() for _, line in zip(range(_UpperCAmelCase ) , _UpperCAmelCase ): for keyword in keywords: if keyword in line.lower(): return {"autogenerated": True} else: return {"autogenerated": False} def UpperCAmelCase__ ( _UpperCAmelCase , _UpperCAmelCase=5 , _UpperCAmelCase=0.05 ): """simple docstring""" A_ : Any = ['unit tests', 'test file', 'configuration file'] A_ : Dict = example['content'].splitlines() A_ : List[Any] = 0 A_ : str = 0 # first test for _, line in zip(range(_UpperCAmelCase ) , _UpperCAmelCase ): for keyword in keywords: if keyword in line.lower(): return {"config_or_test": True} # second test A_ : Tuple = example['content'].count('\n' ) A_ : Tuple = int(coeff * nlines ) for line in lines: count_config += line.lower().count('config' ) count_test += line.lower().count('test' ) if count_config > threshold or count_test > threshold: return {"config_or_test": True} return {"config_or_test": False} def UpperCAmelCase__ ( _UpperCAmelCase ): """simple docstring""" A_ : List[Any] = ['def ', 'class ', 'for ', 'while '] A_ : Tuple = example['content'].splitlines() for line in lines: for keyword in keywords: if keyword in line.lower(): return {"has_no_keywords": False} return {"has_no_keywords": True} def UpperCAmelCase__ ( _UpperCAmelCase , _UpperCAmelCase=4 ): """simple docstring""" A_ : Union[str, Any] = example['content'].splitlines() A_ : Any = 0 for line in lines: counter += line.lower().count('=' ) if counter > minimum: return {"has_few_assignments": False} return {"has_few_assignments": True} def UpperCAmelCase__ ( _UpperCAmelCase ): """simple docstring""" A_ : Optional[Any] = tokenizer(example['content'] , truncation=_UpperCAmelCase )['input_ids'] A_ : Dict = len(example['content'] ) / len(_UpperCAmelCase ) return {"ratio": ratio} def UpperCAmelCase__ ( _UpperCAmelCase ): """simple docstring""" A_ : Any = {} results.update(get_hash(_UpperCAmelCase ) ) results.update(line_stats(_UpperCAmelCase ) ) results.update(alpha_stats(_UpperCAmelCase ) ) results.update(char_token_ratio(_UpperCAmelCase ) ) results.update(is_autogenerated(_UpperCAmelCase ) ) results.update(is_config_or_test(_UpperCAmelCase ) ) results.update(has_no_keywords(_UpperCAmelCase ) ) results.update(has_few_assignments(_UpperCAmelCase ) ) return results def UpperCAmelCase__ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): """simple docstring""" if not check_uniques(_UpperCAmelCase , _UpperCAmelCase ): return False elif example["autogenerated"]: return False elif example["line_max"] > args.line_max: return False elif example["line_mean"] > args.line_mean: return False elif example["alpha_frac"] < args.alpha_frac: return False elif example["ratio"] < args.min_token_ratio: return False elif example["config_or_test"] and np.random.rand() <= args.filter_proba: return False elif example["has_no_keywords"] and np.random.rand() <= args.filter_proba: return False elif example["has_few_assignments"]: return False else: return True def UpperCAmelCase__ ( _UpperCAmelCase ): """simple docstring""" with open(_UpperCAmelCase , 'rb' ) as f_in: with gzip.open(str(_UpperCAmelCase ) + '.gz' , 'wb' , compresslevel=6 ) as f_out: shutil.copyfileobj(_UpperCAmelCase , _UpperCAmelCase ) os.unlink(_UpperCAmelCase ) # Settings lowerCamelCase_ : Optional[int] = HfArgumentParser(PreprocessingArguments) lowerCamelCase_ : Optional[Any] = parser.parse_args() if args.num_workers is None: lowerCamelCase_ : int = multiprocessing.cpu_count() lowerCamelCase_ : Tuple = AutoTokenizer.from_pretrained(args.tokenizer_dir) # Load dataset lowerCamelCase_ : Tuple = time.time() lowerCamelCase_ : Tuple = load_dataset(args.dataset_name, split='train') print(F"Time to load dataset: {time.time()-t_start:.2f}") # Run preprocessing lowerCamelCase_ : List[str] = time.time() lowerCamelCase_ : Optional[int] = ds.map(preprocess, num_proc=args.num_workers) print(F"Time to preprocess dataset: {time.time()-t_start:.2f}") # Deduplicate hashes lowerCamelCase_ : int = set(ds.unique('hash')) lowerCamelCase_ : Union[str, Any] = len(uniques) / len(ds) print(F"Fraction of duplicates: {1-frac:.2%}") # Deduplicate data and apply heuristics lowerCamelCase_ : Optional[int] = time.time() lowerCamelCase_ : Tuple = ds.filter(filter, fn_kwargs={'uniques': uniques, 'args': args}) print(F"Time to filter dataset: {time.time()-t_start:.2f}") print(F"Size of filtered dataset: {len(ds_filter)}") # Deduplicate with minhash and jaccard similarity if args.near_deduplication: lowerCamelCase_ : Union[str, Any] = time.time() lowerCamelCase_ , lowerCamelCase_ : str = deduplicate_dataset(ds_filter, args.jaccard_threshold) print(F"Time to deduplicate dataset: {time.time()-t_start:.2f}") print(F"Size of deduplicate dataset: {len(ds_filter)}") # Save data in batches of samples_per_file lowerCamelCase_ : Tuple = Path(args.output_dir) output_dir.mkdir(exist_ok=True) # save duplicate_clusters in the output_dir as artifacts # not sure it is the right place the save it if args.near_deduplication: with open(output_dir / 'duplicate_clusters.json', 'w') as f: json.dump(duplicate_clusters, f) lowerCamelCase_ : Optional[Any] = output_dir / 'data' data_dir.mkdir(exist_ok=True) lowerCamelCase_ : List[str] = time.time() for file_number, index in enumerate(range(0, len(ds_filter), args.samples_per_file)): lowerCamelCase_ : Optional[int] = str(data_dir / F"file-{file_number+1:012}.json") lowerCamelCase_ : List[str] = min(len(ds_filter), index + args.samples_per_file) ds_filter.select(list(range(index, end_index))).to_json(file_path) compress_file(file_path) print(F"Time to save dataset: {time.time()-t_start:.2f}")
286
1
"""simple docstring""" from __future__ import annotations import math def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> int: if depth < 0: raise ValueError("""Depth cannot be less than 0""" ) if not scores: raise ValueError("""Scores cannot be empty""" ) if depth == height: return scores[node_index] return ( max( minimax(depth + 1 , node_index * 2 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , minimax(depth + 1 , node_index * 2 + 1 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , ) if is_max else min( minimax(depth + 1 , node_index * 2 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , minimax(depth + 1 , node_index * 2 + 1 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , ) ) def _lowercase ( ) -> None: SCREAMING_SNAKE_CASE__ : List[Any] = [90, 23, 6, 33, 21, 65, 123, 3_4423] SCREAMING_SNAKE_CASE__ : str = math.log(len(SCREAMING_SNAKE_CASE_ ) , 2 ) print(F'''Optimal value : {minimax(0 , 0 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )}''' ) if __name__ == "__main__": import doctest doctest.testmod() main()
365
"""simple docstring""" from __future__ import annotations from PIL import Image # Define glider example a :str = [ [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], ] # Define blinker example a :Dict = [[0, 1, 0], [0, 1, 0], [0, 1, 0]] def _lowercase ( __lowerCAmelCase ) -> list[list[int]]: SCREAMING_SNAKE_CASE__ : Optional[Any] = [] for i in range(len(__lowerCAmelCase ) ): SCREAMING_SNAKE_CASE__ : Any = [] for j in range(len(cells[i] ) ): # Get the number of live neighbours SCREAMING_SNAKE_CASE__ : List[str] = 0 if i > 0 and j > 0: neighbour_count += cells[i - 1][j - 1] if i > 0: neighbour_count += cells[i - 1][j] if i > 0 and j < len(cells[i] ) - 1: neighbour_count += cells[i - 1][j + 1] if j > 0: neighbour_count += cells[i][j - 1] if j < len(cells[i] ) - 1: neighbour_count += cells[i][j + 1] if i < len(__lowerCAmelCase ) - 1 and j > 0: neighbour_count += cells[i + 1][j - 1] if i < len(__lowerCAmelCase ) - 1: neighbour_count += cells[i + 1][j] if i < len(__lowerCAmelCase ) - 1 and j < len(cells[i] ) - 1: neighbour_count += cells[i + 1][j + 1] # Rules of the game of life (excerpt from Wikipedia): # 1. Any live cell with two or three live neighbours survives. # 2. Any dead cell with three live neighbours becomes a live cell. # 3. All other live cells die in the next generation. # Similarly, all other dead cells stay dead. SCREAMING_SNAKE_CASE__ : Dict = cells[i][j] == 1 if ( (alive and 2 <= neighbour_count <= 3) or not alive and neighbour_count == 3 ): next_generation_row.append(1 ) else: next_generation_row.append(0 ) next_generation.append(__lowerCAmelCase ) return next_generation def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> list[Image.Image]: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] for _ in range(__lowerCAmelCase ): # Create output image SCREAMING_SNAKE_CASE__ : int = Image.new("""RGB""" , (len(cells[0] ), len(__lowerCAmelCase )) ) SCREAMING_SNAKE_CASE__ : List[Any] = img.load() # Save cells to image for x in range(len(__lowerCAmelCase ) ): for y in range(len(cells[0] ) ): SCREAMING_SNAKE_CASE__ : str = 255 - cells[y][x] * 255 SCREAMING_SNAKE_CASE__ : Optional[Any] = (colour, colour, colour) # Save image images.append(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = new_generation(__lowerCAmelCase ) return images if __name__ == "__main__": a :Dict = generate_images(GLIDER, 16) images[0].save("out.gif", save_all=True, append_images=images[1:])
56
0
from __future__ import annotations def SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ) -> list[int]: # This function is recursive '''simple docstring''' lowerCAmelCase : Optional[Any] = len(SCREAMING_SNAKE_CASE__ ) # If the array contains only one element, we return it (it's the stop condition of # recursion) if array_length <= 1: return array # Else lowerCAmelCase : Dict = array[0] lowerCAmelCase : Union[str, Any] = False lowerCAmelCase : List[str] = 1 lowerCAmelCase : list[int] = [] while not is_found and i < array_length: if array[i] < pivot: lowerCAmelCase : Tuple = True lowerCAmelCase : Tuple = [element for element in array[i:] if element >= array[i]] lowerCAmelCase : str = longest_subsequence(SCREAMING_SNAKE_CASE__ ) if len(SCREAMING_SNAKE_CASE__ ) > len(SCREAMING_SNAKE_CASE__ ): lowerCAmelCase : Dict = temp_array else: i += 1 lowerCAmelCase : Any = [element for element in array[1:] if element >= pivot] lowerCAmelCase : Dict = [pivot, *longest_subsequence(SCREAMING_SNAKE_CASE__ )] if len(SCREAMING_SNAKE_CASE__ ) > len(SCREAMING_SNAKE_CASE__ ): return temp_array else: return longest_subseq if __name__ == "__main__": import doctest doctest.testmod()
138
import argparse import json from collections import OrderedDict import torch from huggingface_hub import cached_download, hf_hub_url from transformers import AutoImageProcessor, CvtConfig, CvtForImageClassification def _snake_case( SCREAMING_SNAKE_CASE__ ) -> Tuple: lowercase : Union[str, Any] = [] embed.append( ( f"cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.weight", f"stage{idx}.patch_embed.proj.weight", ) ) embed.append( ( f"cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.bias", f"stage{idx}.patch_embed.proj.bias", ) ) embed.append( ( f"cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.weight", f"stage{idx}.patch_embed.norm.weight", ) ) embed.append( ( f"cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.bias", f"stage{idx}.patch_embed.norm.bias", ) ) return embed def _snake_case( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> str: lowercase : Optional[Any] = [] attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.convolution.weight", f"stage{idx}.blocks.{cnt}.attn.conv_proj_q.conv.weight", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.weight", f"stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.weight", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.bias", f"stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.bias", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_mean", f"stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_mean", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_var", f"stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_var", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.num_batches_tracked", f"stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.num_batches_tracked", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.convolution.weight", f"stage{idx}.blocks.{cnt}.attn.conv_proj_k.conv.weight", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.weight", f"stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.weight", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.bias", f"stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.bias", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_mean", f"stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_mean", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_var", f"stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_var", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.num_batches_tracked", f"stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.num_batches_tracked", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.convolution.weight", f"stage{idx}.blocks.{cnt}.attn.conv_proj_v.conv.weight", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.weight", f"stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.weight", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.bias", f"stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.bias", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_mean", f"stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_mean", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_var", f"stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_var", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.num_batches_tracked", f"stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.num_batches_tracked", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.weight", f"stage{idx}.blocks.{cnt}.attn.proj_q.weight", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.bias", f"stage{idx}.blocks.{cnt}.attn.proj_q.bias", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.weight", f"stage{idx}.blocks.{cnt}.attn.proj_k.weight", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.bias", f"stage{idx}.blocks.{cnt}.attn.proj_k.bias", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.weight", f"stage{idx}.blocks.{cnt}.attn.proj_v.weight", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.bias", f"stage{idx}.blocks.{cnt}.attn.proj_v.bias", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.weight", f"stage{idx}.blocks.{cnt}.attn.proj.weight", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.bias", f"stage{idx}.blocks.{cnt}.attn.proj.bias", ) ) attention_weights.append( (f"cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.weight", f"stage{idx}.blocks.{cnt}.mlp.fc1.weight") ) attention_weights.append( (f"cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.bias", f"stage{idx}.blocks.{cnt}.mlp.fc1.bias") ) attention_weights.append( (f"cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.weight", f"stage{idx}.blocks.{cnt}.mlp.fc2.weight") ) attention_weights.append( (f"cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.bias", f"stage{idx}.blocks.{cnt}.mlp.fc2.bias") ) attention_weights.append( (f"cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.weight", f"stage{idx}.blocks.{cnt}.norm1.weight") ) attention_weights.append( (f"cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.bias", f"stage{idx}.blocks.{cnt}.norm1.bias") ) attention_weights.append( (f"cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.weight", f"stage{idx}.blocks.{cnt}.norm2.weight") ) attention_weights.append( (f"cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.bias", f"stage{idx}.blocks.{cnt}.norm2.bias") ) return attention_weights def _snake_case( SCREAMING_SNAKE_CASE__ ) -> Optional[Any]: lowercase : Optional[Any] = [] token.append((f"cvt.encoder.stages.{idx}.cls_token", """stage2.cls_token""") ) return token def _snake_case( ) -> Dict: lowercase : Optional[Any] = [] head.append(("""layernorm.weight""", """norm.weight""") ) head.append(("""layernorm.bias""", """norm.bias""") ) head.append(("""classifier.weight""", """head.weight""") ) head.append(("""classifier.bias""", """head.bias""") ) return head def _snake_case( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> str: lowercase : Any = """imagenet-1k-id2label.json""" lowercase : List[str] = 1_000 lowercase : int = """huggingface/label-files""" lowercase : Union[str, Any] = num_labels lowercase : Optional[Any] = json.load(open(cached_download(hf_hub_url(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , repo_type="""dataset""" ) ) , """r""" ) ) lowercase : List[Any] = {int(SCREAMING_SNAKE_CASE__ ): v for k, v in idalabel.items()} lowercase : Dict = idalabel lowercase : List[str] = {v: k for k, v in idalabel.items()} lowercase : List[str] = CvtConfig(num_labels=SCREAMING_SNAKE_CASE__ , idalabel=SCREAMING_SNAKE_CASE__ , labelaid=SCREAMING_SNAKE_CASE__ ) # For depth size 13 (13 = 1+2+10) if cvt_model.rsplit("""/""" , 1 )[-1][4:6] == "13": lowercase : Tuple = [1, 2, 10] # For depth size 21 (21 = 1+4+16) elif cvt_model.rsplit("""/""" , 1 )[-1][4:6] == "21": lowercase : Dict = [1, 4, 16] # For wide cvt (similar to wide-resnet) depth size 24 (w24 = 2 + 2 20) else: lowercase : int = [2, 2, 20] lowercase : Optional[int] = [3, 12, 16] lowercase : str = [192, 768, 1_024] lowercase : Union[str, Any] = CvtForImageClassification(SCREAMING_SNAKE_CASE__ ) lowercase : Union[str, Any] = AutoImageProcessor.from_pretrained("""facebook/convnext-base-224-22k-1k""" ) lowercase : Optional[Any] = image_size lowercase : Union[str, Any] = torch.load(SCREAMING_SNAKE_CASE__ , map_location=torch.device("""cpu""" ) ) lowercase : Optional[Any] = OrderedDict() lowercase : Tuple = [] for idx in range(len(config.depth ) ): if config.cls_token[idx]: lowercase : Optional[Any] = list_of_state_dict + cls_token(SCREAMING_SNAKE_CASE__ ) lowercase : str = list_of_state_dict + embeddings(SCREAMING_SNAKE_CASE__ ) for cnt in range(config.depth[idx] ): lowercase : List[str] = list_of_state_dict + attention(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowercase : List[str] = list_of_state_dict + final() for gg in list_of_state_dict: print(SCREAMING_SNAKE_CASE__ ) for i in range(len(SCREAMING_SNAKE_CASE__ ) ): lowercase : Optional[Any] = original_weights[list_of_state_dict[i][1]] model.load_state_dict(SCREAMING_SNAKE_CASE__ ) model.save_pretrained(SCREAMING_SNAKE_CASE__ ) image_processor.save_pretrained(SCREAMING_SNAKE_CASE__ ) # Download the weights from zoo: https://1drv.ms/u/s!AhIXJn_J-blW9RzF3rMW7SsLHa8h?e=blQ0Al if __name__ == "__main__": lowercase : Tuple = argparse.ArgumentParser() parser.add_argument( """--cvt_model""", default="""cvt-w24""", type=str, help="""Name of the cvt model you'd like to convert.""", ) parser.add_argument( """--image_size""", default=384, type=int, help="""Input Image Size""", ) parser.add_argument( """--cvt_file_name""", default=R"""cvtmodels\CvT-w24-384x384-IN-22k.pth""", type=str, help="""Input Image Size""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) lowercase : Optional[int] = parser.parse_args() convert_cvt_checkpoint(args.cvt_model, args.image_size, args.cvt_file_name, args.pytorch_dump_folder_path)
20
0
import inspect import re from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_config_docstrings.py __UpperCamelCase = 'src/transformers' # This is to make sure the transformers module imported is the one in the repo. __UpperCamelCase = direct_transformers_import(PATH_TO_TRANSFORMERS) __UpperCamelCase = transformers.models.auto.configuration_auto.CONFIG_MAPPING # Regex pattern used to find the checkpoint mentioned in the docstring of `config_class`. # For example, `[bert-base-uncased](https://huggingface.co/bert-base-uncased)` __UpperCamelCase = re.compile(R"\[(.+?)\]\((https://huggingface\.co/.+?)\)") __UpperCamelCase = { 'DecisionTransformerConfig', 'EncoderDecoderConfig', 'MusicgenConfig', 'RagConfig', 'SpeechEncoderDecoderConfig', 'TimmBackboneConfig', 'VisionEncoderDecoderConfig', 'VisionTextDualEncoderConfig', 'LlamaConfig', } def _a ( _lowerCamelCase ) -> Optional[Any]: """simple docstring""" __snake_case : Optional[int] = None # source code of `config_class` __snake_case : Dict = inspect.getsource(lowerCAmelCase__ ) __snake_case : Optional[Any] = _re_checkpoint.findall(lowerCAmelCase__ ) # Each `checkpoint` is a tuple of a checkpoint name and a checkpoint link. # For example, `('bert-base-uncased', 'https://huggingface.co/bert-base-uncased')` for ckpt_name, ckpt_link in checkpoints: # allow the link to end with `/` if ckpt_link.endswith("""/""" ): __snake_case : Any = ckpt_link[:-1] # verify the checkpoint name corresponds to the checkpoint link __snake_case : Optional[Any] = F'''https://huggingface.co/{ckpt_name}''' if ckpt_link == ckpt_link_from_name: __snake_case : Optional[int] = ckpt_name break return checkpoint def _a ( ) -> Tuple: """simple docstring""" __snake_case : List[Any] = [] for config_class in list(CONFIG_MAPPING.values() ): # Skip deprecated models if "models.deprecated" in config_class.__module__: continue __snake_case : int = get_checkpoint_from_config_class(lowerCAmelCase__ ) __snake_case : Tuple = config_class.__name__ if checkpoint is None and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK: configs_without_checkpoint.append(lowerCAmelCase__ ) if len(lowerCAmelCase__ ) > 0: __snake_case : Union[str, Any] = """\n""".join(sorted(lowerCAmelCase__ ) ) raise ValueError(F'''The following configurations don\'t contain any valid checkpoint:\n{message}''' ) if __name__ == "__main__": check_config_docstrings_have_checkpoints()
365
'''simple docstring''' def _a ( _lowerCamelCase ) -> bool: """simple docstring""" __snake_case : Optional[int] = (1 + 24 * n) ** 0.5 return ((1 + root) / 6) % 1 == 0 def _a ( _lowerCamelCase = 5000 ) -> int: """simple docstring""" __snake_case : int = [(i * (3 * i - 1)) // 2 for i in range(1 , _lowerCamelCase )] for i, pentagonal_i in enumerate(_lowerCamelCase ): for j in range(_lowerCamelCase , len(_lowerCamelCase ) ): __snake_case : Optional[int] = pentagonal_nums[j] __snake_case : str = pentagonal_i + pentagonal_j __snake_case : List[Any] = pentagonal_j - pentagonal_i if is_pentagonal(_lowerCamelCase ) and is_pentagonal(_lowerCamelCase ): return b return -1 if __name__ == "__main__": print(f"""{solution() = }""")
13
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __A : List[str] = { '''configuration_mobilenet_v2''': [ '''MOBILENET_V2_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MobileNetV2Config''', '''MobileNetV2OnnxConfig''', ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Dict = ['''MobileNetV2FeatureExtractor'''] __A : Optional[int] = ['''MobileNetV2ImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Optional[Any] = [ '''MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MobileNetV2ForImageClassification''', '''MobileNetV2ForSemanticSegmentation''', '''MobileNetV2Model''', '''MobileNetV2PreTrainedModel''', '''load_tf_weights_in_mobilenet_v2''', ] if TYPE_CHECKING: from .configuration_mobilenet_va import ( MOBILENET_V2_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileNetVaConfig, MobileNetVaOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_mobilenet_va import MobileNetVaFeatureExtractor from .image_processing_mobilenet_va import MobileNetVaImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mobilenet_va import ( MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation, MobileNetVaModel, MobileNetVaPreTrainedModel, load_tf_weights_in_mobilenet_va, ) else: import sys __A : List[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
33
"""simple docstring""" def lowercase ( __snake_case : Optional[int] ): lowercase_ : int = 0 lowercase_ : Optional[Any] = len(__snake_case ) for i in range(n - 1 ): for j in range(i + 1 , __snake_case ): if arr[i] > arr[j]: num_inversions += 1 return num_inversions def lowercase ( __snake_case : str ): if len(__snake_case ) <= 1: return arr, 0 lowercase_ : Optional[Any] = len(__snake_case ) // 2 lowercase_ : List[Any] = arr[0:mid] lowercase_ : Union[str, Any] = arr[mid:] lowercase_ , lowercase_ : Tuple = count_inversions_recursive(__snake_case ) lowercase_ , lowercase_ : List[Any] = count_inversions_recursive(__snake_case ) lowercase_ , lowercase_ : List[Any] = _count_cross_inversions(__snake_case , __snake_case ) lowercase_ : List[Any] = inversion_p + inversions_q + cross_inversions return c, num_inversions def lowercase ( __snake_case : str , __snake_case : Optional[int] ): lowercase_ : Optional[Any] = [] lowercase_ : Any = 0 while i < len(__snake_case ) and j < len(__snake_case ): if p[i] > q[j]: # if P[1] > Q[j], then P[k] > Q[k] for all i < k <= len(P) # These are all inversions. The claim emerges from the # property that P is sorted. num_inversion += len(__snake_case ) - i r.append(q[j] ) j += 1 else: r.append(p[i] ) i += 1 if i < len(__snake_case ): r.extend(p[i:] ) else: r.extend(q[j:] ) return r, num_inversion def lowercase ( ): lowercase_ : Union[str, Any] = [1_0, 2, 1, 5, 5, 2, 1_1] # this arr has 8 inversions: # (10, 2), (10, 1), (10, 5), (10, 5), (10, 2), (2, 1), (5, 2), (5, 2) lowercase_ : int = count_inversions_bf(__snake_case ) lowercase_ , lowercase_ : Dict = count_inversions_recursive(__snake_case ) assert num_inversions_bf == num_inversions_recursive == 8 print('''number of inversions = ''' , __snake_case ) # testing an array with zero inversion (a sorted arr_1) arr_a.sort() lowercase_ : Dict = count_inversions_bf(__snake_case ) lowercase_ , lowercase_ : Dict = count_inversions_recursive(__snake_case ) assert num_inversions_bf == num_inversions_recursive == 0 print('''number of inversions = ''' , __snake_case ) # an empty list should also have zero inversions lowercase_ : List[Any] = [] lowercase_ : Any = count_inversions_bf(__snake_case ) lowercase_ , lowercase_ : List[str] = count_inversions_recursive(__snake_case ) assert num_inversions_bf == num_inversions_recursive == 0 print('''number of inversions = ''' , __snake_case ) if __name__ == "__main__": main()
33
1
import unittest from transformers import AutoTokenizer, FalconConfig, 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 ( FalconForCausalLM, FalconForQuestionAnswering, FalconForSequenceClassification, FalconForTokenClassification, FalconModel, ) class _a : '''simple docstring''' def __init__( self , A__ , A__=3 , A__=7 , A__=True , A__=True , A__=False , 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.0_2 , A__=3 , A__=4 , A__=None , ): A__ : List[Any] = parent A__ : List[str] = batch_size A__ : Optional[int] = seq_length A__ : Optional[int] = is_training A__ : Any = use_input_mask A__ : Tuple = use_token_type_ids A__ : str = use_labels A__ : Tuple = vocab_size A__ : Any = hidden_size A__ : List[str] = num_hidden_layers A__ : Optional[int] = num_attention_heads A__ : Optional[Any] = intermediate_size A__ : Optional[Any] = hidden_act A__ : Tuple = hidden_dropout_prob A__ : Union[str, Any] = attention_probs_dropout_prob A__ : List[str] = max_position_embeddings A__ : Union[str, Any] = type_vocab_size A__ : str = type_sequence_label_size A__ : Tuple = initializer_range A__ : Tuple = num_labels A__ : Dict = num_choices A__ : List[str] = scope def __A ( self ): A__ : Any = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A__ : Any = None if self.use_input_mask: A__ : int = random_attention_mask([self.batch_size, self.seq_length] ) A__ : str = None A__ : Union[str, Any] = None A__ : List[str] = None A__ : Optional[Any] = None if self.use_labels: A__ : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A__ : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) A__ : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) A__ : Dict = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __A ( self ): return FalconConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=A__ , initializer_range=self.initializer_range , pad_token_id=1 , new_decoder_architecture=A__ , ) def __A ( self , A__ , A__ , A__ , A__ , A__ , A__ , A__ ): A__ : List[str] = FalconModel(config=A__ ) model.to(A__ ) model.eval() A__ : int = model(A__ , attention_mask=A__ ) A__ : Union[str, Any] = model(A__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __A ( self , A__ , A__ , A__ , A__ , A__ , A__ , A__ , A__ , A__ , ): A__ : Union[str, Any] = True A__ : Union[str, Any] = FalconModel(A__ ) model.to(A__ ) model.eval() A__ : Tuple = model( A__ , attention_mask=A__ , encoder_hidden_states=A__ , encoder_attention_mask=A__ , ) A__ : Union[str, Any] = model( A__ , attention_mask=A__ , encoder_hidden_states=A__ , ) A__ : List[str] = model(A__ , attention_mask=A__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __A ( self , A__ , A__ , A__ , A__ , A__ , A__ , A__ , A__ , A__ , ): A__ : Any = FalconForCausalLM(config=A__ ) model.to(A__ ) model.eval() A__ : Tuple = model(A__ , attention_mask=A__ , labels=A__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __A ( self , A__ , A__ , A__ , A__ , A__ , A__ , A__ , A__ , A__ , ): A__ : Optional[Any] = True A__ : Union[str, Any] = True A__ : int = FalconForCausalLM(config=A__ ) model.to(A__ ) model.eval() # first forward pass A__ : List[Any] = model( A__ , attention_mask=A__ , encoder_hidden_states=A__ , encoder_attention_mask=A__ , use_cache=A__ , ) A__ : Tuple = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids A__ : Tuple = ids_tensor((self.batch_size, 3) , config.vocab_size ) A__ : List[Any] = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and A__ : Optional[int] = torch.cat([input_ids, next_tokens] , dim=-1 ) A__ : List[str] = torch.cat([input_mask, next_mask] , dim=-1 ) A__ : Optional[int] = model( A__ , attention_mask=A__ , encoder_hidden_states=A__ , encoder_attention_mask=A__ , output_hidden_states=A__ , )["""hidden_states"""][0] A__ : Any = model( A__ , attention_mask=A__ , encoder_hidden_states=A__ , encoder_attention_mask=A__ , past_key_values=A__ , output_hidden_states=A__ , )["""hidden_states"""][0] # select random slice A__ : List[Any] = ids_tensor((1,) , output_from_past.shape[-1] ).item() A__ : List[str] = output_from_no_past[:, -3:, random_slice_idx].detach() A__ : Optional[Any] = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(A__ , A__ , atol=1e-3 ) ) def __A ( self ): A__ : List[str] = self.prepare_config_and_inputs() ( A__ ) : Tuple = config_and_inputs A__ : List[str] = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class _a (__magic_name__ , __magic_name__ , __magic_name__ , unittest.TestCase ): '''simple docstring''' UpperCAmelCase__: List[Any] = ( ( FalconModel, FalconForCausalLM, FalconForSequenceClassification, FalconForTokenClassification, FalconForQuestionAnswering, ) if is_torch_available() else () ) UpperCAmelCase__: Tuple = (FalconForCausalLM,) if is_torch_available() else () UpperCAmelCase__: Optional[int] = ( { '''feature-extraction''': FalconModel, '''text-classification''': FalconForSequenceClassification, '''text-generation''': FalconForCausalLM, '''question-answering''': FalconForQuestionAnswering, '''token-classification''': FalconForTokenClassification, '''zero-shot''': FalconForSequenceClassification, } if is_torch_available() else {} ) UpperCAmelCase__: str = False UpperCAmelCase__: int = False def __A ( self ): A__ : List[Any] = FalconModelTester(self ) A__ : Union[str, Any] = ConfigTester(self , config_class=A__ , hidden_size=37 ) def __A ( self ): self.config_tester.run_common_tests() def __A ( self ): A__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A__ ) def __A ( self ): A__ : List[Any] = self.model_tester.prepare_config_and_inputs() for alibi in [True, False]: A__ : Tuple = alibi self.model_tester.create_and_check_model(A__ , *A__ ) def __A ( self ): A__ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() A__ : Optional[int] = 3 A__ : int = input_dict["""input_ids"""] A__ : int = input_ids.ne(1 ).to(A__ ) A__ : Union[str, Any] = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) A__ : Optional[int] = FalconForSequenceClassification(A__ ) model.to(A__ ) model.eval() A__ : int = model(A__ , attention_mask=A__ , labels=A__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def __A ( self ): A__ : str = self.model_tester.prepare_config_and_inputs_for_common() A__ : Dict = 3 A__ : Tuple = """single_label_classification""" A__ : List[Any] = input_dict["""input_ids"""] A__ : Dict = input_ids.ne(1 ).to(A__ ) A__ : Dict = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) A__ : Any = FalconForSequenceClassification(A__ ) model.to(A__ ) model.eval() A__ : Any = model(A__ , attention_mask=A__ , labels=A__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def __A ( self ): A__ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() A__ : List[str] = input_dict["""input_ids"""] A__ : List[str] = FalconForCausalLM(A__ ) model.to(A__ ) model.eval() A__ : Any = model(A__ , use_cache=A__ ) A__ : Any = input_ids.shape[0] A__ : Union[str, Any] = model._convert_to_rw_cache(result.past_key_values ) A__ : int = model._convert_cache_to_standard_format(A__ , A__ ) for layer in range(len(A__ ) ): for tensor_idx in range(2 ): self.assertTrue(rw_cache[layer][tensor_idx].ndim == 3 ) self.assertTrue(result.past_key_values[layer][tensor_idx].ndim == 4 ) self.assertTrue( torch.all(result.past_key_values[layer][tensor_idx] == standard_cache[layer][tensor_idx] ) ) def __A ( self ): A__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() A__ : Optional[Any] = 3 A__ : List[Any] = """multi_label_classification""" A__ : Tuple = input_dict["""input_ids"""] A__ : List[Any] = input_ids.ne(1 ).to(A__ ) A__ : Optional[Any] = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) A__ : Optional[int] = FalconForSequenceClassification(A__ ) model.to(A__ ) model.eval() A__ : List[Any] = model(A__ , attention_mask=A__ , labels=A__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def __A ( self ): # Falcon can have different numbers of KV-heads than the number of query heads, so we need # to override this test to use the right head counts. for model_class in self.all_generative_model_classes: A__ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() # If it doesn't support cache, pass the test if not hasattr(A__ , """use_cache""" ): return A__ : Optional[Any] = model_class(A__ ).to(A__ ) if "use_cache" not in inputs: A__ : Optional[int] = True A__ : List[Any] = model(**A__ ) # If "past_key_values" is not returned, pass the test (e.g. RWKV uses a different cache name and format) if "past_key_values" not in outputs: return A__ : str = ( getattr(A__ , """decoder_layers""" , A__ ) or getattr(A__ , """num_decoder_layers""" , A__ ) or config.num_hidden_layers ) A__ : Dict = getattr(A__ , """num_kv_heads""" , config.num_attention_heads ) A__ : List[str] = getattr(A__ , """d_model""" , config.hidden_size ) A__ : Union[str, Any] = embed_dim // num_attention_heads A__ : str = outputs["""past_key_values"""] self.assertEqual(len(A__ ) , A__ ) A__ : int = inputs["""input_ids"""].shape for i in range(A__ ): if config.new_decoder_architecture: A__ : Any = config.num_attention_heads elif config.multi_query: A__ : List[Any] = 1 self.assertEqual(len(past_kv[0] ) , 2 ) # K V for the decoder = 2 self.assertEqual( past_kv[i][0].shape , (batch_size, num_attention_heads, seq_length, per_head_embed_dim) ) self.assertEqual( past_kv[i][1].shape , (batch_size, num_attention_heads, seq_length, per_head_embed_dim) ) @require_torch class _a (unittest.TestCase ): '''simple docstring''' @slow def __A ( self ): A__ : Dict = AutoTokenizer.from_pretrained("""Rocketknight1/falcon-rw-1b""" ) A__ : List[Any] = FalconForCausalLM.from_pretrained("""Rocketknight1/falcon-rw-1b""" ) model.eval() model.to(A__ ) A__ : Optional[int] = tokenizer("""My favorite food is""" , return_tensors="""pt""" ).to(A__ ) A__ : Optional[Any] = ( """My favorite food is pizza. I love it so much that I have a pizza party every year for my birthday.""" ) A__ : Any = model.generate(**A__ , do_sample=A__ , max_new_tokens=19 ) A__ : Optional[int] = tokenizer.batch_decode(A__ )[0] self.assertEqual(A__ , A__ ) @slow def __A ( self ): # The big models are way too big for the CI, so we use tiny random models that resemble their # architectures but with much smaller and fewer layers for repo in ["Rocketknight1/tiny-random-falcon-7b", "Rocketknight1/tiny-random-falcon-40b"]: A__ : Dict = AutoTokenizer.from_pretrained(A__ ) A__ : List[str] = FalconForCausalLM.from_pretrained(A__ ) model.eval() model.to(A__ ) A__ : Union[str, Any] = tokenizer("""My favorite food is""" , return_tensors="""pt""" ).to(A__ ) # We just test that these run without errors - the models are randomly initialized # and so the actual text outputs will be garbage model.generate(**A__ , do_sample=A__ , max_new_tokens=4 ) model.generate(**A__ , do_sample=A__ , max_new_tokens=4 ) model.generate(**A__ , num_beams=2 , max_new_tokens=4 ) @slow def __A ( self ): # The big models are way too big for the CI, so we use tiny random models that resemble their # architectures but with much smaller and fewer layers with torch.no_grad(): for repo in [ "Rocketknight1/falcon-rw-1b", "Rocketknight1/tiny-random-falcon-7b", "Rocketknight1/tiny-random-falcon-40b", ]: A__ : Dict = AutoTokenizer.from_pretrained(A__ ) A__ : Any = FalconForCausalLM.from_pretrained(A__ ) model.eval() model.to(device=A__ ) A__ : List[str] = tokenizer("""My favorite food is""" , return_tensors="""pt""" ).to(A__ ) # Test results are the same with and without cache A__ : Tuple = model.generate(**A__ , do_sample=A__ , max_new_tokens=20 , use_cache=A__ ) A__ : Optional[Any] = model.generate(**A__ , do_sample=A__ , max_new_tokens=20 , use_cache=A__ ) self.assertTrue((outputs_cache - outputs_no_cache).sum().item() == 0 )
363
from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable A_ : List[Any] = {'configuration_gpt_neox': ['GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP', 'GPTNeoXConfig']} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : Optional[Any] = ['GPTNeoXTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : Optional[int] = [ 'GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST', 'GPTNeoXForCausalLM', 'GPTNeoXForQuestionAnswering', 'GPTNeoXForSequenceClassification', 'GPTNeoXForTokenClassification', 'GPTNeoXLayer', 'GPTNeoXModel', 'GPTNeoXPreTrainedModel', ] if TYPE_CHECKING: from .configuration_gpt_neox import GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXConfig try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_neox_fast import GPTNeoXTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox import ( GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXLayer, GPTNeoXModel, GPTNeoXPreTrainedModel, ) else: import sys A_ : Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
141
0
'''simple docstring''' def lowerCAmelCase (__A = 4_000_000): """simple docstring""" _a = [0, 1] _a = 0 while fib[i] <= n: fib.append(fib[i] + fib[i + 1]) if fib[i + 2] > n: break i += 1 _a = 0 for j in range(len(__A) - 1): if fib[j] % 2 == 0: total += fib[j] return total if __name__ == "__main__": print(F"""{solution() = }""")
211
'''simple docstring''' from __future__ import annotations import math def lowerCAmelCase (__A , __A): """simple docstring""" _a = u for i in range(1 , __A): _a = temp * (u - i) return temp def lowerCAmelCase (): """simple docstring""" _a = int(input('''enter the numbers of values: ''')) _a = [] for _ in range(__A): y.append([]) for i in range(__A): for j in range(__A): y[i].append(__A) _a = 0 print('''enter the values of parameters in a list: ''') _a = list(map(__A , input().split())) print('''enter the values of corresponding parameters: ''') for i in range(__A): _a = float(input()) _a = int(input('''enter the value to interpolate: ''')) _a = (value - x[0]) / (x[1] - x[0]) # for calculating forward difference table for i in range(1 , __A): for j in range(n - i): _a = y[j + 1][i - 1] - y[j][i - 1] _a = y[0][0] for i in range(1 , __A): summ += (ucal(__A , __A) * y[0][i]) / math.factorial(__A) print(F'''the value at {value} is {summ}''') if __name__ == "__main__": main()
211
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowerCAmelCase : Tuple = { "configuration_megatron_bert": ["MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "MegatronBertConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase : List[str] = [ "MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST", "MegatronBertForCausalLM", "MegatronBertForMaskedLM", "MegatronBertForMultipleChoice", "MegatronBertForNextSentencePrediction", "MegatronBertForPreTraining", "MegatronBertForQuestionAnswering", "MegatronBertForSequenceClassification", "MegatronBertForTokenClassification", "MegatronBertModel", "MegatronBertPreTrainedModel", ] if TYPE_CHECKING: from .configuration_megatron_bert import MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MegatronBertConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_megatron_bert import ( MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, MegatronBertPreTrainedModel, ) else: import sys _lowerCAmelCase : Optional[int] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
308
import unittest from transformers import load_tool from transformers.utils import is_torch_available if is_torch_available(): import torch from transformers.testing_utils import require_torch from .test_tools_common import ToolTesterMixin @require_torch class __magic_name__ ( unittest.TestCase , lowerCAmelCase_ ): def __magic_name__ ( self ) -> Union[str, Any]: '''simple docstring''' __a =load_tool('text-to-speech' ) self.tool.setup() def __magic_name__ ( self ) -> Dict: '''simple docstring''' # SpeechT5 isn't deterministic torch.manual_seed(0 ) __a =self.tool('hey' ) __a =result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.000_5966_6688_3211_5829, -0.000_3657_6401_9079_5064, -0.0001_3439_5027_9988_3485] ) , ) ) def __magic_name__ ( self ) -> List[Any]: '''simple docstring''' # SpeechT5 isn't deterministic torch.manual_seed(0 ) __a =self.tool('hey' ) __a =result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.000_5966_6688_3211_5829, -0.000_3657_6401_9079_5064, -0.0001_3439_5027_9988_3485] ) , ) )
308
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_speech_available, is_torch_available UpperCAmelCase_ : Any = { 'configuration_audio_spectrogram_transformer': [ 'AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ASTConfig', ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : int = [ 'AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'ASTForAudioClassification', 'ASTModel', 'ASTPreTrainedModel', ] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Union[str, Any] = ['ASTFeatureExtractor'] if TYPE_CHECKING: from .configuration_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ASTConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ASTForAudioClassification, ASTModel, ASTPreTrainedModel, ) try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_audio_spectrogram_transformer import ASTFeatureExtractor else: import sys UpperCAmelCase_ : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
32
'''simple docstring''' UpperCAmelCase = ''' # Transformers installation ! pip install transformers datasets # To install from source instead of the last release, comment the command above and uncomment the following one. # ! pip install git+https://github.com/huggingface/transformers.git ''' UpperCAmelCase = [{'''type''': '''code''', '''content''': INSTALL_CONTENT}] UpperCAmelCase = { '''{processor_class}''': '''FakeProcessorClass''', '''{model_class}''': '''FakeModelClass''', '''{object_class}''': '''FakeObjectClass''', }
141
0
"""simple docstring""" from __future__ import annotations from math import pi # Define the Reduced Planck Constant ℏ (H bar), speed of light C, value of # Pi and the function UpperCAmelCase__ = 1.0_5457_1817E-34 # unit of ℏ : J * s UpperCAmelCase__ = 3E8 # unit of c : m * s^-1 def __UpperCAmelCase ( lowercase ,lowercase ,lowercase ): """simple docstring""" if (force, area, distance).count(0 ) != 1: raise ValueError("""One and only one argument must be 0""" ) if force < 0: raise ValueError("""Magnitude of force can not be negative""" ) if distance < 0: raise ValueError("""Distance can not be negative""" ) if area < 0: raise ValueError("""Area can not be negative""" ) if force == 0: _UpperCAmelCase = (REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 * area) / ( 2_40 * (distance) ** 4 ) return {"force": force} elif area == 0: _UpperCAmelCase = (2_40 * force * (distance) ** 4) / ( REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 ) return {"area": area} elif distance == 0: _UpperCAmelCase = ( (REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 * area) / (2_40 * force) ) ** (1 / 4) return {"distance": distance} raise ValueError("""One and only one argument must be 0""" ) # Run doctest if __name__ == "__main__": import doctest doctest.testmod()
358
"""simple docstring""" import csv from collections import defaultdict from dataclasses import dataclass, field from typing import List, Optional import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import ScalarFormatter from transformers import HfArgumentParser def __UpperCAmelCase ( lowercase=None ,lowercase=None ): """simple docstring""" return field(default_factory=lambda: default ,metadata=lowercase ) @dataclass class a : _snake_case : str = field( metadata={'help': 'The csv file to plot.'} , ) _snake_case : bool = field( default=lowerCAmelCase_ , metadata={'help': 'Whether to plot along batch size or sequence length. Defaults to sequence length.'} , ) _snake_case : bool = field( default=lowerCAmelCase_ , metadata={'help': 'Whether the csv file has time results or memory results. Defaults to memory results.'} , ) _snake_case : bool = field( default=lowerCAmelCase_ , metadata={'help': 'Disable logarithmic scale when plotting'} , ) _snake_case : bool = field( default=lowerCAmelCase_ , metadata={ 'help': 'Whether the csv file has training results or inference results. Defaults to inference results.' } , ) _snake_case : Optional[str] = field( default=lowerCAmelCase_ , metadata={'help': 'Filename under which the plot will be saved. If unused no plot is saved.'} , ) _snake_case : Optional[List[str]] = list_field( default=lowerCAmelCase_ , metadata={'help': 'List of model names that are used instead of the ones in the csv file.'} ) def __UpperCAmelCase ( lowercase ): """simple docstring""" try: int(lowercase ) return True except ValueError: return False def __UpperCAmelCase ( lowercase ): """simple docstring""" try: float(lowercase ) return True except ValueError: return False class a : def __init__( self : int , __lowerCAmelCase : Union[str, Any] ): _UpperCAmelCase = args _UpperCAmelCase = defaultdict(lambda: {"bsz": [], "seq_len": [], "result": {}} ) with open(self.args.csv_file , newline="""""" ) as csv_file: _UpperCAmelCase = csv.DictReader(__lowerCAmelCase ) for row in reader: _UpperCAmelCase = row["""model"""] self.result_dict[model_name]["bsz"].append(int(row["""batch_size"""] ) ) self.result_dict[model_name]["seq_len"].append(int(row["""sequence_length"""] ) ) if can_convert_to_int(row["""result"""] ): # value is not None _UpperCAmelCase = int(row["""result"""] ) elif can_convert_to_float(row["""result"""] ): # value is not None _UpperCAmelCase = float(row["""result"""] ) def lowerCAmelCase_ ( self : Optional[Any] ): _UpperCAmelCase , _UpperCAmelCase = plt.subplots() _UpperCAmelCase = """Time usage""" if self.args.is_time else """Memory usage""" _UpperCAmelCase = title_str + """ for training""" if self.args.is_train else title_str + """ for inference""" if not self.args.no_log_scale: # set logarithm scales ax.set_xscale("""log""" ) ax.set_yscale("""log""" ) for axis in [ax.xaxis, ax.yaxis]: axis.set_major_formatter(ScalarFormatter() ) for model_name_idx, model_name in enumerate(self.result_dict.keys() ): _UpperCAmelCase = sorted(set(self.result_dict[model_name]["""bsz"""] ) ) _UpperCAmelCase = sorted(set(self.result_dict[model_name]["""seq_len"""] ) ) _UpperCAmelCase = self.result_dict[model_name]["""result"""] ((_UpperCAmelCase) , (_UpperCAmelCase)) = ( (batch_sizes, sequence_lengths) if self.args.plot_along_batch else (sequence_lengths, batch_sizes) ) _UpperCAmelCase = ( model_name if self.args.short_model_names is None else self.args.short_model_names[model_name_idx] ) for inner_loop_value in inner_loop_array: if self.args.plot_along_batch: _UpperCAmelCase = np.asarray( [results[(x, inner_loop_value)] for x in x_axis_array if (x, inner_loop_value) in results] , dtype=__lowerCAmelCase , ) else: _UpperCAmelCase = np.asarray( [results[(inner_loop_value, x)] for x in x_axis_array if (inner_loop_value, x) in results] , dtype=np.floataa , ) ((_UpperCAmelCase) , (_UpperCAmelCase)) = ( ("""batch_size""", """len""") if self.args.plot_along_batch else ("""in #tokens""", """bsz""") ) _UpperCAmelCase = np.asarray(__lowerCAmelCase , __lowerCAmelCase )[: len(__lowerCAmelCase )] plt.scatter( __lowerCAmelCase , __lowerCAmelCase , label=f'''{label_model_name} - {inner_loop_label}: {inner_loop_value}''' ) plt.plot(__lowerCAmelCase , __lowerCAmelCase , """--""" ) title_str += f''' {label_model_name} vs.''' _UpperCAmelCase = title_str[:-4] _UpperCAmelCase = """Time in s""" if self.args.is_time else """Memory in MB""" # plot plt.title(__lowerCAmelCase ) plt.xlabel(__lowerCAmelCase ) plt.ylabel(__lowerCAmelCase ) plt.legend() if self.args.figure_png_file is not None: plt.savefig(self.args.figure_png_file ) else: plt.show() def __UpperCAmelCase ( ): """simple docstring""" _UpperCAmelCase = HfArgumentParser(lowercase ) _UpperCAmelCase = parser.parse_args_into_dataclasses()[0] _UpperCAmelCase = Plot(args=lowercase ) plot.plot() if __name__ == "__main__": main()
30
0
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging a_ = logging.get_logger(__name__) a_ = { """google/bigbird-roberta-base""": """https://huggingface.co/google/bigbird-roberta-base/resolve/main/config.json""", """google/bigbird-roberta-large""": """https://huggingface.co/google/bigbird-roberta-large/resolve/main/config.json""", """google/bigbird-base-trivia-itc""": """https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/config.json""", # See all BigBird models at https://huggingface.co/models?filter=big_bird } class __snake_case ( SCREAMING_SNAKE_CASE__ ): """simple docstring""" _lowerCamelCase = """big_bird""" def __init__( self , __lowerCamelCase=5_0358 , __lowerCamelCase=768 , __lowerCamelCase=12 , __lowerCamelCase=12 , __lowerCamelCase=3072 , __lowerCamelCase="gelu_new" , __lowerCamelCase=0.1 , __lowerCamelCase=0.1 , __lowerCamelCase=4096 , __lowerCamelCase=2 , __lowerCamelCase=0.0_2 , __lowerCamelCase=1e-1_2 , __lowerCamelCase=True , __lowerCamelCase=0 , __lowerCamelCase=1 , __lowerCamelCase=2 , __lowerCamelCase=66 , __lowerCamelCase="block_sparse" , __lowerCamelCase=True , __lowerCamelCase=False , __lowerCamelCase=64 , __lowerCamelCase=3 , __lowerCamelCase=None , **__lowerCamelCase , ): '''simple docstring''' super().__init__( pad_token_id=__lowerCamelCase , bos_token_id=__lowerCamelCase , eos_token_id=__lowerCamelCase , sep_token_id=__lowerCamelCase , **__lowerCamelCase , ) __A : List[str] = vocab_size __A : Dict = max_position_embeddings __A : Optional[Any] = hidden_size __A : Union[str, Any] = num_hidden_layers __A : List[Any] = num_attention_heads __A : Optional[Any] = intermediate_size __A : Dict = hidden_act __A : Dict = hidden_dropout_prob __A : List[Any] = attention_probs_dropout_prob __A : Optional[int] = initializer_range __A : Dict = type_vocab_size __A : Any = layer_norm_eps __A : Optional[Any] = use_cache __A : Dict = rescale_embeddings __A : int = attention_type __A : Union[str, Any] = use_bias __A : int = block_size __A : Any = num_random_blocks __A : int = classifier_dropout class __snake_case ( SCREAMING_SNAKE_CASE__ ): """simple docstring""" @property def UpperCamelCase__( self ): '''simple docstring''' if self.task == "multiple-choice": __A : int = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: __A : Any = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ] )
179
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging a_ = logging.get_logger(__name__) a_ = { """bert-base-uncased""": """https://huggingface.co/bert-base-uncased/resolve/main/config.json""", """bert-large-uncased""": """https://huggingface.co/bert-large-uncased/resolve/main/config.json""", """bert-base-cased""": """https://huggingface.co/bert-base-cased/resolve/main/config.json""", """bert-large-cased""": """https://huggingface.co/bert-large-cased/resolve/main/config.json""", """bert-base-multilingual-uncased""": """https://huggingface.co/bert-base-multilingual-uncased/resolve/main/config.json""", """bert-base-multilingual-cased""": """https://huggingface.co/bert-base-multilingual-cased/resolve/main/config.json""", """bert-base-chinese""": """https://huggingface.co/bert-base-chinese/resolve/main/config.json""", """bert-base-german-cased""": """https://huggingface.co/bert-base-german-cased/resolve/main/config.json""", """bert-large-uncased-whole-word-masking""": ( """https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/config.json""" ), """bert-large-cased-whole-word-masking""": ( """https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/config.json""" ), """bert-large-uncased-whole-word-masking-finetuned-squad""": ( """https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/config.json""" ), """bert-large-cased-whole-word-masking-finetuned-squad""": ( """https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/config.json""" ), """bert-base-cased-finetuned-mrpc""": """https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/config.json""", """bert-base-german-dbmdz-cased""": """https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/config.json""", """bert-base-german-dbmdz-uncased""": """https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/config.json""", """cl-tohoku/bert-base-japanese""": """https://huggingface.co/cl-tohoku/bert-base-japanese/resolve/main/config.json""", """cl-tohoku/bert-base-japanese-whole-word-masking""": ( """https://huggingface.co/cl-tohoku/bert-base-japanese-whole-word-masking/resolve/main/config.json""" ), """cl-tohoku/bert-base-japanese-char""": ( """https://huggingface.co/cl-tohoku/bert-base-japanese-char/resolve/main/config.json""" ), """cl-tohoku/bert-base-japanese-char-whole-word-masking""": ( """https://huggingface.co/cl-tohoku/bert-base-japanese-char-whole-word-masking/resolve/main/config.json""" ), """TurkuNLP/bert-base-finnish-cased-v1""": ( """https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/config.json""" ), """TurkuNLP/bert-base-finnish-uncased-v1""": ( """https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/config.json""" ), """wietsedv/bert-base-dutch-cased""": """https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/config.json""", # See all BERT models at https://huggingface.co/models?filter=bert } class __snake_case ( SCREAMING_SNAKE_CASE__ ): """simple docstring""" _lowerCamelCase = """bert""" def __init__( self , __lowerCamelCase=3_0522 , __lowerCamelCase=768 , __lowerCamelCase=12 , __lowerCamelCase=12 , __lowerCamelCase=3072 , __lowerCamelCase="gelu" , __lowerCamelCase=0.1 , __lowerCamelCase=0.1 , __lowerCamelCase=512 , __lowerCamelCase=2 , __lowerCamelCase=0.0_2 , __lowerCamelCase=1e-1_2 , __lowerCamelCase=0 , __lowerCamelCase="absolute" , __lowerCamelCase=True , __lowerCamelCase=None , **__lowerCamelCase , ): '''simple docstring''' super().__init__(pad_token_id=__lowerCamelCase , **__lowerCamelCase ) __A : Dict = vocab_size __A : Any = hidden_size __A : str = num_hidden_layers __A : int = num_attention_heads __A : Optional[int] = hidden_act __A : List[Any] = intermediate_size __A : Tuple = hidden_dropout_prob __A : Optional[int] = attention_probs_dropout_prob __A : Optional[int] = max_position_embeddings __A : Optional[Any] = type_vocab_size __A : Optional[Any] = initializer_range __A : Dict = layer_norm_eps __A : Any = position_embedding_type __A : Optional[int] = use_cache __A : str = classifier_dropout class __snake_case ( SCREAMING_SNAKE_CASE__ ): """simple docstring""" @property def UpperCamelCase__( self ): '''simple docstring''' if self.task == "multiple-choice": __A : str = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: __A : Tuple = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ('''token_type_ids''', dynamic_axis), ] )
179
1
import fire from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoTokenizer from utils import SeqaSeqDataset, pickle_save def lowerCAmelCase__ ( a__ , a__ , a__=1_024 , a__=1_024 , a__=False , **a__ ) ->int: '''simple docstring''' _UpperCamelCase = AutoTokenizer.from_pretrained(a__ ) _UpperCamelCase = SeqaSeqDataset(a__ , a__ , a__ , a__ , type_path="train" , **a__ ) _UpperCamelCase = tok.pad_token_id def get_lens(a__ ): _UpperCamelCase = tqdm( DataLoader(a__ , batch_size=512 , num_workers=8 , shuffle=a__ , collate_fn=ds.collate_fn ) , desc=str(ds.len_file ) , ) _UpperCamelCase = [] for batch in dl: _UpperCamelCase = batch["input_ids"].ne(a__ ).sum(1 ).tolist() _UpperCamelCase = batch["labels"].ne(a__ ).sum(1 ).tolist() if consider_target: for src, tgt in zip(a__ , a__ ): max_lens.append(max(a__ , a__ ) ) else: max_lens.extend(a__ ) return max_lens _UpperCamelCase = get_lens(a__ ) _UpperCamelCase = SeqaSeqDataset(a__ , a__ , a__ , a__ , type_path="val" , **a__ ) _UpperCamelCase = get_lens(a__ ) pickle_save(a__ , train_ds.len_file ) pickle_save(a__ , val_ds.len_file ) if __name__ == "__main__": fire.Fire(save_len_file)
63
import requests from bsa import BeautifulSoup def lowerCAmelCase__ ( a__ = "https://www.worldometers.info/coronavirus" ) ->dict: '''simple docstring''' _UpperCamelCase = BeautifulSoup(requests.get(a__ ).text , "html.parser" ) _UpperCamelCase = soup.findAll("h1" ) _UpperCamelCase = soup.findAll("div" , {"class": "maincounter-number"} ) keys += soup.findAll("span" , {"class": "panel-title"} ) values += soup.findAll("div" , {"class": "number-table-main"} ) return {key.text.strip(): value.text.strip() for key, value in zip(a__ , a__ )} if __name__ == "__main__": print('''\033[1m''' + '''COVID-19 Status of the World''' + '''\033[0m\n''') for key, value in world_covidaa_stats().items(): print(F"{key}\n{value}\n")
63
1
from __future__ import annotations def __UpperCAmelCase ( __a : list[int] ) -> int: """simple docstring""" if not nums: return 0 _a : Optional[int] = nums[0] _a : str = 0 for num in nums[1:]: _a : List[Any] = ( max_excluding + num, max(_lowerCamelCase ,_lowerCamelCase ), ) return max(_lowerCamelCase ,_lowerCamelCase ) if __name__ == "__main__": import doctest doctest.testmod()
235
import inspect import unittest import numpy as np from transformers import ViTConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor if is_flax_available(): import jax from transformers.models.vit.modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel class lowerCamelCase__ ( unittest.TestCase): '''simple docstring''' def __init__( self :List[str] , a :Any , a :List[Any]=1_3 , a :Any=3_0 , a :Dict=2 , a :List[str]=3 , a :Union[str, Any]=True , a :Optional[int]=True , a :Tuple=3_2 , a :Any=5 , a :List[str]=4 , a :Optional[Any]=3_7 , a :List[Any]="gelu" , a :Any=0.1 , a :Any=0.1 , a :List[str]=1_0 , a :str=0.02 , ) -> Union[str, Any]: __UpperCamelCase : int = parent __UpperCamelCase : List[Any] = batch_size __UpperCamelCase : Optional[Any] = image_size __UpperCamelCase : int = patch_size __UpperCamelCase : Optional[Any] = num_channels __UpperCamelCase : Optional[int] = is_training __UpperCamelCase : Union[str, Any] = use_labels __UpperCamelCase : Tuple = hidden_size __UpperCamelCase : List[Any] = num_hidden_layers __UpperCamelCase : List[Any] = num_attention_heads __UpperCamelCase : Dict = intermediate_size __UpperCamelCase : Optional[int] = hidden_act __UpperCamelCase : List[Any] = hidden_dropout_prob __UpperCamelCase : str = attention_probs_dropout_prob __UpperCamelCase : List[str] = type_sequence_label_size __UpperCamelCase : List[str] = initializer_range # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) __UpperCamelCase : Union[str, Any] = (image_size // patch_size) ** 2 __UpperCamelCase : Optional[int] = num_patches + 1 def _lowerCamelCase ( self :Optional[int] ) -> Union[str, Any]: __UpperCamelCase : Optional[int] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __UpperCamelCase : Tuple = ViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=a , initializer_range=self.initializer_range , ) return config, pixel_values def _lowerCamelCase ( self :Tuple , a :Optional[int] , a :Optional[int] ) -> Optional[int]: __UpperCamelCase : Optional[Any] = FlaxViTModel(config=a ) __UpperCamelCase : int = model(a ) # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token) __UpperCamelCase : Any = (self.image_size, self.image_size) __UpperCamelCase : Optional[int] = (self.patch_size, self.patch_size) __UpperCamelCase : Optional[int] = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, num_patches + 1, self.hidden_size) ) def _lowerCamelCase ( self :Dict , a :List[str] , a :Any ) -> str: __UpperCamelCase : Dict = self.type_sequence_label_size __UpperCamelCase : Dict = FlaxViTForImageClassification(config=a ) __UpperCamelCase : Tuple = model(a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images __UpperCamelCase : Dict = 1 __UpperCamelCase : Optional[Any] = FlaxViTForImageClassification(a ) __UpperCamelCase : List[str] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __UpperCamelCase : str = model(a ) def _lowerCamelCase ( self :str ) -> Optional[int]: __UpperCamelCase : str = self.prepare_config_and_inputs() ( ( __UpperCamelCase ) , ( __UpperCamelCase ) , ) : List[Any] = config_and_inputs __UpperCamelCase : str = {"pixel_values": pixel_values} return config, inputs_dict @require_flax class lowerCamelCase__ ( __lowercase , unittest.TestCase): '''simple docstring''' _A = (FlaxViTModel, FlaxViTForImageClassification) if is_flax_available() else () def _lowerCamelCase ( self :Optional[int] ) -> None: __UpperCamelCase : int = FlaxViTModelTester(self ) __UpperCamelCase : Any = ConfigTester(self , config_class=a , has_text_modality=a , hidden_size=3_7 ) def _lowerCamelCase ( self :List[Any] ) -> str: self.config_tester.run_common_tests() def _lowerCamelCase ( self :List[Any] ) -> List[str]: __UpperCamelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a ) def _lowerCamelCase ( self :List[str] ) -> Union[str, Any]: __UpperCamelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a ) def _lowerCamelCase ( self :Tuple ) -> Any: __UpperCamelCase , __UpperCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __UpperCamelCase : List[Any] = model_class(a ) __UpperCamelCase : Optional[int] = inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __UpperCamelCase : Dict = [*signature.parameters.keys()] __UpperCamelCase : Any = ["pixel_values"] self.assertListEqual(arg_names[:1] , a ) def _lowerCamelCase ( self :str ) -> Any: __UpperCamelCase , __UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __UpperCamelCase : List[Any] = self._prepare_for_class(a , a ) __UpperCamelCase : List[Any] = model_class(a ) @jax.jit def model_jitted(a :List[str] , **a :List[Any] ): return model(pixel_values=a , **a ) with self.subTest("JIT Enabled" ): __UpperCamelCase : int = model_jitted(**a ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): __UpperCamelCase : Optional[Any] = model_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 _lowerCamelCase ( self :Dict ) -> str: for model_class_name in self.all_model_classes: __UpperCamelCase : List[Any] = model_class_name.from_pretrained("google/vit-base-patch16-224" ) __UpperCamelCase : Optional[int] = model(np.ones((1, 3, 2_2_4, 2_2_4) ) ) self.assertIsNotNone(a )
232
0
'''simple docstring''' from __future__ import annotations import copy import inspect import json import math import os import tempfile import unittest from importlib import import_module import numpy as np from transformers import ViTMAEConfig from transformers.file_utils import cached_property, is_tf_available, is_vision_available from transformers.testing_utils import require_tf, require_vision, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFViTMAEForPreTraining, TFViTMAEModel if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class a : def __init__( self , __magic_name__ , __magic_name__=13 , __magic_name__=30 , __magic_name__=2 , __magic_name__=3 , __magic_name__=True , __magic_name__=True , __magic_name__=32 , __magic_name__=2 , __magic_name__=4 , __magic_name__=37 , __magic_name__="gelu" , __magic_name__=0.1 , __magic_name__=0.1 , __magic_name__=10 , __magic_name__=0.0_2 , __magic_name__=3 , __magic_name__=0.6 , __magic_name__=None , ) -> int: _a = parent _a = batch_size _a = image_size _a = patch_size _a = num_channels _a = is_training _a = use_labels _a = hidden_size _a = num_hidden_layers _a = num_attention_heads _a = intermediate_size _a = hidden_act _a = hidden_dropout_prob _a = attention_probs_dropout_prob _a = type_sequence_label_size _a = initializer_range _a = mask_ratio _a = scope # in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above # (we add 1 for the [CLS] token) _a = (image_size // patch_size) ** 2 _a = int(math.ceil((1 - mask_ratio) * (num_patches + 1) ) ) def __UpperCAmelCase ( self ) -> Optional[Any]: _a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _a = None if self.use_labels: _a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _a = self.get_config() return config, pixel_values, labels def __UpperCAmelCase ( self ) -> Any: return ViTMAEConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , decoder_hidden_size=self.hidden_size , decoder_num_hidden_layers=self.num_hidden_layers , decoder_num_attention_heads=self.num_attention_heads , decoder_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=__magic_name__ , initializer_range=self.initializer_range , mask_ratio=self.mask_ratio , ) def __UpperCAmelCase ( self , __magic_name__ , __magic_name__ , __magic_name__ ) -> Union[str, Any]: _a = TFViTMAEModel(config=__magic_name__ ) _a = model(__magic_name__ , training=__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self , __magic_name__ , __magic_name__ , __magic_name__ ) -> str: _a = TFViTMAEForPreTraining(__magic_name__ ) _a = model(__magic_name__ , training=__magic_name__ ) # expected sequence length = num_patches _a = (self.image_size // self.patch_size) ** 2 _a = self.patch_size**2 * self.num_channels self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) # test greyscale images _a = 1 _a = TFViTMAEForPreTraining(__magic_name__ ) _a = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) _a = model(__magic_name__ , training=__magic_name__ ) _a = self.patch_size**2 self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) def __UpperCAmelCase ( self ) -> List[Any]: _a = self.prepare_config_and_inputs() ((_a) , (_a) , (_a)) = config_and_inputs _a = {'pixel_values': pixel_values} return config, inputs_dict @require_tf class a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , unittest.TestCase ): _lowerCAmelCase = (TFViTMAEModel, TFViTMAEForPreTraining) if is_tf_available() else () _lowerCAmelCase = {"""feature-extraction""": TFViTMAEModel} if is_tf_available() else {} _lowerCAmelCase = False _lowerCAmelCase = False _lowerCAmelCase = False _lowerCAmelCase = False def __UpperCAmelCase ( self ) -> Union[str, Any]: _a = TFViTMAEModelTester(self ) _a = ConfigTester(self , config_class=__magic_name__ , has_text_modality=__magic_name__ , hidden_size=37 ) def __UpperCAmelCase ( self ) -> Tuple: self.config_tester.run_common_tests() @unittest.skip(reason='ViTMAE does not use inputs_embeds' ) def __UpperCAmelCase ( self ) -> str: pass def __UpperCAmelCase ( self ) -> List[str]: _a , _a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a = model_class(__magic_name__ ) self.assertIsInstance(model.get_input_embeddings() , (tf.keras.layers.Layer) ) _a = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__magic_name__ , tf.keras.layers.Layer ) ) def __UpperCAmelCase ( self ) -> List[Any]: _a , _a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a = model_class(__magic_name__ ) _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] , __magic_name__ ) def __UpperCAmelCase ( self ) -> List[str]: _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__magic_name__ ) def __UpperCAmelCase ( self ) -> Any: _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*__magic_name__ ) def __UpperCAmelCase ( self ) -> List[Any]: # make the mask reproducible np.random.seed(2 ) _a , _a = self.model_tester.prepare_config_and_inputs_for_common() _a = int((config.image_size // config.patch_size) ** 2 ) _a = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) for model_class in self.all_model_classes: _a = model_class(__magic_name__ ) _a = self._prepare_for_class(__magic_name__ , __magic_name__ ) _a = model(__magic_name__ , noise=__magic_name__ ) _a = copy.deepcopy(self._prepare_for_class(__magic_name__ , __magic_name__ ) ) _a = model(**__magic_name__ , noise=__magic_name__ ) _a = outputs_dict[0].numpy() _a = outputs_keywords[0].numpy() self.assertLess(np.sum(np.abs(output_dict - output_keywords ) ) , 1e-6 ) def __UpperCAmelCase ( self ) -> Dict: # make the mask reproducible np.random.seed(2 ) _a , _a = self.model_tester.prepare_config_and_inputs_for_common() _a = int((config.image_size // config.patch_size) ** 2 ) _a = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) def prepare_numpy_arrays(__magic_name__ ): _a = {} for k, v in inputs_dict.items(): if tf.is_tensor(__magic_name__ ): _a = v.numpy() else: _a = np.array(__magic_name__ ) return inputs_np_dict for model_class in self.all_model_classes: _a = model_class(__magic_name__ ) _a = self._prepare_for_class(__magic_name__ , __magic_name__ ) _a = prepare_numpy_arrays(__magic_name__ ) _a = model(__magic_name__ , noise=__magic_name__ ) _a = model(**__magic_name__ , noise=__magic_name__ ) self.assert_outputs_same(__magic_name__ , __magic_name__ ) def __UpperCAmelCase ( self , __magic_name__ , __magic_name__ , __magic_name__ ) -> int: # make masks reproducible np.random.seed(2 ) _a = int((tf_model.config.image_size // tf_model.config.patch_size) ** 2 ) _a = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) _a = tf.constant(__magic_name__ ) # Add `noise` argument. # PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument _a = tf_noise super().check_pt_tf_models(__magic_name__ , __magic_name__ , __magic_name__ ) def __UpperCAmelCase ( self ) -> Tuple: # make mask reproducible np.random.seed(2 ) _a , _a = self.model_tester.prepare_config_and_inputs_for_common() _a = { module_member for model_class in self.all_model_classes for module in (import_module(model_class.__module__ ),) for module_member_name in dir(__magic_name__ ) if module_member_name.endswith('MainLayer' ) # This condition is required, since `modeling_tf_clip.py` has 3 classes whose names end with `MainLayer`. and module_member_name[: -len('MainLayer' )] == model_class.__name__[: -len('Model' )] for module_member in (getattr(__magic_name__ , __magic_name__ ),) if isinstance(__magic_name__ , __magic_name__ ) and tf.keras.layers.Layer in module_member.__bases__ and getattr(__magic_name__ , '_keras_serializable' , __magic_name__ ) } _a = int((config.image_size // config.patch_size) ** 2 ) _a = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) _a = tf.convert_to_tensor(__magic_name__ ) inputs_dict.update({'noise': noise} ) for main_layer_class in tf_main_layer_classes: _a = main_layer_class(__magic_name__ ) _a = { name: tf.keras.Input(tensor.shape[1:] , dtype=tensor.dtype ) for name, tensor in inputs_dict.items() } _a = tf.keras.Model(__magic_name__ , outputs=main_layer(__magic_name__ ) ) _a = model(__magic_name__ ) with tempfile.TemporaryDirectory() as tmpdirname: _a = os.path.join(__magic_name__ , 'keras_model.h5' ) model.save(__magic_name__ ) _a = tf.keras.models.load_model( __magic_name__ , custom_objects={main_layer_class.__name__: main_layer_class} ) assert isinstance(__magic_name__ , tf.keras.Model ) _a = model(__magic_name__ ) self.assert_outputs_same(__magic_name__ , __magic_name__ ) @slow def __UpperCAmelCase ( self ) -> Optional[int]: # make mask reproducible np.random.seed(2 ) _a , _a = self.model_tester.prepare_config_and_inputs_for_common() _a = int((config.image_size // config.patch_size) ** 2 ) _a = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) for model_class in self.all_model_classes: _a = model_class(__magic_name__ ) _a = self._prepare_for_class(__magic_name__ , __magic_name__ ) _a = model(__magic_name__ , noise=__magic_name__ ) if model_class.__name__ == "TFViTMAEModel": _a = outputs.last_hidden_state.numpy() _a = 0 else: _a = outputs.logits.numpy() _a = 0 with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(__magic_name__ , saved_model=__magic_name__ ) _a = model_class.from_pretrained(__magic_name__ ) _a = model(__magic_name__ , noise=__magic_name__ ) if model_class.__name__ == "TFViTMAEModel": _a = after_outputs['last_hidden_state'].numpy() _a = 0 else: _a = after_outputs['logits'].numpy() _a = 0 _a = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(__magic_name__ , 1e-5 ) def __UpperCAmelCase ( self ) -> Optional[Any]: # make mask reproducible np.random.seed(2 ) _a , _a = self.model_tester.prepare_config_and_inputs_for_common() _a = int((config.image_size // config.patch_size) ** 2 ) _a = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) for model_class in self.all_model_classes: _a = model_class(__magic_name__ ) _a = self._prepare_for_class(__magic_name__ , __magic_name__ ) _a = model(__magic_name__ , noise=__magic_name__ ) _a = model.get_config() # make sure that returned config is jsonifiable, which is required by keras json.dumps(__magic_name__ ) _a = model_class.from_config(model.get_config() ) # make sure it also accepts a normal config _a = model_class.from_config(model.config ) _a = new_model(__magic_name__ ) # Build model new_model.set_weights(model.get_weights() ) _a = new_model(__magic_name__ , noise=__magic_name__ ) self.assert_outputs_same(__magic_name__ , __magic_name__ ) @unittest.skip( reason='ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load\n to get deterministic results.' ) def __UpperCAmelCase ( self ) -> str: pass @unittest.skip(reason='ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load' ) def __UpperCAmelCase ( self ) -> int: pass @slow def __UpperCAmelCase ( self ) -> List[Any]: _a = TFViTMAEModel.from_pretrained('google/vit-base-patch16-224' ) self.assertIsNotNone(__magic_name__ ) def _A () -> Optional[int]: '''simple docstring''' _a = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf @require_vision class a ( unittest.TestCase ): @cached_property def __UpperCAmelCase ( self ) -> int: return ViTImageProcessor.from_pretrained('facebook/vit-mae-base' ) if is_vision_available() else None @slow def __UpperCAmelCase ( self ) -> Union[str, Any]: # make random mask reproducible across the PT and TF model np.random.seed(2 ) _a = TFViTMAEForPreTraining.from_pretrained('facebook/vit-mae-base' ) _a = self.default_image_processor _a = prepare_img() _a = image_processor(images=__magic_name__ , return_tensors='tf' ) # prepare a noise vector that will be also used for testing the TF model # (this way we can ensure that the PT and TF models operate on the same inputs) _a = ViTMAEConfig() _a = int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2 ) _a = np.random.uniform(size=(1, num_patches) ) # forward pass _a = model(**__magic_name__ , noise=__magic_name__ ) # verify the logits _a = tf.convert_to_tensor([1, 1_96, 7_68] ) self.assertEqual(outputs.logits.shape , __magic_name__ ) _a = tf.convert_to_tensor( [[-0.0_5_4_8, -1.7_0_2_3, -0.9_3_2_5], [0.3_7_2_1, -0.5_6_7_0, -0.2_2_3_3], [0.8_2_3_5, -1.3_8_7_8, -0.3_5_2_4]] ) tf.debugging.assert_near(outputs.logits[0, :3, :3] , __magic_name__ , atol=1e-4 )
360
'''simple docstring''' from __future__ import annotations def _A (lowerCAmelCase__ :int ) -> list[int]: '''simple docstring''' _a = 2 _a = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(lowerCAmelCase__ ) if n > 1: factors.append(lowerCAmelCase__ ) return factors if __name__ == "__main__": import doctest doctest.testmod()
104
0
from typing import Callable, Optional from .. import Features from ..packaged_modules.generator.generator import Generator from .abc import AbstractDatasetInputStream class SCREAMING_SNAKE_CASE__ ( lowercase__ ): def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Callable , SCREAMING_SNAKE_CASE__ : Optional[Features] = None , SCREAMING_SNAKE_CASE__ : str = None , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : Optional[dict] = None , SCREAMING_SNAKE_CASE__ : Optional[int] = None , **SCREAMING_SNAKE_CASE__ : Dict , ) -> List[Any]: super().__init__( features=__UpperCAmelCase , cache_dir=__UpperCAmelCase , keep_in_memory=__UpperCAmelCase , streaming=__UpperCAmelCase , num_proc=__UpperCAmelCase , **__UpperCAmelCase , ) a_ : Union[str, Any] = Generator( cache_dir=__UpperCAmelCase , features=__UpperCAmelCase , generator=__UpperCAmelCase , gen_kwargs=__UpperCAmelCase , **__UpperCAmelCase , ) def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Tuple: if self.streaming: a_ : int = self.builder.as_streaming_dataset(split='train' ) # Build regular (map-style) dataset else: a_ : Union[str, Any] = None a_ : Optional[Any] = None a_ : Any = None a_ : int = None self.builder.download_and_prepare( download_config=__UpperCAmelCase , download_mode=__UpperCAmelCase , verification_mode=__UpperCAmelCase , base_path=__UpperCAmelCase , num_proc=self.num_proc , ) a_ : List[Any] = self.builder.as_dataset( split='train' , verification_mode=__UpperCAmelCase , in_memory=self.keep_in_memory ) return dataset
32
from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = { "t5-small": "https://huggingface.co/t5-small/resolve/main/config.json", "t5-base": "https://huggingface.co/t5-base/resolve/main/config.json", "t5-large": "https://huggingface.co/t5-large/resolve/main/config.json", "t5-3b": "https://huggingface.co/t5-3b/resolve/main/config.json", "t5-11b": "https://huggingface.co/t5-11b/resolve/main/config.json", } class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = '''t5''' __snake_case = ['''past_key_values'''] __snake_case = {'''hidden_size''': '''d_model''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers'''} def __init__( self : Optional[Any] , __UpperCAmelCase : Optional[Any]=32_128 , __UpperCAmelCase : List[Any]=512 , __UpperCAmelCase : Dict=64 , __UpperCAmelCase : Tuple=2_048 , __UpperCAmelCase : int=6 , __UpperCAmelCase : Optional[int]=None , __UpperCAmelCase : Optional[int]=8 , __UpperCAmelCase : str=32 , __UpperCAmelCase : Tuple=128 , __UpperCAmelCase : Optional[Any]=0.1 , __UpperCAmelCase : int=1e-6 , __UpperCAmelCase : int=1.0 , __UpperCAmelCase : List[str]="relu" , __UpperCAmelCase : int=True , __UpperCAmelCase : int=True , __UpperCAmelCase : List[Any]=0 , __UpperCAmelCase : int=1 , **__UpperCAmelCase : str , ) ->Optional[Any]: """simple docstring""" a = vocab_size a = d_model a = d_kv a = d_ff a = num_layers a = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry a = num_heads a = relative_attention_num_buckets a = relative_attention_max_distance a = dropout_rate a = layer_norm_epsilon a = initializer_factor a = feed_forward_proj a = use_cache a = self.feed_forward_proj.split('''-''' ) a = act_info[-1] a = act_info[0] == '''gated''' if len(__UpperCAmelCase ) > 1 and act_info[0] != "gated" or len(__UpperCAmelCase ) > 2: raise ValueError( F"""`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.""" '''Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. ''' '''\'gated-gelu\' or \'relu\'''' ) # for backwards compatibility if feed_forward_proj == "gated-gelu": a = '''gelu_new''' super().__init__( pad_token_id=__UpperCAmelCase , eos_token_id=__UpperCAmelCase , is_encoder_decoder=__UpperCAmelCase , **__UpperCAmelCase , ) class lowercase_ ( lowercase ): '''simple docstring''' @property def __lowerCAmelCase ( self : Optional[Any] ) ->Mapping[str, Mapping[int, str]]: """simple docstring""" a = { '''input_ids''': {0: '''batch''', 1: '''encoder_sequence'''}, '''attention_mask''': {0: '''batch''', 1: '''encoder_sequence'''}, } if self.use_past: a = '''past_encoder_sequence + sequence''' a = {0: '''batch'''} a = {0: '''batch''', 1: '''past_decoder_sequence + sequence'''} else: a = {0: '''batch''', 1: '''decoder_sequence'''} a = {0: '''batch''', 1: '''decoder_sequence'''} if self.use_past: self.fill_with_past_key_values_(__UpperCAmelCase , direction='''inputs''' ) return common_inputs @property def __lowerCAmelCase ( self : Union[str, Any] ) ->int: """simple docstring""" return 13
0
0
"""simple docstring""" from functools import reduce __magic_name__ = ( "73167176531330624919225119674426574742355349194934" "96983520312774506326239578318016984801869478851843" "85861560789112949495459501737958331952853208805511" "12540698747158523863050715693290963295227443043557" "66896648950445244523161731856403098711121722383113" "62229893423380308135336276614282806444486645238749" "30358907296290491560440772390713810515859307960866" "70172427121883998797908792274921901699720888093776" "65727333001053367881220235421809751254540594752243" "52584907711670556013604839586446706324415722155397" "53697817977846174064955149290862569321978468622482" "83972241375657056057490261407972968652414535100474" "82166370484403199890008895243450658541227588666881" "16427171479924442928230863465674813919123162824586" "17866458359124566529476545682848912883142607690042" "24219022671055626321111109370544217506941658960408" "07198403850962455444362981230987879927244284909188" "84580156166097919133875499200524063689912560717606" "05886116467109405077541002256983155200055935729725" "71636269561882670428252483600823257530420752963450" ) def _lowerCAmelCase ( A__: Any = N ): '''simple docstring''' return max( # mypy cannot properly interpret reduce int(reduce(lambda A__ , A__ : str(int(a__ ) * int(a__ ) ) , n[i : i + 13] ) ) for i in range(len(a__ ) - 12 ) ) if __name__ == "__main__": print(f'''{solution() = }''')
369
# Function to print upper half of diamond (pyramid) def _lowerCAmelCase ( A__: str ): '''simple docstring''' for i in range(0 , A__ ): for _ in range(0 , n - i - 1 ): # printing spaces print(''' ''' , end='''''' ) for _ in range(0 , i + 1 ): # printing stars print('''* ''' , end='''''' ) print() def _lowerCAmelCase ( A__: Optional[int] ): '''simple docstring''' for i in range(A__ , 0 , -1 ): for _ in range(A__ , 0 , -1 ): # printing stars print('''* ''' , end='''''' ) print() for _ in range(n - i + 1 , 0 , -1 ): # printing spaces print(''' ''' , end='''''' ) def _lowerCAmelCase ( A__: str ): '''simple docstring''' if n <= 0: print(''' ... .... nothing printing :(''' ) return floyd(A__ ) # upper half reverse_floyd(A__ ) # lower half if __name__ == "__main__": print(r"| /\ | |- | |- |--| |\ /| |-") print(r"|/ \| |- |_ |_ |__| | \/ | |_") __magic_name__ = 1 while K: __magic_name__ = int(input("enter the number and , and see the magic : ")) print() pretty_print(user_number) __magic_name__ = int(input("press 0 to exit... and 1 to continue...")) print("Good Bye...")
152
0