code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_torch_available, ) A__: Any = { '''configuration_speecht5''': [ '''SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP''', '''SpeechT5Config''', '''SpeechT5HifiGanConfig''', ], '''feature_extraction_speecht5''': ['''SpeechT5FeatureExtractor'''], '''processing_speecht5''': ['''SpeechT5Processor'''], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: str = ['''SpeechT5Tokenizer'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Tuple = [ '''SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST''', '''SpeechT5ForSpeechToText''', '''SpeechT5ForSpeechToSpeech''', '''SpeechT5ForTextToSpeech''', '''SpeechT5Model''', '''SpeechT5PreTrainedModel''', '''SpeechT5HifiGan''', ] if TYPE_CHECKING: from .configuration_speechta import ( SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP, SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP, SpeechTaConfig, SpeechTaHifiGanConfig, ) from .feature_extraction_speechta import SpeechTaFeatureExtractor from .processing_speechta import SpeechTaProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speechta import SpeechTaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speechta import ( SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechTaForSpeechToSpeech, SpeechTaForSpeechToText, SpeechTaForTextToSpeech, SpeechTaHifiGan, SpeechTaModel, SpeechTaPreTrainedModel, ) else: import sys A__: int = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
276
'''simple docstring''' import contextlib import os import sqlitea import pytest from datasets import Dataset, Features, Value from datasets.io.sql import SqlDatasetReader, SqlDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases, require_sqlalchemy def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Any ,_UpperCAmelCase : str ) -> Dict: assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ) 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 @require_sqlalchemy @pytest.mark.parametrize("""keep_in_memory""" ,[False, True] ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Optional[int] ,_UpperCAmelCase : str ) -> Optional[Any]: _a : Any =tmp_path / """cache""" _a : int ={"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): _a : Tuple =SqlDatasetReader( """dataset""" ,"""sqlite:///""" + sqlite_path ,cache_dir=_UpperCAmelCase ,keep_in_memory=_UpperCAmelCase ).read() _check_sql_dataset(_UpperCAmelCase ,_UpperCAmelCase ) @require_sqlalchemy @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 SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[Any] ,_UpperCAmelCase : Dict ,_UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : int ) -> List[Any]: _a : Union[str, Any] =tmp_path / """cache""" _a : str ={"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} _a : Optional[int] =features.copy() if features else default_expected_features _a : Union[str, Any] =( Features({feature: Value(_UpperCAmelCase ) for feature, dtype in features.items()} ) if features is not None else None ) _a : Optional[Any] =SqlDatasetReader("""dataset""" ,"""sqlite:///""" + sqlite_path ,features=_UpperCAmelCase ,cache_dir=_UpperCAmelCase ).read() _check_sql_dataset(_UpperCAmelCase ,_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[Any] ) -> List[str]: with contextlib.closing(sqlitea.connect(_UpperCAmelCase ) ) as con: _a : Any =con.cursor() cur.execute("""SELECT * FROM dataset""" ) for row in cur: yield row @require_sqlalchemy def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Dict ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : List[str] ) -> Union[str, Any]: _a : Union[str, Any] =tmp_path / """cache""" _a : Union[str, Any] =os.path.join(_UpperCAmelCase ,"""tmp.sql""" ) _a : Tuple =SqlDatasetReader("""dataset""" ,"""sqlite:///""" + sqlite_path ,cache_dir=_UpperCAmelCase ).read() SqlDatasetWriter(_UpperCAmelCase ,"""dataset""" ,"""sqlite:///""" + output_sqlite_path ,num_proc=1 ).write() _a : Tuple =iter_sql_file(_UpperCAmelCase ) _a : List[Any] =iter_sql_file(_UpperCAmelCase ) for rowa, rowa in zip(_UpperCAmelCase ,_UpperCAmelCase ): assert rowa == rowa @require_sqlalchemy def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Any ,_UpperCAmelCase : List[Any] ) -> Optional[int]: _a : int =tmp_path / """cache""" _a : Any =os.path.join(_UpperCAmelCase ,"""tmp.sql""" ) _a : Union[str, Any] =SqlDatasetReader("""dataset""" ,"""sqlite:///""" + sqlite_path ,cache_dir=_UpperCAmelCase ).read() SqlDatasetWriter(_UpperCAmelCase ,"""dataset""" ,"""sqlite:///""" + output_sqlite_path ,num_proc=2 ).write() _a : List[Any] =iter_sql_file(_UpperCAmelCase ) _a : str =iter_sql_file(_UpperCAmelCase ) for rowa, rowa in zip(_UpperCAmelCase ,_UpperCAmelCase ): assert rowa == rowa @require_sqlalchemy def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : str ,_UpperCAmelCase : List[Any] ) -> List[str]: _a : List[str] =tmp_path / """cache""" _a : Dict =os.path.join(_UpperCAmelCase ,"""tmp.sql""" ) _a : Optional[Any] =SqlDatasetReader("""dataset""" ,"""sqlite:///""" + sqlite_path ,cache_dir=_UpperCAmelCase ).read() with pytest.raises(_UpperCAmelCase ): SqlDatasetWriter(_UpperCAmelCase ,"""dataset""" ,"""sqlite:///""" + output_sqlite_path ,num_proc=0 ).write()
276
1
'''simple docstring''' from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL from ...utils import BaseOutput, OptionalDependencyNotAvailable, is_torch_available, is_transformers_available from .timesteps import ( fastaa_timesteps, smartaa_timesteps, smartaa_timesteps, smartaaa_timesteps, smartaaa_timesteps, superaa_timesteps, superaa_timesteps, superaaa_timesteps, ) @dataclass class A__ ( UpperCAmelCase__ ): __UpperCamelCase : Union[List[PIL.Image.Image], np.ndarray] __UpperCamelCase : Optional[List[bool]] __UpperCamelCase : Optional[List[bool]] try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipeline_if import IFPipeline from .pipeline_if_imgaimg import IFImgaImgPipeline from .pipeline_if_imgaimg_superresolution import IFImgaImgSuperResolutionPipeline from .pipeline_if_inpainting import IFInpaintingPipeline from .pipeline_if_inpainting_superresolution import IFInpaintingSuperResolutionPipeline from .pipeline_if_superresolution import IFSuperResolutionPipeline from .safety_checker import IFSafetyChecker from .watermark import IFWatermarker
276
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A__: List[str] = logging.get_logger(__name__) A__: Union[str, Any] = { '''facebook/data2vec-text-base''': '''https://huggingface.co/data2vec/resolve/main/config.json''', } class A__ ( UpperCAmelCase__ ): __UpperCamelCase : int = "data2vec-text" def __init__( self :str , SCREAMING_SNAKE_CASE :Optional[Any]=3_0_5_2_2 , SCREAMING_SNAKE_CASE :Any=7_6_8 , SCREAMING_SNAKE_CASE :List[Any]=1_2 , SCREAMING_SNAKE_CASE :List[str]=1_2 , SCREAMING_SNAKE_CASE :Dict=3_0_7_2 , SCREAMING_SNAKE_CASE :List[str]="gelu" , SCREAMING_SNAKE_CASE :Any=0.1 , SCREAMING_SNAKE_CASE :List[str]=0.1 , SCREAMING_SNAKE_CASE :int=5_1_2 , SCREAMING_SNAKE_CASE :int=2 , SCREAMING_SNAKE_CASE :Union[str, Any]=0.02 , SCREAMING_SNAKE_CASE :Dict=1e-12 , SCREAMING_SNAKE_CASE :int=1 , SCREAMING_SNAKE_CASE :Dict=0 , SCREAMING_SNAKE_CASE :List[Any]=2 , SCREAMING_SNAKE_CASE :str="absolute" , SCREAMING_SNAKE_CASE :Tuple=True , SCREAMING_SNAKE_CASE :Union[str, Any]=None , **SCREAMING_SNAKE_CASE :Union[str, Any] , ) -> List[str]: '''simple docstring''' super().__init__(pad_token_id=SCREAMING_SNAKE_CASE , bos_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) _a : Optional[Any] =vocab_size _a : Optional[Any] =hidden_size _a : Any =num_hidden_layers _a : List[str] =num_attention_heads _a : Union[str, Any] =hidden_act _a : Any =intermediate_size _a : str =hidden_dropout_prob _a : Optional[Any] =attention_probs_dropout_prob _a : Optional[Any] =max_position_embeddings _a : Union[str, Any] =type_vocab_size _a : Tuple =initializer_range _a : Optional[int] =layer_norm_eps _a : Tuple =position_embedding_type _a : int =use_cache _a : List[str] =classifier_dropout class A__ ( UpperCAmelCase__ ): @property def __UpperCAmelCase ( self :int ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' 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), ] )
276
1
'''simple docstring''' import json import os import unittest from transformers import OpenAIGPTTokenizer, OpenAIGPTTokenizerFast from transformers.models.openai.tokenization_openai import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_spacy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class A__ ( UpperCAmelCase__ , unittest.TestCase ): __UpperCamelCase : List[Any] = OpenAIGPTTokenizer __UpperCamelCase : Any = OpenAIGPTTokenizerFast __UpperCamelCase : Optional[int] = True __UpperCamelCase : Any = False def __UpperCAmelCase ( self :str ) -> Tuple: '''simple docstring''' super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt _a : Optional[int] =[ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """w</w>""", """r</w>""", """t</w>""", """lo""", """low""", """er</w>""", """low</w>""", """lowest</w>""", """newer</w>""", """wider</w>""", """<unk>""", ] _a : Optional[int] =dict(zip(SCREAMING_SNAKE_CASE , range(len(SCREAMING_SNAKE_CASE ) ) ) ) _a : Any =["""#version: 0.2""", """l o""", """lo w""", """e r</w>""", """"""] _a : Dict =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) _a : List[Any] =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" ) as fp: fp.write(json.dumps(SCREAMING_SNAKE_CASE ) ) with open(self.merges_file , """w""" ) as fp: fp.write("""\n""".join(SCREAMING_SNAKE_CASE ) ) def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :str ) -> Any: '''simple docstring''' return "lower newer", "lower newer" def __UpperCAmelCase ( self :Dict ) -> Optional[Any]: '''simple docstring''' _a : Dict =OpenAIGPTTokenizer(self.vocab_file , self.merges_file ) _a : Optional[int] ="""lower""" _a : int =["""low""", """er</w>"""] _a : List[Any] =tokenizer.tokenize(SCREAMING_SNAKE_CASE ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =tokens + ["""<unk>"""] _a : List[str] =[1_4, 1_5, 2_0] self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :int=1_5 ) -> Optional[Any]: '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})" ): _a : Any =self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) # Simple input _a : Optional[Any] ="""This is a simple input""" _a : Optional[Any] =["""This is a simple input 1""", """This is a simple input 2"""] _a : Tuple =("""This is a simple input""", """This is a pair""") _a : Union[str, Any] =[ ("""This is a simple input 1""", """This is a simple input 2"""), ("""This is a simple pair 1""", """This is a simple pair 2"""), ] # Simple input tests self.assertRaises(SCREAMING_SNAKE_CASE , tokenizer_r.encode , SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE , padding="""max_length""" ) # Simple input self.assertRaises(SCREAMING_SNAKE_CASE , tokenizer_r.encode_plus , SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE , padding="""max_length""" ) # Simple input self.assertRaises( SCREAMING_SNAKE_CASE , tokenizer_r.batch_encode_plus , SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE , padding="""max_length""" , ) # Pair input self.assertRaises(SCREAMING_SNAKE_CASE , tokenizer_r.encode , SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE , padding="""max_length""" ) # Pair input self.assertRaises(SCREAMING_SNAKE_CASE , tokenizer_r.encode_plus , SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE , padding="""max_length""" ) # Pair input self.assertRaises( SCREAMING_SNAKE_CASE , tokenizer_r.batch_encode_plus , SCREAMING_SNAKE_CASE , max_length=SCREAMING_SNAKE_CASE , padding="""max_length""" , ) def __UpperCAmelCase ( self :List[Any] ) -> List[Any]: '''simple docstring''' pass @require_ftfy @require_spacy @require_tokenizers class A__ ( UpperCAmelCase__ ): pass
276
'''simple docstring''' from typing import Dict, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import flip_channel_order, resize, to_channel_dimension_format, to_pil_image from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_pytesseract_available, is_vision_available, logging, requires_backends if is_vision_available(): import PIL # soft dependency if is_pytesseract_available(): import pytesseract A__: Union[str, Any] = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : List[str] ) -> int: return [ int(1000 * (box[0] / width) ), int(1000 * (box[1] / height) ), int(1000 * (box[2] / width) ), int(1000 * (box[3] / height) ), ] def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : np.ndarray ,_UpperCAmelCase : Optional[str] ,_UpperCAmelCase : Optional[str] = None ) -> Optional[int]: _a : Any =tesseract_config if tesseract_config is not None else """""" # apply OCR _a : Optional[Any] =to_pil_image(_UpperCAmelCase ) _a , _a : List[Any] =pil_image.size _a : List[str] =pytesseract.image_to_data(_UpperCAmelCase ,lang=_UpperCAmelCase ,output_type="""dict""" ,config=_UpperCAmelCase ) _a , _a , _a , _a , _a : str =data["""text"""], data["""left"""], data["""top"""], data["""width"""], data["""height"""] # filter empty words and corresponding coordinates _a : Tuple =[idx for idx, word in enumerate(_UpperCAmelCase ) if not word.strip()] _a : List[Any] =[word for idx, word in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] _a : Dict =[coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] _a : List[str] =[coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] _a : Union[str, Any] =[coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] _a : Union[str, Any] =[coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] # turn coordinates into (left, top, left+width, top+height) format _a : List[str] =[] for x, y, w, h in zip(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ): _a : int =[x, y, x + w, y + h] actual_boxes.append(_UpperCAmelCase ) # finally, normalize the bounding boxes _a : str =[] for box in actual_boxes: normalized_boxes.append(normalize_box(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) ) assert len(_UpperCAmelCase ) == len(_UpperCAmelCase ), "Not as many words as there are bounding boxes" return words, normalized_boxes class A__ ( UpperCAmelCase__ ): __UpperCamelCase : List[Any] = ["pixel_values"] def __init__( self :Tuple , SCREAMING_SNAKE_CASE :bool = True , SCREAMING_SNAKE_CASE :Dict[str, int] = None , SCREAMING_SNAKE_CASE :PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE :bool = True , SCREAMING_SNAKE_CASE :Optional[str] = None , SCREAMING_SNAKE_CASE :Optional[str] = "" , **SCREAMING_SNAKE_CASE :Tuple , ) -> None: '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE ) _a : List[Any] =size if size is not None else {"""height""": 2_2_4, """width""": 2_2_4} _a : Tuple =get_size_dict(SCREAMING_SNAKE_CASE ) _a : Dict =do_resize _a : Tuple =size _a : str =resample _a : Dict =apply_ocr _a : Union[str, Any] =ocr_lang _a : Dict =tesseract_config def __UpperCAmelCase ( self :List[str] , SCREAMING_SNAKE_CASE :np.ndarray , SCREAMING_SNAKE_CASE :Dict[str, int] , SCREAMING_SNAKE_CASE :PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE :Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE :Dict , ) -> np.ndarray: '''simple docstring''' _a : int =get_size_dict(SCREAMING_SNAKE_CASE ) if "height" not in size or "width" not in size: raise ValueError(f"The size dictionary must contain the keys 'height' and 'width'. Got {size.keys()}" ) _a : Any =(size["""height"""], size["""width"""]) return resize(SCREAMING_SNAKE_CASE , size=SCREAMING_SNAKE_CASE , resample=SCREAMING_SNAKE_CASE , data_format=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Dict , SCREAMING_SNAKE_CASE :ImageInput , SCREAMING_SNAKE_CASE :bool = None , SCREAMING_SNAKE_CASE :Dict[str, int] = None , SCREAMING_SNAKE_CASE :PILImageResampling = None , SCREAMING_SNAKE_CASE :bool = None , SCREAMING_SNAKE_CASE :Optional[str] = None , SCREAMING_SNAKE_CASE :Optional[str] = None , SCREAMING_SNAKE_CASE :Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE :ChannelDimension = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE :Optional[Any] , ) -> PIL.Image.Image: '''simple docstring''' _a : Optional[int] =do_resize if do_resize is not None else self.do_resize _a : Optional[int] =size if size is not None else self.size _a : str =get_size_dict(SCREAMING_SNAKE_CASE ) _a : List[str] =resample if resample is not None else self.resample _a : int =apply_ocr if apply_ocr is not None else self.apply_ocr _a : str =ocr_lang if ocr_lang is not None else self.ocr_lang _a : Union[str, Any] =tesseract_config if tesseract_config is not None else self.tesseract_config _a : List[str] =make_list_of_images(SCREAMING_SNAKE_CASE ) if not valid_images(SCREAMING_SNAKE_CASE ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None: raise ValueError("""Size must be specified if do_resize is True.""" ) # All transformations expect numpy arrays. _a : List[Any] =[to_numpy_array(SCREAMING_SNAKE_CASE ) for image in images] if apply_ocr: requires_backends(self , """pytesseract""" ) _a : Any =[] _a : Any =[] for image in images: _a , _a : int =apply_tesseract(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) words_batch.append(SCREAMING_SNAKE_CASE ) boxes_batch.append(SCREAMING_SNAKE_CASE ) if do_resize: _a : Union[str, Any] =[self.resize(image=SCREAMING_SNAKE_CASE , size=SCREAMING_SNAKE_CASE , resample=SCREAMING_SNAKE_CASE ) for image in images] # flip color channels from RGB to BGR (as Detectron2 requires this) _a : Dict =[flip_channel_order(SCREAMING_SNAKE_CASE ) for image in images] _a : str =[to_channel_dimension_format(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for image in images] _a : str =BatchFeature(data={"""pixel_values""": images} , tensor_type=SCREAMING_SNAKE_CASE ) if apply_ocr: _a : List[Any] =words_batch _a : Dict =boxes_batch return data
276
1
'''simple docstring''' import pytest from datasets.utils.sharding import _distribute_shards, _number_of_shards_in_gen_kwargs, _split_gen_kwargs @pytest.mark.parametrize( """kwargs, expected""" ,[ ({"""num_shards""": 0, """max_num_jobs""": 1}, []), ({"""num_shards""": 10, """max_num_jobs""": 1}, [range(10 )]), ({"""num_shards""": 10, """max_num_jobs""": 10}, [range(_UpperCAmelCase ,i + 1 ) for i in range(10 )]), ({"""num_shards""": 1, """max_num_jobs""": 10}, [range(1 )]), ({"""num_shards""": 10, """max_num_jobs""": 3}, [range(0 ,4 ), range(4 ,7 ), range(7 ,10 )]), ({"""num_shards""": 3, """max_num_jobs""": 10}, [range(0 ,1 ), range(1 ,2 ), range(2 ,3 )]), ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : Dict ) -> Optional[Any]: _a : Tuple =_distribute_shards(**_UpperCAmelCase ) assert out == expected @pytest.mark.parametrize( """gen_kwargs, max_num_jobs, expected""" ,[ ({"""foo""": 0}, 10, [{"""foo""": 0}]), ({"""shards""": [0, 1, 2, 3]}, 1, [{"""shards""": [0, 1, 2, 3]}]), ({"""shards""": [0, 1, 2, 3]}, 4, [{"""shards""": [0]}, {"""shards""": [1]}, {"""shards""": [2]}, {"""shards""": [3]}]), ({"""shards""": [0, 1]}, 4, [{"""shards""": [0]}, {"""shards""": [1]}]), ({"""shards""": [0, 1, 2, 3]}, 2, [{"""shards""": [0, 1]}, {"""shards""": [2, 3]}]), ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : List[Any] ,_UpperCAmelCase : Union[str, Any] ) -> List[str]: _a : List[str] =_split_gen_kwargs(_UpperCAmelCase ,_UpperCAmelCase ) assert out == expected @pytest.mark.parametrize( """gen_kwargs, expected""" ,[ ({"""foo""": 0}, 1), ({"""shards""": [0]}, 1), ({"""shards""": [0, 1, 2, 3]}, 4), ({"""shards""": [0, 1, 2, 3], """foo""": 0}, 4), ({"""shards""": [0, 1, 2, 3], """other""": (0, 1)}, 4), ({"""shards""": [0, 1, 2, 3], """shards2""": [0, 1]}, RuntimeError), ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : List[Any] ) -> Union[str, Any]: if expected is RuntimeError: with pytest.raises(_UpperCAmelCase ): _number_of_shards_in_gen_kwargs(_UpperCAmelCase ) else: _a : Dict =_number_of_shards_in_gen_kwargs(_UpperCAmelCase ) assert out == expected
276
'''simple docstring''' from __future__ import annotations import requests def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ) -> dict: _a : Any =F"https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty" return requests.get(_UpperCAmelCase ).json() def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int = 10 ) -> list[dict]: _a : Union[str, Any] ="""https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty""" _a : int =requests.get(_UpperCAmelCase ).json()[:max_stories] return [get_hackernews_story(_UpperCAmelCase ) for story_id in story_ids] def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int = 10 ) -> str: _a : Union[str, Any] =hackernews_top_stories(_UpperCAmelCase ) return "\n".join("""* [{title}]({url})""".format(**_UpperCAmelCase ) for story in stories ) if __name__ == "__main__": print(hackernews_top_stories_as_markdown())
276
1
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaImgaImgPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class A__ ( UpperCAmelCase__ , unittest.TestCase ): __UpperCamelCase : Tuple = KandinskyVaaImgaImgPipeline __UpperCamelCase : Dict = ["image_embeds", "negative_image_embeds", "image"] __UpperCamelCase : Tuple = [ "image_embeds", "negative_image_embeds", "image", ] __UpperCamelCase : Any = [ "generator", "height", "width", "strength", "guidance_scale", "num_inference_steps", "return_dict", "guidance_scale", "num_images_per_prompt", "output_type", "return_dict", ] __UpperCamelCase : Tuple = False @property def __UpperCAmelCase ( self :str ) -> Union[str, Any]: '''simple docstring''' return 3_2 @property def __UpperCAmelCase ( self :str ) -> str: '''simple docstring''' return 3_2 @property def __UpperCAmelCase ( self :Dict ) -> Any: '''simple docstring''' return self.time_input_dim @property def __UpperCAmelCase ( self :Optional[int] ) -> Any: '''simple docstring''' return self.time_input_dim * 4 @property def __UpperCAmelCase ( self :List[Any] ) -> List[str]: '''simple docstring''' return 1_0_0 @property def __UpperCAmelCase ( self :Dict ) -> List[Any]: '''simple docstring''' torch.manual_seed(0 ) _a : str ={ """in_channels""": 4, # Out channels is double in channels because predicts mean and variance """out_channels""": 8, """addition_embed_type""": """image""", """down_block_types""": ("""ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D"""), """up_block_types""": ("""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""), """mid_block_type""": """UNetMidBlock2DSimpleCrossAttn""", """block_out_channels""": (self.block_out_channels_a, self.block_out_channels_a * 2), """layers_per_block""": 1, """encoder_hid_dim""": self.text_embedder_hidden_size, """encoder_hid_dim_type""": """image_proj""", """cross_attention_dim""": self.cross_attention_dim, """attention_head_dim""": 4, """resnet_time_scale_shift""": """scale_shift""", """class_embed_type""": None, } _a : Union[str, Any] =UNetaDConditionModel(**SCREAMING_SNAKE_CASE ) return model @property def __UpperCAmelCase ( self :Optional[Any] ) -> Union[str, Any]: '''simple docstring''' return { "block_out_channels": [3_2, 6_4], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 1_2, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def __UpperCAmelCase ( self :Any ) -> Union[str, Any]: '''simple docstring''' torch.manual_seed(0 ) _a : Optional[Any] =VQModel(**self.dummy_movq_kwargs ) return model def __UpperCAmelCase ( self :Union[str, Any] ) -> Tuple: '''simple docstring''' _a : Optional[int] =self.dummy_unet _a : List[Any] =self.dummy_movq _a : List[str] ={ """num_train_timesteps""": 1_0_0_0, """beta_schedule""": """linear""", """beta_start""": 0.00_085, """beta_end""": 0.012, """clip_sample""": False, """set_alpha_to_one""": False, """steps_offset""": 0, """prediction_type""": """epsilon""", """thresholding""": False, } _a : List[Any] =DDIMScheduler(**SCREAMING_SNAKE_CASE ) _a : str ={ """unet""": unet, """scheduler""": scheduler, """movq""": movq, } return components def __UpperCAmelCase ( self :str , SCREAMING_SNAKE_CASE :List[Any] , SCREAMING_SNAKE_CASE :Tuple=0 ) -> Dict: '''simple docstring''' _a : str =floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(SCREAMING_SNAKE_CASE ) ).to(SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( SCREAMING_SNAKE_CASE ) # create init_image _a : Optional[int] =floats_tensor((1, 3, 6_4, 6_4) , rng=random.Random(SCREAMING_SNAKE_CASE ) ).to(SCREAMING_SNAKE_CASE ) _a : Any =image.cpu().permute(0 , 2 , 3 , 1 )[0] _a : Union[str, Any] =Image.fromarray(np.uinta(SCREAMING_SNAKE_CASE ) ).convert("""RGB""" ).resize((2_5_6, 2_5_6) ) if str(SCREAMING_SNAKE_CASE ).startswith("""mps""" ): _a : Any =torch.manual_seed(SCREAMING_SNAKE_CASE ) else: _a : Union[str, Any] =torch.Generator(device=SCREAMING_SNAKE_CASE ).manual_seed(SCREAMING_SNAKE_CASE ) _a : List[Any] ={ """image""": init_image, """image_embeds""": image_embeds, """negative_image_embeds""": negative_image_embeds, """generator""": generator, """height""": 6_4, """width""": 6_4, """num_inference_steps""": 1_0, """guidance_scale""": 7.0, """strength""": 0.2, """output_type""": """np""", } return inputs def __UpperCAmelCase ( self :List[Any] ) -> List[str]: '''simple docstring''' _a : Dict ="""cpu""" _a : Tuple =self.get_dummy_components() _a : List[str] =self.pipeline_class(**SCREAMING_SNAKE_CASE ) _a : int =pipe.to(SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE ) _a : Tuple =pipe(**self.get_dummy_inputs(SCREAMING_SNAKE_CASE ) ) _a : Optional[int] =output.images _a : Optional[int] =pipe( **self.get_dummy_inputs(SCREAMING_SNAKE_CASE ) , return_dict=SCREAMING_SNAKE_CASE , )[0] _a : List[str] =image[0, -3:, -3:, -1] _a : Optional[int] =image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) _a : List[Any] =np.array( [0.6_199_778, 0.63_984_406, 0.46_145_785, 0.62_944_984, 0.5_622_215, 0.47_306_132, 0.47_441_456, 0.4_607_606, 0.48_719_263] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), f" expected_slice {expected_slice}, but got {image_slice.flatten()}" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), f" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}" @slow @require_torch_gpu class A__ ( unittest.TestCase ): def __UpperCAmelCase ( self :int ) -> Dict: '''simple docstring''' # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __UpperCAmelCase ( self :Dict ) -> Optional[int]: '''simple docstring''' _a : Any =load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinskyv22/kandinskyv22_img2img_frog.npy""" ) _a : List[str] =load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/cat.png""" ) _a : Tuple ="""A red cartoon frog, 4k""" _a : str =KandinskyVaaPriorPipeline.from_pretrained( """kandinsky-community/kandinsky-2-2-prior""" , torch_dtype=torch.floataa ) pipe_prior.to(SCREAMING_SNAKE_CASE ) _a : Optional[Any] =KandinskyVaaImgaImgPipeline.from_pretrained( """kandinsky-community/kandinsky-2-2-decoder""" , torch_dtype=torch.floataa ) _a : List[str] =pipeline.to(SCREAMING_SNAKE_CASE ) pipeline.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE ) _a : Dict =torch.Generator(device="""cpu""" ).manual_seed(0 ) _a , _a : List[Any] =pipe_prior( SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE , num_inference_steps=5 , negative_prompt="""""" , ).to_tuple() _a : Any =pipeline( image=SCREAMING_SNAKE_CASE , image_embeds=SCREAMING_SNAKE_CASE , negative_image_embeds=SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE , num_inference_steps=1_0_0 , height=7_6_8 , width=7_6_8 , strength=0.2 , output_type="""np""" , ) _a : str =output.images[0] assert image.shape == (7_6_8, 7_6_8, 3) assert_mean_pixel_difference(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
276
'''simple docstring''' from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .modeling_utils import ModelMixin from .vae import Decoder, DecoderOutput, Encoder, VectorQuantizer @dataclass class A__ ( UpperCAmelCase__ ): __UpperCamelCase : torch.FloatTensor class A__ ( UpperCAmelCase__ , UpperCAmelCase__ ): @register_to_config def __init__( self :Optional[Any] , SCREAMING_SNAKE_CASE :int = 3 , SCREAMING_SNAKE_CASE :int = 3 , SCREAMING_SNAKE_CASE :Tuple[str] = ("DownEncoderBlock2D",) , SCREAMING_SNAKE_CASE :Tuple[str] = ("UpDecoderBlock2D",) , SCREAMING_SNAKE_CASE :Tuple[int] = (6_4,) , SCREAMING_SNAKE_CASE :int = 1 , SCREAMING_SNAKE_CASE :str = "silu" , SCREAMING_SNAKE_CASE :int = 3 , SCREAMING_SNAKE_CASE :int = 3_2 , SCREAMING_SNAKE_CASE :int = 2_5_6 , SCREAMING_SNAKE_CASE :int = 3_2 , SCREAMING_SNAKE_CASE :Optional[int] = None , SCREAMING_SNAKE_CASE :float = 0.18_215 , SCREAMING_SNAKE_CASE :str = "group" , ) -> Optional[int]: '''simple docstring''' super().__init__() # pass init params to Encoder _a : Union[str, Any] =Encoder( in_channels=SCREAMING_SNAKE_CASE , out_channels=SCREAMING_SNAKE_CASE , down_block_types=SCREAMING_SNAKE_CASE , block_out_channels=SCREAMING_SNAKE_CASE , layers_per_block=SCREAMING_SNAKE_CASE , act_fn=SCREAMING_SNAKE_CASE , norm_num_groups=SCREAMING_SNAKE_CASE , double_z=SCREAMING_SNAKE_CASE , ) _a : Optional[int] =vq_embed_dim if vq_embed_dim is not None else latent_channels _a : Optional[int] =nn.Convad(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , 1 ) _a : str =VectorQuantizer(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , beta=0.25 , remap=SCREAMING_SNAKE_CASE , sane_index_shape=SCREAMING_SNAKE_CASE ) _a : List[str] =nn.Convad(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , 1 ) # pass init params to Decoder _a : List[str] =Decoder( in_channels=SCREAMING_SNAKE_CASE , out_channels=SCREAMING_SNAKE_CASE , up_block_types=SCREAMING_SNAKE_CASE , block_out_channels=SCREAMING_SNAKE_CASE , layers_per_block=SCREAMING_SNAKE_CASE , act_fn=SCREAMING_SNAKE_CASE , norm_num_groups=SCREAMING_SNAKE_CASE , norm_type=SCREAMING_SNAKE_CASE , ) @apply_forward_hook def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :torch.FloatTensor , SCREAMING_SNAKE_CASE :bool = True ) -> VQEncoderOutput: '''simple docstring''' _a : Optional[int] =self.encoder(SCREAMING_SNAKE_CASE ) _a : int =self.quant_conv(SCREAMING_SNAKE_CASE ) if not return_dict: return (h,) return VQEncoderOutput(latents=SCREAMING_SNAKE_CASE ) @apply_forward_hook def __UpperCAmelCase ( self :List[Any] , SCREAMING_SNAKE_CASE :torch.FloatTensor , SCREAMING_SNAKE_CASE :bool = False , SCREAMING_SNAKE_CASE :bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: '''simple docstring''' # also go through quantization layer if not force_not_quantize: _a , _a , _a : Tuple =self.quantize(SCREAMING_SNAKE_CASE ) else: _a : str =h _a : Dict =self.post_quant_conv(SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =self.decoder(SCREAMING_SNAKE_CASE , quant if self.config.norm_type == """spatial""" else None ) if not return_dict: return (dec,) return DecoderOutput(sample=SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :torch.FloatTensor , SCREAMING_SNAKE_CASE :bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: '''simple docstring''' _a : Tuple =sample _a : int =self.encode(SCREAMING_SNAKE_CASE ).latents _a : List[Any] =self.decode(SCREAMING_SNAKE_CASE ).sample if not return_dict: return (dec,) return DecoderOutput(sample=SCREAMING_SNAKE_CASE )
276
1
'''simple docstring''' import argparse import gc import json import os 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 A__: Dict = 16 A__: Tuple = 32 def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[int] ) -> List[str]: return int(x / 2**20 ) class A__ : def __enter__( self :str ) -> List[str]: '''simple docstring''' gc.collect() torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() # reset the peak gauge to zero _a : str =torch.cuda.memory_allocated() return self def __exit__( self :Any , *SCREAMING_SNAKE_CASE :List[str] ) -> List[Any]: '''simple docstring''' gc.collect() torch.cuda.empty_cache() _a : str =torch.cuda.memory_allocated() _a : Tuple =torch.cuda.max_memory_allocated() _a : Optional[Any] =bamb(self.end - self.begin ) _a : List[Any] =bamb(self.peak - self.begin ) # print(f"delta used/peak {self.used:4d}/{self.peaked:4d}") def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Accelerator ,_UpperCAmelCase : int = 16 ,_UpperCAmelCase : str = "bert-base-cased" ,_UpperCAmelCase : int = 320 ,_UpperCAmelCase : int = 160 ,) -> Union[str, Any]: _a : List[Any] =AutoTokenizer.from_pretrained(_UpperCAmelCase ) _a : str =load_dataset( """glue""" ,"""mrpc""" ,split={"""train""": F"train[:{n_train}]", """validation""": F"validation[:{n_val}]"} ) def tokenize_function(_UpperCAmelCase : Any ): # max_length=None => use the model max length (it's actually the default) _a : int =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 _a : Union[str, Any] =datasets.map( _UpperCAmelCase ,batched=_UpperCAmelCase ,remove_columns=["""idx""", """sentence1""", """sentence2"""] ,load_from_cache_file=_UpperCAmelCase ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library _a : Any =tokenized_datasets.rename_column("""label""" ,"""labels""" ) def collate_fn(_UpperCAmelCase : Optional[Any] ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(_UpperCAmelCase ,padding="""max_length""" ,max_length=128 ,return_tensors="""pt""" ) return tokenizer.pad(_UpperCAmelCase ,padding="""longest""" ,return_tensors="""pt""" ) # Instantiate dataloaders. _a : Dict =DataLoader( tokenized_datasets["""train"""] ,shuffle=_UpperCAmelCase ,collate_fn=_UpperCAmelCase ,batch_size=_UpperCAmelCase ) _a : Dict =DataLoader( tokenized_datasets["""validation"""] ,shuffle=_UpperCAmelCase ,collate_fn=_UpperCAmelCase ,batch_size=_UpperCAmelCase ) return train_dataloader, eval_dataloader def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : str ) -> int: # Initialize accelerator _a : Optional[Any] =Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs _a : Optional[Any] =config["""lr"""] _a : List[Any] =int(config["""num_epochs"""] ) _a : Any =int(config["""seed"""] ) _a : List[str] =int(config["""batch_size"""] ) _a : Dict =args.model_name_or_path set_seed(_UpperCAmelCase ) _a , _a : Optional[int] =get_dataloaders(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,args.n_train ,args.n_val ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) _a : Optional[Any] =AutoModelForSequenceClassification.from_pretrained(_UpperCAmelCase ,return_dict=_UpperCAmelCase ) # Instantiate optimizer _a : Tuple =( AdamW if accelerator.state.deepspeed_plugin is None or """optimizer""" not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) _a : int =optimizer_cls(params=model.parameters() ,lr=_UpperCAmelCase ) if accelerator.state.deepspeed_plugin is not None: _a : str =accelerator.state.deepspeed_plugin.deepspeed_config[ """gradient_accumulation_steps""" ] else: _a : Dict =1 _a : List[str] =(len(_UpperCAmelCase ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): _a : int =get_linear_schedule_with_warmup( optimizer=_UpperCAmelCase ,num_warmup_steps=0 ,num_training_steps=_UpperCAmelCase ,) else: _a : List[Any] =DummyScheduler(_UpperCAmelCase ,total_num_steps=_UpperCAmelCase ,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. _a , _a , _a , _a , _a : List[str] =accelerator.prepare( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) # We need to keep track of how many total steps we have iterated over _a : Union[str, Any] =0 # We also need to keep track of the stating epoch so files are named properly _a : Optional[Any] =0 # Now we train the model _a : Tuple ={} for epoch in range(_UpperCAmelCase ,_UpperCAmelCase ): with TorchTracemalloc() as tracemalloc: model.train() for step, batch in enumerate(_UpperCAmelCase ): _a : Tuple =model(**_UpperCAmelCase ) _a : Union[str, Any] =outputs.loss _a : Dict =loss / gradient_accumulation_steps accelerator.backward(_UpperCAmelCase ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 # Printing the GPU memory usage details such as allocated memory, peak memory, and total memory usage accelerator.print("""Memory before entering the train : {}""".format(bamb(tracemalloc.begin ) ) ) accelerator.print("""Memory consumed at the end of the train (end-begin): {}""".format(tracemalloc.used ) ) accelerator.print("""Peak Memory consumed during the train (max-begin): {}""".format(tracemalloc.peaked ) ) accelerator.print( """Total Peak Memory consumed during the train (max): {}""".format( tracemalloc.peaked + bamb(tracemalloc.begin ) ) ) _a : Any =tracemalloc.peaked + bamb(tracemalloc.begin ) if args.peak_memory_upper_bound is not None: assert ( train_total_peak_memory[F"epoch-{epoch}"] <= args.peak_memory_upper_bound ), "Peak memory usage exceeded the upper bound" accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir ,"""peak_memory_utilization.json""" ) ,"""w""" ) as f: json.dump(_UpperCAmelCase ,_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( ) -> Any: _a : Dict =argparse.ArgumentParser(description="""Simple example of training script tracking peak GPU memory usage.""" ) parser.add_argument( """--model_name_or_path""" ,type=_UpperCAmelCase ,default="""bert-base-cased""" ,help="""Path to pretrained model or model identifier from huggingface.co/models.""" ,required=_UpperCAmelCase ,) parser.add_argument( """--output_dir""" ,type=_UpperCAmelCase ,default=""".""" ,help="""Optional save directory where all checkpoint folders will be stored. Default is the current working directory.""" ,) parser.add_argument( """--peak_memory_upper_bound""" ,type=_UpperCAmelCase ,default=_UpperCAmelCase ,help="""The upper bound of peak memory usage in MB. If set, the training will throw an error if the peak memory usage exceeds this value.""" ,) parser.add_argument( """--n_train""" ,type=_UpperCAmelCase ,default=320 ,help="""Number of training examples to use.""" ,) parser.add_argument( """--n_val""" ,type=_UpperCAmelCase ,default=160 ,help="""Number of validation examples to use.""" ,) parser.add_argument( """--num_epochs""" ,type=_UpperCAmelCase ,default=1 ,help="""Number of train epochs.""" ,) _a : Any =parser.parse_args() _a : Union[str, Any] ={"""lr""": 2e-5, """num_epochs""": args.num_epochs, """seed""": 42, """batch_size""": 16} training_function(_UpperCAmelCase ,_UpperCAmelCase ) if __name__ == "__main__": main()
276
'''simple docstring''' import unittest from transformers import EsmConfig, is_torch_available from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import EsmForMaskedLM, EsmForSequenceClassification, EsmForTokenClassification, EsmModel from transformers.models.esm.modeling_esm import ( ESM_PRETRAINED_MODEL_ARCHIVE_LIST, EsmEmbeddings, create_position_ids_from_input_ids, ) class A__ : def __init__( self :Tuple , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :Optional[int]=1_3 , SCREAMING_SNAKE_CASE :Optional[int]=7 , SCREAMING_SNAKE_CASE :Tuple=False , SCREAMING_SNAKE_CASE :Dict=True , SCREAMING_SNAKE_CASE :Optional[int]=False , SCREAMING_SNAKE_CASE :Optional[Any]=True , SCREAMING_SNAKE_CASE :List[str]=3_3 , SCREAMING_SNAKE_CASE :Tuple=3_2 , SCREAMING_SNAKE_CASE :Tuple=5 , SCREAMING_SNAKE_CASE :int=4 , SCREAMING_SNAKE_CASE :Union[str, Any]=3_7 , SCREAMING_SNAKE_CASE :List[str]="gelu" , SCREAMING_SNAKE_CASE :Optional[Any]=0.1 , SCREAMING_SNAKE_CASE :Tuple=0.1 , SCREAMING_SNAKE_CASE :str=5_1_2 , SCREAMING_SNAKE_CASE :Dict=1_6 , SCREAMING_SNAKE_CASE :Dict=2 , SCREAMING_SNAKE_CASE :Union[str, Any]=0.02 , SCREAMING_SNAKE_CASE :str=3 , SCREAMING_SNAKE_CASE :List[str]=4 , SCREAMING_SNAKE_CASE :List[str]=None , ) -> Union[str, Any]: '''simple docstring''' _a : Union[str, Any] =parent _a : List[Any] =batch_size _a : Optional[int] =seq_length _a : Union[str, Any] =is_training _a : List[Any] =use_input_mask _a : Optional[int] =use_token_type_ids _a : int =use_labels _a : List[str] =vocab_size _a : List[Any] =hidden_size _a : int =num_hidden_layers _a : Tuple =num_attention_heads _a : Any =intermediate_size _a : str =hidden_act _a : Union[str, Any] =hidden_dropout_prob _a : Union[str, Any] =attention_probs_dropout_prob _a : str =max_position_embeddings _a : Dict =type_vocab_size _a : Tuple =type_sequence_label_size _a : Dict =initializer_range _a : List[str] =num_labels _a : Tuple =num_choices _a : int =scope def __UpperCAmelCase ( self :Union[str, Any] ) -> str: '''simple docstring''' _a : Optional[int] =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _a : List[Any] =None if self.use_input_mask: _a : Any =random_attention_mask([self.batch_size, self.seq_length] ) _a : Optional[int] =None _a : str =None _a : Dict =None if self.use_labels: _a : Dict =ids_tensor([self.batch_size] , self.type_sequence_label_size ) _a : str =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _a : List[str] =ids_tensor([self.batch_size] , self.num_choices ) _a : List[Any] =self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCAmelCase ( self :str ) -> Optional[int]: '''simple docstring''' return EsmConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , pad_token_id=1 , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) def __UpperCAmelCase ( self :List[str] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :int ) -> Tuple: '''simple docstring''' _a : Any =EsmModel(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() _a : Optional[Any] =model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =model(SCREAMING_SNAKE_CASE ) _a : str =model(SCREAMING_SNAKE_CASE ) 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 __UpperCAmelCase ( self :str , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :Optional[Any] ) -> Dict: '''simple docstring''' _a : str =EsmForMaskedLM(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() _a : Union[str, Any] =model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :List[Any] , SCREAMING_SNAKE_CASE :Union[str, Any] ) -> Optional[Any]: '''simple docstring''' _a : int =self.num_labels _a : Tuple =EsmForTokenClassification(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() _a : Tuple =model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCAmelCase ( self :Dict ) -> List[str]: '''simple docstring''' _a : Optional[Any] =self.prepare_config_and_inputs() ( ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ) : Any =config_and_inputs _a : List[Any] ={"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class A__ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): __UpperCamelCase : Any = False __UpperCamelCase : Any = ( ( EsmForMaskedLM, EsmModel, EsmForSequenceClassification, EsmForTokenClassification, ) if is_torch_available() else () ) __UpperCamelCase : str = () __UpperCamelCase : List[str] = ( { "feature-extraction": EsmModel, "fill-mask": EsmForMaskedLM, "text-classification": EsmForSequenceClassification, "token-classification": EsmForTokenClassification, "zero-shot": EsmForSequenceClassification, } if is_torch_available() else {} ) __UpperCamelCase : Union[str, Any] = True def __UpperCAmelCase ( self :Optional[int] ) -> int: '''simple docstring''' _a : Dict =EsmModelTester(self ) _a : Optional[Any] =ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , hidden_size=3_7 ) def __UpperCAmelCase ( self :Tuple ) -> List[Any]: '''simple docstring''' self.config_tester.run_common_tests() def __UpperCAmelCase ( self :Optional[int] ) -> str: '''simple docstring''' _a : List[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :List[Any] ) -> Dict: '''simple docstring''' _a : List[str] =self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: _a : Dict =type self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Dict ) -> List[str]: '''simple docstring''' _a : Tuple =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :List[Any] ) -> List[str]: '''simple docstring''' _a : str =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE ) @slow def __UpperCAmelCase ( self :str ) -> Dict: '''simple docstring''' for model_name in ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _a : Union[str, Any] =EsmModel.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Tuple ) -> int: '''simple docstring''' _a : Optional[Any] =self.model_tester.prepare_config_and_inputs()[0] _a : Dict =EsmEmbeddings(config=SCREAMING_SNAKE_CASE ) _a : Tuple =torch.as_tensor([[1_2, 3_1, 1_3, model.padding_idx]] ) _a : Optional[Any] =torch.as_tensor( [ [ 0 + model.padding_idx + 1, 1 + model.padding_idx + 1, 2 + model.padding_idx + 1, model.padding_idx, ] ] ) _a : Any =create_position_ids_from_input_ids(SCREAMING_SNAKE_CASE , model.padding_idx ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) ) def __UpperCAmelCase ( self :Optional[Any] ) -> Tuple: '''simple docstring''' _a : List[Any] =self.model_tester.prepare_config_and_inputs()[0] _a : Optional[int] =EsmEmbeddings(config=SCREAMING_SNAKE_CASE ) _a : Tuple =torch.empty(2 , 4 , 3_0 ) _a : str =[ 0 + embeddings.padding_idx + 1, 1 + embeddings.padding_idx + 1, 2 + embeddings.padding_idx + 1, 3 + embeddings.padding_idx + 1, ] _a : int =torch.as_tensor([expected_single_positions, expected_single_positions] ) _a : Any =embeddings.create_position_ids_from_inputs_embeds(SCREAMING_SNAKE_CASE ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) ) @unittest.skip("""Esm does not support embedding resizing""" ) def __UpperCAmelCase ( self :Tuple ) -> List[str]: '''simple docstring''' pass @unittest.skip("""Esm does not support embedding resizing""" ) def __UpperCAmelCase ( self :str ) -> Any: '''simple docstring''' pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def __UpperCAmelCase ( self :Dict ) -> Any: '''simple docstring''' pass @require_torch class A__ ( UpperCAmelCase__ ): @slow def __UpperCAmelCase ( self :List[Any] ) -> str: '''simple docstring''' with torch.no_grad(): _a : Optional[int] =EsmForMaskedLM.from_pretrained("""facebook/esm2_t6_8M_UR50D""" ) model.eval() _a : Any =torch.tensor([[0, 1, 2, 3, 4, 5]] ) _a : Tuple =model(SCREAMING_SNAKE_CASE )[0] _a : int =3_3 _a : Tuple =torch.Size((1, 6, vocab_size) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =torch.tensor( [[[8.9_215, -10.5_898, -6.4_671], [-6.3_967, -13.9_114, -1.1_212], [-7.7_812, -13.9_516, -3.7_406]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) ) @slow def __UpperCAmelCase ( self :Union[str, Any] ) -> Tuple: '''simple docstring''' with torch.no_grad(): _a : Any =EsmModel.from_pretrained("""facebook/esm2_t6_8M_UR50D""" ) model.eval() _a : Any =torch.tensor([[0, 6, 4, 1_3, 5, 4, 1_6, 1_2, 1_1, 7, 2]] ) _a : int =model(SCREAMING_SNAKE_CASE )[0] # compare the actual values for a slice. _a : str =torch.tensor( [[[0.1_444, 0.5_413, 0.3_248], [0.3_034, 0.0_053, 0.3_108], [0.3_228, -0.2_499, 0.3_415]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) )
276
1
'''simple docstring''' import logging import os from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union from filelock import FileLock from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available A__: int = logging.getLogger(__name__) @dataclass class A__ : __UpperCamelCase : str __UpperCamelCase : List[str] __UpperCamelCase : Optional[List[str]] @dataclass class A__ : __UpperCamelCase : List[int] __UpperCamelCase : List[int] __UpperCamelCase : Optional[List[int]] = None __UpperCamelCase : Optional[List[int]] = None class A__ ( UpperCAmelCase__ ): __UpperCamelCase : str = "train" __UpperCamelCase : Tuple = "dev" __UpperCamelCase : str = "test" class A__ : @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :Union[Split, str] ) -> List[InputExample]: '''simple docstring''' raise NotImplementedError @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :str ) -> List[str]: '''simple docstring''' raise NotImplementedError @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :List[InputExample] , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :PreTrainedTokenizer , SCREAMING_SNAKE_CASE :str=False , SCREAMING_SNAKE_CASE :Optional[Any]="[CLS]" , SCREAMING_SNAKE_CASE :Optional[int]=1 , SCREAMING_SNAKE_CASE :Any="[SEP]" , SCREAMING_SNAKE_CASE :List[Any]=False , SCREAMING_SNAKE_CASE :Union[str, Any]=False , SCREAMING_SNAKE_CASE :List[str]=0 , SCREAMING_SNAKE_CASE :str=0 , SCREAMING_SNAKE_CASE :Dict=-1_0_0 , SCREAMING_SNAKE_CASE :Optional[int]=0 , SCREAMING_SNAKE_CASE :Tuple=True , ) -> List[InputFeatures]: '''simple docstring''' _a : str ={label: i for i, label in enumerate(SCREAMING_SNAKE_CASE )} _a : Tuple =[] for ex_index, example in enumerate(SCREAMING_SNAKE_CASE ): if ex_index % 1_0_0_0_0 == 0: logger.info("""Writing example %d of %d""" , SCREAMING_SNAKE_CASE , len(SCREAMING_SNAKE_CASE ) ) _a : Optional[Any] =[] _a : List[Any] =[] for word, label in zip(example.words , example.labels ): _a : Optional[int] =tokenizer.tokenize(SCREAMING_SNAKE_CASE ) # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space. if len(SCREAMING_SNAKE_CASE ) > 0: tokens.extend(SCREAMING_SNAKE_CASE ) # Use the real label id for the first token of the word, and padding ids for the remaining tokens label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(SCREAMING_SNAKE_CASE ) - 1) ) # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa. _a : Optional[int] =tokenizer.num_special_tokens_to_add() if len(SCREAMING_SNAKE_CASE ) > max_seq_length - special_tokens_count: _a : List[Any] =tokens[: (max_seq_length - special_tokens_count)] _a : Tuple =label_ids[: (max_seq_length - special_tokens_count)] # The convention in BERT is: # (a) For sequence pairs: # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP] # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1 # (b) For single sequences: # tokens: [CLS] the dog is hairy . [SEP] # type_ids: 0 0 0 0 0 0 0 # # Where "type_ids" are used to indicate whether this is the first # sequence or the second sequence. The embedding vectors for `type=0` and # `type=1` were learned during pre-training and are added to the wordpiece # embedding vector (and position vector). This is not *strictly* necessary # since the [SEP] token unambiguously separates the sequences, but it makes # it easier for the model to learn the concept of sequences. # # For classification tasks, the first vector (corresponding to [CLS]) is # used as the "sentence vector". Note that this only makes sense because # the entire model is fine-tuned. tokens += [sep_token] label_ids += [pad_token_label_id] if sep_token_extra: # roberta uses an extra separator b/w pairs of sentences tokens += [sep_token] label_ids += [pad_token_label_id] _a : Dict =[sequence_a_segment_id] * len(SCREAMING_SNAKE_CASE ) if cls_token_at_end: tokens += [cls_token] label_ids += [pad_token_label_id] segment_ids += [cls_token_segment_id] else: _a : Any =[cls_token] + tokens _a : Dict =[pad_token_label_id] + label_ids _a : Union[str, Any] =[cls_token_segment_id] + segment_ids _a : List[str] =tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE ) # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. _a : Optional[int] =[1 if mask_padding_with_zero else 0] * len(SCREAMING_SNAKE_CASE ) # Zero-pad up to the sequence length. _a : Union[str, Any] =max_seq_length - len(SCREAMING_SNAKE_CASE ) if pad_on_left: _a : Optional[Any] =([pad_token] * padding_length) + input_ids _a : Optional[int] =([0 if mask_padding_with_zero else 1] * padding_length) + input_mask _a : Union[str, Any] =([pad_token_segment_id] * padding_length) + segment_ids _a : Dict =([pad_token_label_id] * padding_length) + label_ids else: input_ids += [pad_token] * padding_length input_mask += [0 if mask_padding_with_zero else 1] * padding_length segment_ids += [pad_token_segment_id] * padding_length label_ids += [pad_token_label_id] * padding_length assert len(SCREAMING_SNAKE_CASE ) == max_seq_length assert len(SCREAMING_SNAKE_CASE ) == max_seq_length assert len(SCREAMING_SNAKE_CASE ) == max_seq_length assert len(SCREAMING_SNAKE_CASE ) == max_seq_length if ex_index < 5: logger.info("""*** Example ***""" ) logger.info("""guid: %s""" , example.guid ) logger.info("""tokens: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in tokens] ) ) logger.info("""input_ids: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in input_ids] ) ) logger.info("""input_mask: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in input_mask] ) ) logger.info("""segment_ids: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in segment_ids] ) ) logger.info("""label_ids: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in label_ids] ) ) if "token_type_ids" not in tokenizer.model_input_names: _a : Tuple =None features.append( InputFeatures( input_ids=SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , token_type_ids=SCREAMING_SNAKE_CASE , label_ids=SCREAMING_SNAKE_CASE ) ) return features if is_torch_available(): import torch from torch import nn from torch.utils.data import Dataset class A__ ( UpperCAmelCase__ ): __UpperCamelCase : List[InputFeatures] __UpperCamelCase : int = nn.CrossEntropyLoss().ignore_index def __init__( self :Dict , SCREAMING_SNAKE_CASE :TokenClassificationTask , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :PreTrainedTokenizer , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Optional[int] = None , SCREAMING_SNAKE_CASE :int=False , SCREAMING_SNAKE_CASE :Split = Split.train , ) -> List[str]: '''simple docstring''' # Load data features from cache or dataset file _a : Optional[Any] =os.path.join( SCREAMING_SNAKE_CASE , """cached_{}_{}_{}""".format(mode.value , tokenizer.__class__.__name__ , str(SCREAMING_SNAKE_CASE ) ) , ) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. _a : List[str] =cached_features_file + """.lock""" with FileLock(SCREAMING_SNAKE_CASE ): if os.path.exists(SCREAMING_SNAKE_CASE ) and not overwrite_cache: logger.info(f"Loading features from cached file {cached_features_file}" ) _a : Any =torch.load(SCREAMING_SNAKE_CASE ) else: logger.info(f"Creating features from dataset file at {data_dir}" ) _a : Any =token_classification_task.read_examples_from_file(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # TODO clean up all this to leverage built-in features of tokenizers _a : List[str] =token_classification_task.convert_examples_to_features( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cls_token_at_end=bool(model_type in ["""xlnet"""] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ["""xlnet"""] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=SCREAMING_SNAKE_CASE , pad_on_left=bool(tokenizer.padding_side == """left""" ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info(f"Saving features into cached file {cached_features_file}" ) torch.save(self.features , SCREAMING_SNAKE_CASE ) def __len__( self :Optional[int] ) -> Union[str, Any]: '''simple docstring''' return len(self.features ) def __getitem__( self :Dict , SCREAMING_SNAKE_CASE :int ) -> InputFeatures: '''simple docstring''' return self.features[i] if is_tf_available(): import tensorflow as tf class A__ : __UpperCamelCase : List[InputFeatures] __UpperCamelCase : int = -100 def __init__( self :str , SCREAMING_SNAKE_CASE :TokenClassificationTask , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :PreTrainedTokenizer , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Optional[int] = None , SCREAMING_SNAKE_CASE :str=False , SCREAMING_SNAKE_CASE :Split = Split.train , ) -> Any: '''simple docstring''' _a : Tuple =token_classification_task.read_examples_from_file(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # TODO clean up all this to leverage built-in features of tokenizers _a : List[Any] =token_classification_task.convert_examples_to_features( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cls_token_at_end=bool(model_type in ["""xlnet"""] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ["""xlnet"""] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=SCREAMING_SNAKE_CASE , pad_on_left=bool(tokenizer.padding_side == """left""" ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) def gen(): for ex in self.features: if ex.token_type_ids is None: yield ( {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label_ids, ) else: yield ( { "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label_ids, ) if "token_type_ids" not in tokenizer.model_input_names: _a : Union[str, Any] =tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE , ({"""input_ids""": tf.intaa, """attention_mask""": tf.intaa}, tf.intaa) , ( {"""input_ids""": tf.TensorShape([None] ), """attention_mask""": tf.TensorShape([None] )}, tf.TensorShape([None] ), ) , ) else: _a : Union[str, Any] =tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE , ({"""input_ids""": tf.intaa, """attention_mask""": tf.intaa, """token_type_ids""": tf.intaa}, tf.intaa) , ( { """input_ids""": tf.TensorShape([None] ), """attention_mask""": tf.TensorShape([None] ), """token_type_ids""": tf.TensorShape([None] ), }, tf.TensorShape([None] ), ) , ) def __UpperCAmelCase ( self :Tuple ) -> Any: '''simple docstring''' _a : List[Any] =self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features ) ) ) return self.dataset def __len__( self :str ) -> Optional[int]: '''simple docstring''' return len(self.features ) def __getitem__( self :int , SCREAMING_SNAKE_CASE :str ) -> InputFeatures: '''simple docstring''' return self.features[i]
276
'''simple docstring''' from math import isqrt def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ) -> bool: return all(number % divisor != 0 for divisor in range(2 ,isqrt(_UpperCAmelCase ) + 1 ) ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int = 10**6 ) -> int: _a : List[Any] =0 _a : str =1 _a : Optional[Any] =7 while prime_candidate < max_prime: primes_count += is_prime(_UpperCAmelCase ) cube_index += 1 prime_candidate += 6 * cube_index return primes_count if __name__ == "__main__": print(F"{solution() = }")
276
1
'''simple docstring''' import enum import warnings from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING from ..utils import add_end_docstrings, is_tf_available from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf class A__ ( enum.Enum ): __UpperCamelCase : str = 0 __UpperCamelCase : Any = 1 __UpperCamelCase : List[Any] = 2 @add_end_docstrings(UpperCAmelCase__ ) class A__ ( UpperCAmelCase__ ): __UpperCamelCase : Tuple = "\n In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The\n voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western\n Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision\n and denounces one of the men as a horse thief. Although his father initially slaps him for making such an\n accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of\n the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop,\n begging for his blessing. <eod> </s> <eos>\n " def __init__( self :Optional[int] , *SCREAMING_SNAKE_CASE :Any , **SCREAMING_SNAKE_CASE :Any ) -> str: '''simple docstring''' super().__init__(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) self.check_model_type( TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == """tf""" else MODEL_FOR_CAUSAL_LM_MAPPING ) if "prefix" not in self._preprocess_params: # This is very specific. The logic is quite complex and needs to be done # as a "default". # It also defines both some preprocess_kwargs and generate_kwargs # which is why we cannot put them in their respective methods. _a : int =None if self.model.config.prefix is not None: _a : Any =self.model.config.prefix if prefix is None and self.model.__class__.__name__ in [ "XLNetLMHeadModel", "TransfoXLLMHeadModel", "TFXLNetLMHeadModel", "TFTransfoXLLMHeadModel", ]: # For XLNet and TransformerXL we add an article to the prompt to give more state to the model. _a : Any =self.XL_PREFIX if prefix is not None: # Recalculate some generate_kwargs linked to prefix. _a , _a , _a : Tuple =self._sanitize_parameters(prefix=SCREAMING_SNAKE_CASE , **self._forward_params ) _a : Optional[int] ={**self._preprocess_params, **preprocess_params} _a : Tuple ={**self._forward_params, **forward_params} def __UpperCAmelCase ( self :Optional[int] , SCREAMING_SNAKE_CASE :Tuple=None , SCREAMING_SNAKE_CASE :Optional[int]=None , SCREAMING_SNAKE_CASE :Any=None , SCREAMING_SNAKE_CASE :List[Any]=None , SCREAMING_SNAKE_CASE :str=None , SCREAMING_SNAKE_CASE :Dict=None , SCREAMING_SNAKE_CASE :Optional[int]=None , SCREAMING_SNAKE_CASE :Tuple=None , **SCREAMING_SNAKE_CASE :Any , ) -> Optional[int]: '''simple docstring''' _a : Optional[int] ={} if prefix is not None: _a : Union[str, Any] =prefix if prefix: _a : Union[str, Any] =self.tokenizer( SCREAMING_SNAKE_CASE , padding=SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE , return_tensors=self.framework ) _a : List[Any] =prefix_inputs["""input_ids"""].shape[-1] if handle_long_generation is not None: if handle_long_generation not in {"hole"}: raise ValueError( f"{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected" """ [None, 'hole']""" ) _a : List[Any] =handle_long_generation preprocess_params.update(SCREAMING_SNAKE_CASE ) _a : Tuple =generate_kwargs _a : List[str] ={} if return_full_text is not None and return_type is None: if return_text is not None: raise ValueError("""`return_text` is mutually exclusive with `return_full_text`""" ) if return_tensors is not None: raise ValueError("""`return_full_text` is mutually exclusive with `return_tensors`""" ) _a : List[Any] =ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT if return_tensors is not None and return_type is None: if return_text is not None: raise ValueError("""`return_text` is mutually exclusive with `return_tensors`""" ) _a : Any =ReturnType.TENSORS if return_type is not None: _a : Union[str, Any] =return_type if clean_up_tokenization_spaces is not None: _a : Tuple =clean_up_tokenization_spaces if stop_sequence is not None: _a : str =self.tokenizer.encode(SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE ) if len(SCREAMING_SNAKE_CASE ) > 1: warnings.warn( """Stopping on a multiple token sequence is not yet supported on transformers. The first token of""" """ the stop sequence will be used as the stop sequence string in the interim.""" ) _a : Optional[int] =stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def __UpperCAmelCase ( self :str , *SCREAMING_SNAKE_CASE :Any , **SCREAMING_SNAKE_CASE :Dict ) -> Optional[int]: '''simple docstring''' # Parse arguments if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]: kwargs.update({"""add_space_before_punct_symbol""": True} ) return super()._parse_and_tokenize(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) def __call__( self :Dict , SCREAMING_SNAKE_CASE :Optional[int] , **SCREAMING_SNAKE_CASE :Optional[int] ) -> int: '''simple docstring''' return super().__call__(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Optional[int] , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :Optional[Any]="" , SCREAMING_SNAKE_CASE :Optional[Any]=None , **SCREAMING_SNAKE_CASE :List[str] ) -> Any: '''simple docstring''' _a : Union[str, Any] =self.tokenizer( prefix + prompt_text , padding=SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE , return_tensors=self.framework ) _a : Tuple =prompt_text if handle_long_generation == "hole": _a : Optional[Any] =inputs["""input_ids"""].shape[-1] if "max_new_tokens" in generate_kwargs: _a : List[str] =generate_kwargs["""max_new_tokens"""] else: _a : Optional[Any] =generate_kwargs.get("""max_length""" , self.model.config.max_length ) - cur_len if new_tokens < 0: raise ValueError("""We cannot infer how many new tokens are expected""" ) if cur_len + new_tokens > self.tokenizer.model_max_length: _a : List[Any] =self.tokenizer.model_max_length - new_tokens if keep_length <= 0: raise ValueError( """We cannot use `hole` to handle this generation the number of desired tokens exceeds the""" """ models max length""" ) _a : int =inputs["""input_ids"""][:, -keep_length:] if "attention_mask" in inputs: _a : List[str] =inputs["""attention_mask"""][:, -keep_length:] return inputs def __UpperCAmelCase ( self :Tuple , SCREAMING_SNAKE_CASE :Tuple , **SCREAMING_SNAKE_CASE :int ) -> List[str]: '''simple docstring''' _a : int =model_inputs["""input_ids"""] _a : List[str] =model_inputs.get("""attention_mask""" , SCREAMING_SNAKE_CASE ) # Allow empty prompts if input_ids.shape[1] == 0: _a : int =None _a : Optional[Any] =None _a : Any =1 else: _a : Dict =input_ids.shape[0] _a : List[str] =model_inputs.pop("""prompt_text""" ) # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline. _a : str =generate_kwargs.pop("""prefix_length""" , 0 ) if prefix_length > 0: _a : Optional[int] ="""max_new_tokens""" in generate_kwargs or ( """generation_config""" in generate_kwargs and generate_kwargs["""generation_config"""].max_new_tokens is not None ) if not has_max_new_tokens: _a : Union[str, Any] =generate_kwargs.get("""max_length""" ) or self.model.config.max_length generate_kwargs["max_length"] += prefix_length _a : List[Any] ="""min_new_tokens""" in generate_kwargs or ( """generation_config""" in generate_kwargs and generate_kwargs["""generation_config"""].min_new_tokens is not None ) if not has_min_new_tokens and "min_length" in generate_kwargs: generate_kwargs["min_length"] += prefix_length # BS x SL _a : Tuple =self.model.generate(input_ids=SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) _a : int =generated_sequence.shape[0] if self.framework == "pt": _a : List[str] =generated_sequence.reshape(SCREAMING_SNAKE_CASE , out_b // in_b , *generated_sequence.shape[1:] ) elif self.framework == "tf": _a : List[str] =tf.reshape(SCREAMING_SNAKE_CASE , (in_b, out_b // in_b, *generated_sequence.shape[1:]) ) return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text} def __UpperCAmelCase ( self :Optional[int] , SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :Tuple=ReturnType.FULL_TEXT , SCREAMING_SNAKE_CASE :Any=True ) -> Optional[Any]: '''simple docstring''' _a : Optional[int] =model_outputs["""generated_sequence"""][0] _a : Tuple =model_outputs["""input_ids"""] _a : Tuple =model_outputs["""prompt_text"""] _a : List[Any] =generated_sequence.numpy().tolist() _a : Dict =[] for sequence in generated_sequence: if return_type == ReturnType.TENSORS: _a : Union[str, Any] ={"""generated_token_ids""": sequence} elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}: # Decode text _a : int =self.tokenizer.decode( SCREAMING_SNAKE_CASE , skip_special_tokens=SCREAMING_SNAKE_CASE , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE , ) # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used if input_ids is None: _a : Tuple =0 else: _a : List[Any] =len( self.tokenizer.decode( input_ids[0] , skip_special_tokens=SCREAMING_SNAKE_CASE , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE , ) ) if return_type == ReturnType.FULL_TEXT: _a : Dict =prompt_text + text[prompt_length:] else: _a : int =text[prompt_length:] _a : str ={"""generated_text""": all_text} records.append(SCREAMING_SNAKE_CASE ) return records
276
'''simple docstring''' # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from ...utils import deprecate from ..controlnet.multicontrolnet import MultiControlNetModel # noqa: F401 from ..controlnet.pipeline_controlnet import StableDiffusionControlNetPipeline # noqa: F401 deprecate( '''stable diffusion controlnet''', '''0.22.0''', '''Importing `StableDiffusionControlNetPipeline` or `MultiControlNetModel` from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import StableDiffusionControlNetPipeline` instead.''', standard_warn=False, stacklevel=3, )
276
1
'''simple docstring''' from __future__ import annotations import copy import tempfile import unittest from transformers import CONFIG_MAPPING, AutoConfig, BertConfig, GPTaConfig, TaConfig, TapasConfig, is_tf_available from transformers.testing_utils import ( DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, RequestCounter, require_tensorflow_probability, require_tf, slow, ) from ..bert.test_modeling_bert import BertModelTester if is_tf_available(): from transformers import ( TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelForTableQuestionAnswering, TFAutoModelForTokenClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFFunnelBaseModel, TFFunnelModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, TFTapasForQuestionAnswering, ) from transformers.models.auto.modeling_tf_auto import ( TF_MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_PRETRAINING_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, TF_MODEL_MAPPING, ) from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.tapas.modeling_tf_tapas import TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST class A__ ( UpperCAmelCase__ ): __UpperCamelCase : Any = "new-model" if is_tf_available(): class A__ ( UpperCAmelCase__ ): __UpperCamelCase : Any = NewModelConfig @require_tf class A__ ( unittest.TestCase ): @slow def __UpperCAmelCase ( self :List[Any] ) -> Optional[int]: '''simple docstring''' _a : Union[str, Any] ="""bert-base-cased""" _a : Optional[int] =AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) _a : Optional[int] =TFAutoModel.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) @slow def __UpperCAmelCase ( self :List[Any] ) -> List[str]: '''simple docstring''' _a : Tuple ="""bert-base-cased""" _a : Optional[Any] =AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) _a : Dict =TFAutoModelForPreTraining.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) @slow def __UpperCAmelCase ( self :Optional[int] ) -> int: '''simple docstring''' for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _a : Any =AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) _a : Optional[int] =TFAutoModelForCausalLM.from_pretrained(SCREAMING_SNAKE_CASE ) _a , _a : Dict =TFAutoModelForCausalLM.from_pretrained(SCREAMING_SNAKE_CASE , output_loading_info=SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) @slow def __UpperCAmelCase ( self :Any ) -> Optional[int]: '''simple docstring''' for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _a : Tuple =AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) _a : str =TFAutoModelWithLMHead.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) @slow def __UpperCAmelCase ( self :int ) -> int: '''simple docstring''' for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _a : Optional[Any] =AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =TFAutoModelForMaskedLM.from_pretrained(SCREAMING_SNAKE_CASE ) _a , _a : Dict =TFAutoModelForMaskedLM.from_pretrained(SCREAMING_SNAKE_CASE , output_loading_info=SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) @slow def __UpperCAmelCase ( self :Optional[Any] ) -> Optional[int]: '''simple docstring''' for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _a : Dict =AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) _a : List[Any] =TFAutoModelForSeqaSeqLM.from_pretrained(SCREAMING_SNAKE_CASE ) _a , _a : int =TFAutoModelForSeqaSeqLM.from_pretrained(SCREAMING_SNAKE_CASE , output_loading_info=SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) @slow def __UpperCAmelCase ( self :int ) -> Union[str, Any]: '''simple docstring''' # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: _a : str =AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) _a : int =TFAutoModelForSequenceClassification.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) @slow def __UpperCAmelCase ( self :str ) -> Tuple: '''simple docstring''' # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: _a : List[str] =AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) _a : List[Any] =TFAutoModelForQuestionAnswering.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) @slow @require_tensorflow_probability def __UpperCAmelCase ( self :Optional[int] ) -> List[str]: '''simple docstring''' for model_name in TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST[5:6]: _a : str =AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) _a : str =TFAutoModelForTableQuestionAnswering.from_pretrained(SCREAMING_SNAKE_CASE ) _a , _a : Dict =TFAutoModelForTableQuestionAnswering.from_pretrained( SCREAMING_SNAKE_CASE , output_loading_info=SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Dict ) -> List[Any]: '''simple docstring''' _a : Union[str, Any] =TFAutoModelWithLMHead.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=SCREAMING_SNAKE_CASE ) , 1_4_4_1_0 ) def __UpperCAmelCase ( self :Optional[int] ) -> str: '''simple docstring''' _a : str =TFAutoModelWithLMHead.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=SCREAMING_SNAKE_CASE ) , 1_4_4_1_0 ) def __UpperCAmelCase ( self :Union[str, Any] ) -> Dict: '''simple docstring''' # For the auto model mapping, FunnelConfig has two models: FunnelModel and FunnelBaseModel _a : Any =TFAutoModel.from_pretrained("""sgugger/funnel-random-tiny""" ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) _a : Optional[Any] =copy.deepcopy(model.config ) _a : List[Any] =["""FunnelBaseModel"""] _a : List[str] =TFAutoModel.from_config(SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =TFAutoModel.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Union[str, Any] ) -> List[str]: '''simple docstring''' try: AutoConfig.register("""new-model""" , SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =[ TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSequenceClassification, TFAutoModelForTokenClassification, ] for auto_class in auto_classes: with self.subTest(auto_class.__name__ ): # Wrong config class will raise an error with self.assertRaises(SCREAMING_SNAKE_CASE ): auto_class.register(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) auto_class.register(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(SCREAMING_SNAKE_CASE ): auto_class.register(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # Now that the config is registered, it can be used as any other config with the auto-API _a : str =BertModelTester(self ).get_config() _a : Optional[Any] =NewModelConfig(**tiny_config.to_dict() ) _a : Union[str, Any] =auto_class.from_config(SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(SCREAMING_SNAKE_CASE ) _a : str =auto_class.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) finally: if "new-model" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["new-model"] for mapping in ( TF_MODEL_MAPPING, TF_MODEL_FOR_PRETRAINING_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, ): if NewModelConfig in mapping._extra_content: del mapping._extra_content[NewModelConfig] def __UpperCAmelCase ( self :List[Any] ) -> Optional[int]: '''simple docstring''' with self.assertRaisesRegex( SCREAMING_SNAKE_CASE , """bert-base is not a local folder and is not a valid model identifier""" ): _a : List[str] =TFAutoModel.from_pretrained("""bert-base""" ) def __UpperCAmelCase ( self :Optional[int] ) -> str: '''simple docstring''' with self.assertRaisesRegex( SCREAMING_SNAKE_CASE , r"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)""" ): _a : Union[str, Any] =TFAutoModel.from_pretrained(SCREAMING_SNAKE_CASE , revision="""aaaaaa""" ) def __UpperCAmelCase ( self :str ) -> Optional[int]: '''simple docstring''' with self.assertRaisesRegex( SCREAMING_SNAKE_CASE , """hf-internal-testing/config-no-model does not appear to have a file named pytorch_model.bin""" , ): _a : List[str] =TFAutoModel.from_pretrained("""hf-internal-testing/config-no-model""" ) def __UpperCAmelCase ( self :Dict ) -> Union[str, Any]: '''simple docstring''' with self.assertRaisesRegex(SCREAMING_SNAKE_CASE , """Use `from_pt=True` to load this model""" ): _a : str =TFAutoModel.from_pretrained("""hf-internal-testing/tiny-bert-pt-only""" ) def __UpperCAmelCase ( self :Tuple ) -> Optional[Any]: '''simple docstring''' # Make sure we have cached the model. _a : List[Any] =TFAutoModel.from_pretrained("""hf-internal-testing/tiny-random-bert""" ) with RequestCounter() as counter: _a : str =TFAutoModel.from_pretrained("""hf-internal-testing/tiny-random-bert""" ) self.assertEqual(counter.get_request_count , 0 ) self.assertEqual(counter.head_request_count , 1 ) self.assertEqual(counter.other_request_count , 0 ) # With a sharded checkpoint _a : Optional[int] =TFAutoModel.from_pretrained("""ArthurZ/tiny-random-bert-sharded""" ) with RequestCounter() as counter: _a : List[Any] =TFAutoModel.from_pretrained("""ArthurZ/tiny-random-bert-sharded""" ) self.assertEqual(counter.get_request_count , 0 ) self.assertEqual(counter.head_request_count , 1 ) self.assertEqual(counter.other_request_count , 0 )
276
'''simple docstring''' import pytest from datasets.utils.sharding import _distribute_shards, _number_of_shards_in_gen_kwargs, _split_gen_kwargs @pytest.mark.parametrize( """kwargs, expected""" ,[ ({"""num_shards""": 0, """max_num_jobs""": 1}, []), ({"""num_shards""": 10, """max_num_jobs""": 1}, [range(10 )]), ({"""num_shards""": 10, """max_num_jobs""": 10}, [range(_UpperCAmelCase ,i + 1 ) for i in range(10 )]), ({"""num_shards""": 1, """max_num_jobs""": 10}, [range(1 )]), ({"""num_shards""": 10, """max_num_jobs""": 3}, [range(0 ,4 ), range(4 ,7 ), range(7 ,10 )]), ({"""num_shards""": 3, """max_num_jobs""": 10}, [range(0 ,1 ), range(1 ,2 ), range(2 ,3 )]), ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : Dict ) -> Optional[Any]: _a : Tuple =_distribute_shards(**_UpperCAmelCase ) assert out == expected @pytest.mark.parametrize( """gen_kwargs, max_num_jobs, expected""" ,[ ({"""foo""": 0}, 10, [{"""foo""": 0}]), ({"""shards""": [0, 1, 2, 3]}, 1, [{"""shards""": [0, 1, 2, 3]}]), ({"""shards""": [0, 1, 2, 3]}, 4, [{"""shards""": [0]}, {"""shards""": [1]}, {"""shards""": [2]}, {"""shards""": [3]}]), ({"""shards""": [0, 1]}, 4, [{"""shards""": [0]}, {"""shards""": [1]}]), ({"""shards""": [0, 1, 2, 3]}, 2, [{"""shards""": [0, 1]}, {"""shards""": [2, 3]}]), ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : List[Any] ,_UpperCAmelCase : Union[str, Any] ) -> List[str]: _a : List[str] =_split_gen_kwargs(_UpperCAmelCase ,_UpperCAmelCase ) assert out == expected @pytest.mark.parametrize( """gen_kwargs, expected""" ,[ ({"""foo""": 0}, 1), ({"""shards""": [0]}, 1), ({"""shards""": [0, 1, 2, 3]}, 4), ({"""shards""": [0, 1, 2, 3], """foo""": 0}, 4), ({"""shards""": [0, 1, 2, 3], """other""": (0, 1)}, 4), ({"""shards""": [0, 1, 2, 3], """shards2""": [0, 1]}, RuntimeError), ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : List[Any] ) -> Union[str, Any]: if expected is RuntimeError: with pytest.raises(_UpperCAmelCase ): _number_of_shards_in_gen_kwargs(_UpperCAmelCase ) else: _a : Dict =_number_of_shards_in_gen_kwargs(_UpperCAmelCase ) assert out == expected
276
1
'''simple docstring''' from dataclasses import dataclass, field from typing import Optional @dataclass class A__ : __UpperCamelCase : Optional[str] = field( default="codeparrot/codeparrot" , metadata={"help": "Model name or path of model to be trained."} ) __UpperCamelCase : Optional[str] = field( default="./" , metadata={"help": "Save dir where model repo is cloned and models updates are saved to."} ) __UpperCamelCase : Optional[str] = field( default="codeparrot/codeparrot-clean-train" , metadata={"help": "Name or path of training dataset."} ) __UpperCamelCase : Optional[str] = field( default="codeparrot/codeparrot-clean-valid" , metadata={"help": "Name or path of validation dataset."} ) __UpperCamelCase : Optional[int] = field(default=2 , metadata={"help": "Batch size for training."} ) __UpperCamelCase : Optional[int] = field(default=2 , metadata={"help": "Batch size for evaluation."} ) __UpperCamelCase : Optional[float] = field(default=0.1 , metadata={"help": "Value of weight decay."} ) __UpperCamelCase : Optional[int] = field( default=1_0000 , metadata={"help": "Size of buffer used to shuffle streaming dataset."} ) __UpperCamelCase : Optional[float] = field(default=2e-4 , metadata={"help": "Learning rate fo training."} ) __UpperCamelCase : Optional[str] = field(default="cosine" , metadata={"help": "Learning rate."} ) __UpperCamelCase : Optional[int] = field( default=750 , metadata={"help": "Number of warmup steps in the learning rate schedule."} ) __UpperCamelCase : Optional[int] = field( default=16 , metadata={"help": "Number of gradient accumulation steps."} ) __UpperCamelCase : Optional[bool] = field( default=UpperCAmelCase__ , metadata={"help": "Use gradient checkpointing to reduce memory footprint."} ) __UpperCamelCase : Optional[int] = field(default=5_0000 , metadata={"help": "Maximum number of training steps."} ) __UpperCamelCase : Optional[int] = field( default=-1 , metadata={"help": "Maximum number of evaluation steps. If -1 the full dataset is evaluated."} ) __UpperCamelCase : Optional[int] = field(default=1024 , metadata={"help": "Sequence lengths used for training."} ) __UpperCamelCase : Optional[int] = field(default=1 , metadata={"help": "Training seed."} ) __UpperCamelCase : Optional[int] = field( default=1024 , metadata={"help": "Interval to save checkpoints. Measured as number of forward passes not training steps."} , ) __UpperCamelCase : Optional[str] = field( default=UpperCAmelCase__ , metadata={"help": "States path if the training should continue from a checkpoint folder."} ) __UpperCamelCase : Optional[bool] = field(default=UpperCAmelCase__ , metadata={"help": "If True the data is pretokenized."} ) @dataclass class A__ : __UpperCamelCase : Optional[str] = field( default="codeparrot/codeparrot" , metadata={"help": "Model name or path of model to be evaluated."} ) __UpperCamelCase : Optional[str] = field( default="codeparrot/codeparrot-clean-valid" , metadata={"help": "Name or path of validation dataset."} ) __UpperCamelCase : Optional[int] = field(default=2 , metadata={"help": "Batch size used for evaluation."} ) __UpperCamelCase : Optional[int] = field( default=-1 , metadata={"help": "Maximum number of evaluation steps. If -1 the full dataset is evaluated."} ) __UpperCamelCase : Optional[int] = field(default=1024 , metadata={"help": "Length of sequences to be evaluated."} ) __UpperCamelCase : Optional[int] = field(default=1 , metadata={"help": "Random seed used for evaluation."} ) @dataclass class A__ : __UpperCamelCase : Optional[str] = field( default="codeparrot/codeparrot" , metadata={"help": "Model name or path of model to be evaluated."} ) __UpperCamelCase : Optional[int] = field(default=UpperCAmelCase__ , metadata={"help": "Number of workers used for code evaluation."} ) __UpperCamelCase : Optional[int] = field( default=UpperCAmelCase__ , metadata={"help": "The number of human-eval tasks to run. If not included all tasks are evaluated."} , ) __UpperCamelCase : Optional[bool] = field( default=UpperCAmelCase__ , metadata={"help": "Sample from the language model's output distribution."} ) __UpperCamelCase : Optional[float] = field(default=0.2 , metadata={"help": "Sampling temperature used for generation."} ) __UpperCamelCase : Optional[int] = field(default=256 , metadata={"help": "Maximum number of newly generated tokens."} ) __UpperCamelCase : Optional[int] = field(default=0 , metadata={"help": "Top-k parameter used for generation."} ) __UpperCamelCase : Optional[float] = field(default=0.95 , metadata={"help": "Top-p parameter used for nucleus sampling."} ) __UpperCamelCase : Optional[int] = field(default=10 , metadata={"help": "Number of generations to run in parallel."} ) __UpperCamelCase : Optional[int] = field( default=200 , metadata={"help": "Number of completions to generate for each sample."} ) __UpperCamelCase : Optional[int] = field(default=1 , metadata={"help": "Random seed used for evaluation."} ) __UpperCamelCase : Optional[str] = field( default="eval_results.json" , metadata={"help": "Random seed used for evaluation."} ) __UpperCamelCase : Optional[str] = field( default="0" , metadata={"help": "Allow `code_eval` to execute Python code on machine"} ) __UpperCamelCase : Optional[int] = field( default=-1 , metadata={ "help": ( "Determine which device to run the `text-generation` Pipeline on. -1 is CPU and any zero or positive" " number corresponds to which GPU device id to run on." ) } , ) @dataclass class A__ : __UpperCamelCase : Optional[int] = field( default=UpperCAmelCase__ , metadata={ "help": "The number of CPU cores to use for parallel preprocessing. Default uses the maximum available." } , ) __UpperCamelCase : Optional[str] = field( default="transformersbook/codeparrot" , metadata={"help": "Folder or name of dataset to process."} ) __UpperCamelCase : Optional[str] = field( default="codeparrot-clean" , metadata={"help": "Folder to save processed processed dataset."} ) __UpperCamelCase : Optional[int] = field( default=10_0000 , metadata={"help": "Number of files to save per JSON output file."} ) __UpperCamelCase : Optional[str] = field(default="content" , metadata={"help": "Column containing text data to process."} ) __UpperCamelCase : Optional[float] = field( default=1000 , metadata={"help": "Maximum line length in file, otherwise file is filtered."} ) __UpperCamelCase : Optional[float] = field( default=100 , metadata={"help": "Maximum mean line length in file, otherwise file is filtered."} ) __UpperCamelCase : Optional[float] = field( default=0.25 , metadata={"help": "Maximum fraction of non-alphanumeric characters, otherwise file is filtered."} ) __UpperCamelCase : Optional[float] = field( default=1.5 , metadata={"help": "Minimum character token ratio for the file, otherwise file is filtered."} ) __UpperCamelCase : Optional[float] = field( default=0.7 , metadata={"help": "Probability for filtering config, test and uncommon files."} ) __UpperCamelCase : Optional[str] = field( default="codeparrot/codeparrot" , metadata={"help": "Name or path to the tokenizer."} , ) __UpperCamelCase : Optional[bool] = field( default=UpperCAmelCase__ , metadata={"help": "If True, near-duplicate samples are removed."} ) __UpperCamelCase : Optional[float] = field( default=0.85 , metadata={"help": "Jaccard threshold for near-duplicate samples."} ) @dataclass class A__ : __UpperCamelCase : Optional[str] = field( default="gpt2" , metadata={"help": "Base tokenizer to build new tokenizer from."} ) __UpperCamelCase : Optional[str] = field( default="transformersbook/codeparrot-train" , metadata={"help": "Dataset to train tokenizer on."} ) __UpperCamelCase : Optional[str] = field(default="content" , metadata={"help": "Column containing text data to process."} ) __UpperCamelCase : Optional[int] = field(default=20_0000 , metadata={"help": "Number of examples to train tokenizer on."} ) __UpperCamelCase : Optional[int] = field( default=3_2768 , metadata={"help": "Number of examples to train the tokenizer on."} ) __UpperCamelCase : Optional[str] = field(default="codeparrot" , metadata={"help": "Name of new tokenizer."} ) __UpperCamelCase : Optional[bool] = field(default=UpperCAmelCase__ , metadata={"help": "Push saved tokenizer to the hub."} ) @dataclass class A__ : __UpperCamelCase : Optional[str] = field( default="codeparrot/codeparrot" , metadata={"help": "Name or path to the tokenizer."} ) __UpperCamelCase : Optional[str] = field( default="codeparrot/codeparrot-clean-train" , metadata={"help": "Name or path to the dataset to pretokenize."} ) __UpperCamelCase : Optional[str] = field( default="tokenized-codeparrot-train" , metadata={"help": "Repo name of the pretokenized data."} ) __UpperCamelCase : Optional[int] = field(default=UpperCAmelCase__ , metadata={"help": "Number of workers used for code evaluation."} ) @dataclass class A__ : __UpperCamelCase : Optional[str] = field( default="gpt2-large" , metadata={"help": "Configuration to use for model initialization."} ) __UpperCamelCase : Optional[str] = field( default="codeparrot/codeparrot" , metadata={"help": "Tokenizer attached to model."} ) __UpperCamelCase : Optional[str] = field(default="codeparrot" , metadata={"help": "Name of the created model."} ) __UpperCamelCase : Optional[bool] = field(default=UpperCAmelCase__ , metadata={"help": "Push saved tokenizer to the hub."} )
276
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A__: Dict = logging.get_logger(__name__) A__: Tuple = { '''weiweishi/roc-bert-base-zh''': '''https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json''', } class A__ ( UpperCAmelCase__ ): __UpperCamelCase : Tuple = "roc_bert" def __init__( self :Optional[int] , SCREAMING_SNAKE_CASE :Tuple=3_0_5_2_2 , SCREAMING_SNAKE_CASE :List[str]=7_6_8 , SCREAMING_SNAKE_CASE :Dict=1_2 , SCREAMING_SNAKE_CASE :List[str]=1_2 , SCREAMING_SNAKE_CASE :Tuple=3_0_7_2 , SCREAMING_SNAKE_CASE :List[Any]="gelu" , SCREAMING_SNAKE_CASE :Union[str, Any]=0.1 , SCREAMING_SNAKE_CASE :List[Any]=0.1 , SCREAMING_SNAKE_CASE :int=5_1_2 , SCREAMING_SNAKE_CASE :Optional[Any]=2 , SCREAMING_SNAKE_CASE :Union[str, Any]=0.02 , SCREAMING_SNAKE_CASE :Optional[Any]=1e-12 , SCREAMING_SNAKE_CASE :Any=True , SCREAMING_SNAKE_CASE :List[Any]=0 , SCREAMING_SNAKE_CASE :Optional[int]="absolute" , SCREAMING_SNAKE_CASE :Union[str, Any]=None , SCREAMING_SNAKE_CASE :List[Any]=True , SCREAMING_SNAKE_CASE :int=True , SCREAMING_SNAKE_CASE :Optional[int]=7_6_8 , SCREAMING_SNAKE_CASE :Optional[Any]=9_1_0 , SCREAMING_SNAKE_CASE :Union[str, Any]=5_1_2 , SCREAMING_SNAKE_CASE :str=2_4_8_5_8 , SCREAMING_SNAKE_CASE :List[Any]=True , **SCREAMING_SNAKE_CASE :Tuple , ) -> Optional[int]: '''simple docstring''' _a : List[str] =vocab_size _a : List[str] =max_position_embeddings _a : Optional[Any] =hidden_size _a : List[Any] =num_hidden_layers _a : List[str] =num_attention_heads _a : int =intermediate_size _a : Any =hidden_act _a : Dict =hidden_dropout_prob _a : int =attention_probs_dropout_prob _a : str =initializer_range _a : Optional[int] =type_vocab_size _a : Any =layer_norm_eps _a : Any =use_cache _a : Optional[int] =enable_pronunciation _a : Optional[Any] =enable_shape _a : Optional[Any] =pronunciation_embed_dim _a : Tuple =pronunciation_vocab_size _a : Union[str, Any] =shape_embed_dim _a : Any =shape_vocab_size _a : Tuple =concat_input _a : List[str] =position_embedding_type _a : List[str] =classifier_dropout super().__init__(pad_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE )
276
1
'''simple docstring''' import argparse import torch from transformers import YosoConfig, YosoForMaskedLM def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[str] ) -> List[str]: if "model" in orig_key: _a : str =orig_key.replace("""model.""" ,"""""" ) if "norm1" in orig_key: _a : List[str] =orig_key.replace("""norm1""" ,"""attention.output.LayerNorm""" ) if "norm2" in orig_key: _a : int =orig_key.replace("""norm2""" ,"""output.LayerNorm""" ) if "norm" in orig_key: _a : List[Any] =orig_key.replace("""norm""" ,"""LayerNorm""" ) if "transformer" in orig_key: _a : Optional[int] =orig_key.split(""".""" )[0].split("""_""" )[-1] _a : Dict =orig_key.replace(F"transformer_{layer_num}" ,F"encoder.layer.{layer_num}" ) if "mha.attn" in orig_key: _a : int =orig_key.replace("""mha.attn""" ,"""attention.self""" ) if "mha" in orig_key: _a : Any =orig_key.replace("""mha""" ,"""attention""" ) if "W_q" in orig_key: _a : Optional[Any] =orig_key.replace("""W_q""" ,"""self.query""" ) if "W_k" in orig_key: _a : Any =orig_key.replace("""W_k""" ,"""self.key""" ) if "W_v" in orig_key: _a : Tuple =orig_key.replace("""W_v""" ,"""self.value""" ) if "ff1" in orig_key: _a : List[Any] =orig_key.replace("""ff1""" ,"""intermediate.dense""" ) if "ff2" in orig_key: _a : str =orig_key.replace("""ff2""" ,"""output.dense""" ) if "ff" in orig_key: _a : int =orig_key.replace("""ff""" ,"""output.dense""" ) if "mlm_class" in orig_key: _a : Optional[int] =orig_key.replace("""mlm.mlm_class""" ,"""cls.predictions.decoder""" ) if "mlm" in orig_key: _a : Dict =orig_key.replace("""mlm""" ,"""cls.predictions.transform""" ) if "cls" not in orig_key: _a : int ="""yoso.""" + orig_key return orig_key def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Any ,_UpperCAmelCase : Dict ) -> Dict: for key in orig_state_dict.copy().keys(): _a : Union[str, Any] =orig_state_dict.pop(_UpperCAmelCase ) if ("pooler" in key) or ("sen_class" in key): continue else: _a : Optional[int] =val _a : Optional[int] =orig_state_dict["""cls.predictions.decoder.bias"""] _a : Optional[Any] =torch.arange(_UpperCAmelCase ).expand((1, -1) ) + 2 return orig_state_dict def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[str] ,_UpperCAmelCase : int ,_UpperCAmelCase : Optional[int] ) -> Dict: _a : Any =torch.load(_UpperCAmelCase ,map_location="""cpu""" )["""model_state_dict"""] _a : List[str] =YosoConfig.from_json_file(_UpperCAmelCase ) _a : Union[str, Any] =YosoForMaskedLM(_UpperCAmelCase ) _a : Union[str, Any] =convert_checkpoint_helper(config.max_position_embeddings ,_UpperCAmelCase ) print(model.load_state_dict(_UpperCAmelCase ) ) model.eval() model.save_pretrained(_UpperCAmelCase ) print(F"Checkpoint successfuly converted. Model saved at {pytorch_dump_path}" ) if __name__ == "__main__": A__: List[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--pytorch_model_path''', default=None, type=str, required=True, help='''Path to YOSO pytorch checkpoint.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help='''The json file for YOSO model config.''', ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) A__: List[str] = parser.parse_args() convert_yoso_checkpoint(args.pytorch_model_path, args.config_file, args.pytorch_dump_path)
276
'''simple docstring''' class A__ : def __init__( self :List[str] ) -> List[Any]: '''simple docstring''' _a : Tuple =0 _a : Any =0 _a : int ={} def __UpperCAmelCase ( self :Any , SCREAMING_SNAKE_CASE :List[str] ) -> Optional[int]: '''simple docstring''' if vertex not in self.adjacency: _a : Dict ={} self.num_vertices += 1 def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Any ) -> List[str]: '''simple docstring''' self.add_vertex(SCREAMING_SNAKE_CASE ) self.add_vertex(SCREAMING_SNAKE_CASE ) if head == tail: return _a : Any =weight _a : Tuple =weight def __UpperCAmelCase ( self :Dict ) -> Optional[int]: '''simple docstring''' _a : Union[str, Any] =self.get_edges() for edge in edges: _a , _a , _a : List[str] =edge edges.remove((tail, head, weight) ) for i in range(len(SCREAMING_SNAKE_CASE ) ): _a : str =list(edges[i] ) edges.sort(key=lambda SCREAMING_SNAKE_CASE : e[2] ) for i in range(len(SCREAMING_SNAKE_CASE ) - 1 ): if edges[i][2] >= edges[i + 1][2]: _a : Union[str, Any] =edges[i][2] + 1 for edge in edges: _a , _a , _a : Tuple =edge _a : Tuple =weight _a : List[Any] =weight def __str__( self :int ) -> str: '''simple docstring''' _a : int ="""""" for tail in self.adjacency: for head in self.adjacency[tail]: _a : str =self.adjacency[head][tail] string += f"{head} -> {tail} == {weight}\n" return string.rstrip("""\n""" ) def __UpperCAmelCase ( self :Optional[int] ) -> Optional[Any]: '''simple docstring''' _a : Union[str, Any] =[] for tail in self.adjacency: for head in self.adjacency[tail]: output.append((tail, head, self.adjacency[head][tail]) ) return output def __UpperCAmelCase ( self :List[Any] ) -> List[Any]: '''simple docstring''' return self.adjacency.keys() @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :Dict=None , SCREAMING_SNAKE_CASE :List[Any]=None ) -> Optional[int]: '''simple docstring''' _a : str =Graph() if vertices is None: _a : Union[str, Any] =[] if edges is None: _a : List[Any] =[] for vertex in vertices: g.add_vertex(SCREAMING_SNAKE_CASE ) for edge in edges: g.add_edge(*SCREAMING_SNAKE_CASE ) return g class A__ : def __init__( self :Optional[int] ) -> Union[str, Any]: '''simple docstring''' _a : Optional[int] ={} _a : List[str] ={} def __len__( self :List[Any] ) -> List[Any]: '''simple docstring''' return len(self.parent ) def __UpperCAmelCase ( self :Tuple , SCREAMING_SNAKE_CASE :Tuple ) -> Dict: '''simple docstring''' if item in self.parent: return self.find(SCREAMING_SNAKE_CASE ) _a : Optional[Any] =item _a : List[str] =0 return item def __UpperCAmelCase ( self :int , SCREAMING_SNAKE_CASE :Dict ) -> List[str]: '''simple docstring''' if item not in self.parent: return self.make_set(SCREAMING_SNAKE_CASE ) if item != self.parent[item]: _a : str =self.find(self.parent[item] ) return self.parent[item] def __UpperCAmelCase ( self :Optional[int] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :List[Any] ) -> Optional[Any]: '''simple docstring''' _a : Optional[int] =self.find(SCREAMING_SNAKE_CASE ) _a : Dict =self.find(SCREAMING_SNAKE_CASE ) if roota == roota: return roota if self.rank[roota] > self.rank[roota]: _a : Any =roota return roota if self.rank[roota] < self.rank[roota]: _a : List[str] =roota return roota if self.rank[roota] == self.rank[roota]: self.rank[roota] += 1 _a : List[Any] =roota return roota return None @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :Dict ) -> Union[str, Any]: '''simple docstring''' _a : Any =graph.num_vertices _a : Union[str, Any] =Graph.UnionFind() _a : Optional[int] =[] while num_components > 1: _a : str ={} for vertex in graph.get_vertices(): _a : List[str] =-1 _a : Any =graph.get_edges() for edge in edges: _a , _a , _a : Tuple =edge edges.remove((tail, head, weight) ) for edge in edges: _a , _a , _a : Any =edge _a : Any =union_find.find(SCREAMING_SNAKE_CASE ) _a : List[Any] =union_find.find(SCREAMING_SNAKE_CASE ) if seta != seta: if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight: _a : Optional[int] =[head, tail, weight] if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight: _a : List[Any] =[head, tail, weight] for vertex in cheap_edge: if cheap_edge[vertex] != -1: _a , _a , _a : Optional[Any] =cheap_edge[vertex] if union_find.find(SCREAMING_SNAKE_CASE ) != union_find.find(SCREAMING_SNAKE_CASE ): union_find.union(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) mst_edges.append(cheap_edge[vertex] ) _a : str =num_components - 1 _a : str =Graph.build(edges=SCREAMING_SNAKE_CASE ) return mst
276
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) A__: List[str] = {'''configuration_vit_mae''': ['''VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ViTMAEConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: int = [ '''VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ViTMAEForPreTraining''', '''ViTMAELayer''', '''ViTMAEModel''', '''ViTMAEPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Tuple = [ '''TFViTMAEForPreTraining''', '''TFViTMAEModel''', '''TFViTMAEPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_vit_mae import VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTMAEConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vit_mae import ( VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST, ViTMAEForPreTraining, ViTMAELayer, ViTMAEModel, ViTMAEPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vit_mae import TFViTMAEForPreTraining, TFViTMAEModel, TFViTMAEPreTrainedModel else: import sys A__: int = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
276
'''simple docstring''' from datetime import datetime import requests from bsa import BeautifulSoup if __name__ == "__main__": A__: Union[str, Any] = input('''Enter image url: ''').strip() print(F"Downloading image from {url} ...") A__: Tuple = BeautifulSoup(requests.get(url).content, '''html.parser''') # The image URL is in the content field of the first meta tag with property og:image A__: Union[str, Any] = soup.find('''meta''', {'''property''': '''og:image'''})['''content'''] A__: List[Any] = requests.get(image_url).content A__: List[str] = F"{datetime.now():%Y-%m-%d_%H:%M:%S}.jpg" with open(file_name, '''wb''') as fp: fp.write(image_data) print(F"Done. Image saved to disk as {file_name}.")
276
1
'''simple docstring''' from collections.abc import Sequence def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Sequence[float] ,_UpperCAmelCase : bool = False ) -> float: if not arr: return 0 _a : Dict =0 if allow_empty_subarrays else float("""-inf""" ) _a : Optional[int] =0.0 for num in arr: _a : Any =max(0 if allow_empty_subarrays else num ,curr_sum + num ) _a : int =max(_UpperCAmelCase ,_UpperCAmelCase ) return max_sum if __name__ == "__main__": from doctest import testmod testmod() A__: Tuple = [-2, 1, -3, 4, -1, 2, 1, -5, 4] print(F"{max_subarray_sum(nums) = }")
276
'''simple docstring''' A__: Tuple = ''' # Installazione di Transformers ! pip install transformers datasets # Per installare dalla fonte invece dell\'ultima versione rilasciata, commenta il comando sopra e # rimuovi la modalità commento al comando seguente. # ! pip install git+https://github.com/huggingface/transformers.git ''' A__: Tuple = [{'''type''': '''code''', '''content''': INSTALL_CONTENT}] A__: Any = { '''{processor_class}''': '''FakeProcessorClass''', '''{model_class}''': '''FakeModelClass''', '''{object_class}''': '''FakeObjectClass''', }
276
1
'''simple docstring''' import unittest from transformers import EsmConfig, is_torch_available from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import EsmForMaskedLM, EsmForSequenceClassification, EsmForTokenClassification, EsmModel from transformers.models.esm.modeling_esm import ( ESM_PRETRAINED_MODEL_ARCHIVE_LIST, EsmEmbeddings, create_position_ids_from_input_ids, ) class A__ : def __init__( self :Tuple , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :Optional[int]=1_3 , SCREAMING_SNAKE_CASE :Optional[int]=7 , SCREAMING_SNAKE_CASE :Tuple=False , SCREAMING_SNAKE_CASE :Dict=True , SCREAMING_SNAKE_CASE :Optional[int]=False , SCREAMING_SNAKE_CASE :Optional[Any]=True , SCREAMING_SNAKE_CASE :List[str]=3_3 , SCREAMING_SNAKE_CASE :Tuple=3_2 , SCREAMING_SNAKE_CASE :Tuple=5 , SCREAMING_SNAKE_CASE :int=4 , SCREAMING_SNAKE_CASE :Union[str, Any]=3_7 , SCREAMING_SNAKE_CASE :List[str]="gelu" , SCREAMING_SNAKE_CASE :Optional[Any]=0.1 , SCREAMING_SNAKE_CASE :Tuple=0.1 , SCREAMING_SNAKE_CASE :str=5_1_2 , SCREAMING_SNAKE_CASE :Dict=1_6 , SCREAMING_SNAKE_CASE :Dict=2 , SCREAMING_SNAKE_CASE :Union[str, Any]=0.02 , SCREAMING_SNAKE_CASE :str=3 , SCREAMING_SNAKE_CASE :List[str]=4 , SCREAMING_SNAKE_CASE :List[str]=None , ) -> Union[str, Any]: '''simple docstring''' _a : Union[str, Any] =parent _a : List[Any] =batch_size _a : Optional[int] =seq_length _a : Union[str, Any] =is_training _a : List[Any] =use_input_mask _a : Optional[int] =use_token_type_ids _a : int =use_labels _a : List[str] =vocab_size _a : List[Any] =hidden_size _a : int =num_hidden_layers _a : Tuple =num_attention_heads _a : Any =intermediate_size _a : str =hidden_act _a : Union[str, Any] =hidden_dropout_prob _a : Union[str, Any] =attention_probs_dropout_prob _a : str =max_position_embeddings _a : Dict =type_vocab_size _a : Tuple =type_sequence_label_size _a : Dict =initializer_range _a : List[str] =num_labels _a : Tuple =num_choices _a : int =scope def __UpperCAmelCase ( self :Union[str, Any] ) -> str: '''simple docstring''' _a : Optional[int] =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _a : List[Any] =None if self.use_input_mask: _a : Any =random_attention_mask([self.batch_size, self.seq_length] ) _a : Optional[int] =None _a : str =None _a : Dict =None if self.use_labels: _a : Dict =ids_tensor([self.batch_size] , self.type_sequence_label_size ) _a : str =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _a : List[str] =ids_tensor([self.batch_size] , self.num_choices ) _a : List[Any] =self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCAmelCase ( self :str ) -> Optional[int]: '''simple docstring''' return EsmConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , pad_token_id=1 , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) def __UpperCAmelCase ( self :List[str] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :int ) -> Tuple: '''simple docstring''' _a : Any =EsmModel(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() _a : Optional[Any] =model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =model(SCREAMING_SNAKE_CASE ) _a : str =model(SCREAMING_SNAKE_CASE ) 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 __UpperCAmelCase ( self :str , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :Optional[Any] ) -> Dict: '''simple docstring''' _a : str =EsmForMaskedLM(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() _a : Union[str, Any] =model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :List[Any] , SCREAMING_SNAKE_CASE :Union[str, Any] ) -> Optional[Any]: '''simple docstring''' _a : int =self.num_labels _a : Tuple =EsmForTokenClassification(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() _a : Tuple =model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCAmelCase ( self :Dict ) -> List[str]: '''simple docstring''' _a : Optional[Any] =self.prepare_config_and_inputs() ( ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ) : Any =config_and_inputs _a : List[Any] ={"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class A__ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): __UpperCamelCase : Any = False __UpperCamelCase : Any = ( ( EsmForMaskedLM, EsmModel, EsmForSequenceClassification, EsmForTokenClassification, ) if is_torch_available() else () ) __UpperCamelCase : str = () __UpperCamelCase : List[str] = ( { "feature-extraction": EsmModel, "fill-mask": EsmForMaskedLM, "text-classification": EsmForSequenceClassification, "token-classification": EsmForTokenClassification, "zero-shot": EsmForSequenceClassification, } if is_torch_available() else {} ) __UpperCamelCase : Union[str, Any] = True def __UpperCAmelCase ( self :Optional[int] ) -> int: '''simple docstring''' _a : Dict =EsmModelTester(self ) _a : Optional[Any] =ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , hidden_size=3_7 ) def __UpperCAmelCase ( self :Tuple ) -> List[Any]: '''simple docstring''' self.config_tester.run_common_tests() def __UpperCAmelCase ( self :Optional[int] ) -> str: '''simple docstring''' _a : List[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :List[Any] ) -> Dict: '''simple docstring''' _a : List[str] =self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: _a : Dict =type self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Dict ) -> List[str]: '''simple docstring''' _a : Tuple =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :List[Any] ) -> List[str]: '''simple docstring''' _a : str =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE ) @slow def __UpperCAmelCase ( self :str ) -> Dict: '''simple docstring''' for model_name in ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _a : Union[str, Any] =EsmModel.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Tuple ) -> int: '''simple docstring''' _a : Optional[Any] =self.model_tester.prepare_config_and_inputs()[0] _a : Dict =EsmEmbeddings(config=SCREAMING_SNAKE_CASE ) _a : Tuple =torch.as_tensor([[1_2, 3_1, 1_3, model.padding_idx]] ) _a : Optional[Any] =torch.as_tensor( [ [ 0 + model.padding_idx + 1, 1 + model.padding_idx + 1, 2 + model.padding_idx + 1, model.padding_idx, ] ] ) _a : Any =create_position_ids_from_input_ids(SCREAMING_SNAKE_CASE , model.padding_idx ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) ) def __UpperCAmelCase ( self :Optional[Any] ) -> Tuple: '''simple docstring''' _a : List[Any] =self.model_tester.prepare_config_and_inputs()[0] _a : Optional[int] =EsmEmbeddings(config=SCREAMING_SNAKE_CASE ) _a : Tuple =torch.empty(2 , 4 , 3_0 ) _a : str =[ 0 + embeddings.padding_idx + 1, 1 + embeddings.padding_idx + 1, 2 + embeddings.padding_idx + 1, 3 + embeddings.padding_idx + 1, ] _a : int =torch.as_tensor([expected_single_positions, expected_single_positions] ) _a : Any =embeddings.create_position_ids_from_inputs_embeds(SCREAMING_SNAKE_CASE ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) ) @unittest.skip("""Esm does not support embedding resizing""" ) def __UpperCAmelCase ( self :Tuple ) -> List[str]: '''simple docstring''' pass @unittest.skip("""Esm does not support embedding resizing""" ) def __UpperCAmelCase ( self :str ) -> Any: '''simple docstring''' pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def __UpperCAmelCase ( self :Dict ) -> Any: '''simple docstring''' pass @require_torch class A__ ( UpperCAmelCase__ ): @slow def __UpperCAmelCase ( self :List[Any] ) -> str: '''simple docstring''' with torch.no_grad(): _a : Optional[int] =EsmForMaskedLM.from_pretrained("""facebook/esm2_t6_8M_UR50D""" ) model.eval() _a : Any =torch.tensor([[0, 1, 2, 3, 4, 5]] ) _a : Tuple =model(SCREAMING_SNAKE_CASE )[0] _a : int =3_3 _a : Tuple =torch.Size((1, 6, vocab_size) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =torch.tensor( [[[8.9_215, -10.5_898, -6.4_671], [-6.3_967, -13.9_114, -1.1_212], [-7.7_812, -13.9_516, -3.7_406]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) ) @slow def __UpperCAmelCase ( self :Union[str, Any] ) -> Tuple: '''simple docstring''' with torch.no_grad(): _a : Any =EsmModel.from_pretrained("""facebook/esm2_t6_8M_UR50D""" ) model.eval() _a : Any =torch.tensor([[0, 6, 4, 1_3, 5, 4, 1_6, 1_2, 1_1, 7, 2]] ) _a : int =model(SCREAMING_SNAKE_CASE )[0] # compare the actual values for a slice. _a : str =torch.tensor( [[[0.1_444, 0.5_413, 0.3_248], [0.3_034, 0.0_053, 0.3_108], [0.3_228, -0.2_499, 0.3_415]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) )
276
'''simple docstring''' A__: Optional[int] = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] A__: Any = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] A__: int = { 0: '''Sunday''', 1: '''Monday''', 2: '''Tuesday''', 3: '''Wednesday''', 4: '''Thursday''', 5: '''Friday''', 6: '''Saturday''', } def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ,_UpperCAmelCase : int ,_UpperCAmelCase : int ) -> str: assert len(str(_UpperCAmelCase ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 12, "month should be between 1 to 12" assert 1 <= day <= 31, "day should be between 1 to 31" # Doomsday algorithm: _a : List[str] =year // 100 _a : List[str] =(5 * (century % 4) + 2) % 7 _a : Optional[int] =year % 100 _a : Any =centurian % 12 _a : int =( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 _a : Optional[Any] =( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 400) == 0) else DOOMSDAY_LEAP[month - 1] ) _a : str =(dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
276
1
'''simple docstring''' # Lint as: python3 # pylint: enable=line-too-long # pylint: disable=g-import-not-at-top,g-bad-import-order,wrong-import-position A__: Tuple = '''2.13.1''' import platform import pyarrow from packaging import version if version.parse(platform.python_version()) < version.parse('''3.7'''): raise ImportWarning( '''To use `datasets`, Python>=3.7 is required, and the current version of Python doesn\'t match this condition.''' ) if version.parse(pyarrow.__version__).major < 8: raise ImportWarning( '''To use `datasets`, the module `pyarrow>=8.0.0` is required, and the current version of `pyarrow` doesn\'t match this condition.\n''' '''If you are running this in a Google Colab, you should probably just restart the runtime to use the right version of `pyarrow`.''' ) del platform del pyarrow del version from .arrow_dataset import Dataset from .arrow_reader import ReadInstruction from .builder import ArrowBasedBuilder, BeamBasedBuilder, BuilderConfig, DatasetBuilder, GeneratorBasedBuilder from .combine import concatenate_datasets, interleave_datasets from .dataset_dict import DatasetDict, IterableDatasetDict from .download import * from .features import * from .fingerprint import disable_caching, enable_caching, is_caching_enabled, set_caching_enabled from .info import DatasetInfo, MetricInfo from .inspect import ( get_dataset_config_info, get_dataset_config_names, get_dataset_infos, get_dataset_split_names, inspect_dataset, inspect_metric, list_datasets, list_metrics, ) from .iterable_dataset import IterableDataset from .load import load_dataset, load_dataset_builder, load_from_disk, load_metric from .metric import Metric from .splits import ( NamedSplit, NamedSplitAll, Split, SplitBase, SplitDict, SplitGenerator, SplitInfo, SubSplitInfo, percent, ) from .tasks import * from .utils import * from .utils import logging # deprecated modules from datasets import arrow_dataset as _arrow_dataset # isort:skip from datasets import utils as _utils # isort:skip from datasets.utils import download_manager as _deprecated_download_manager # isort:skip A__: Union[str, Any] = concatenate_datasets A__: Tuple = DownloadConfig A__: Optional[int] = DownloadManager A__: Optional[Any] = DownloadMode A__: Optional[int] = DownloadConfig A__: Tuple = DownloadMode A__: Union[str, Any] = DownloadManager del _arrow_dataset, _utils, _deprecated_download_manager
276
'''simple docstring''' from __future__ import annotations from typing import TypedDict class A__ ( UpperCAmelCase__ ): __UpperCamelCase : str __UpperCamelCase : int def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ) -> list[str]: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError("""The parameter s type must be str.""" ) return [s[i:] + s[:i] for i in range(len(_UpperCAmelCase ) )] def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ) -> BWTTransformDict: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError("""The parameter s type must be str.""" ) if not s: raise ValueError("""The parameter s must not be empty.""" ) _a : List[Any] =all_rotations(_UpperCAmelCase ) rotations.sort() # sort the list of rotations in alphabetically order # make a string composed of the last char of each rotation _a : BWTTransformDict ={ "bwt_string": "".join([word[-1] for word in rotations] ), "idx_original_string": rotations.index(_UpperCAmelCase ), } return response def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : int ) -> str: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError("""The parameter bwt_string type must be str.""" ) if not bwt_string: raise ValueError("""The parameter bwt_string must not be empty.""" ) try: _a : List[str] =int(_UpperCAmelCase ) except ValueError: raise TypeError( """The parameter idx_original_string type must be int or passive""" """ of cast to int.""" ) if idx_original_string < 0: raise ValueError("""The parameter idx_original_string must not be lower than 0.""" ) if idx_original_string >= len(_UpperCAmelCase ): raise ValueError( """The parameter idx_original_string must be lower than""" """ len(bwt_string).""" ) _a : Optional[int] =[""""""] * len(_UpperCAmelCase ) for _ in range(len(_UpperCAmelCase ) ): for i in range(len(_UpperCAmelCase ) ): _a : int =bwt_string[i] + ordered_rotations[i] ordered_rotations.sort() return ordered_rotations[idx_original_string] if __name__ == "__main__": A__: Any = '''Provide a string that I will generate its BWT transform: ''' A__: Union[str, Any] = input(entry_msg).strip() A__: Optional[int] = bwt_transform(s) print( F"Burrows Wheeler transform for string '{s}' results " F"in '{result['bwt_string']}'" ) A__: Union[str, Any] = reverse_bwt(result['''bwt_string'''], result['''idx_original_string''']) print( F"Reversing Burrows Wheeler transform for entry '{result['bwt_string']}' " F"we get original string '{original_string}'" )
276
1
'''simple docstring''' A__: Optional[Any] = { '''A''': ['''B''', '''C''', '''E'''], '''B''': ['''A''', '''D''', '''E'''], '''C''': ['''A''', '''F''', '''G'''], '''D''': ['''B'''], '''E''': ['''A''', '''B''', '''D'''], '''F''': ['''C'''], '''G''': ['''C'''], } def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : dict ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : Optional[Any] ) -> list[str]: _a : List[Any] =set() # keep track of all the paths to be checked _a : Tuple =[[start]] # return path if start is goal if start == goal: return [start] # keeps looping until all possible paths have been checked while queue: # pop the first path from the queue _a : Optional[int] =queue.pop(0 ) # get the last node from the path _a : Any =path[-1] if node not in explored: _a : Dict =graph[node] # go through all neighbour nodes, construct a new path and # push it into the queue for neighbour in neighbours: _a : Any =list(_UpperCAmelCase ) new_path.append(_UpperCAmelCase ) queue.append(_UpperCAmelCase ) # return path if neighbour is goal if neighbour == goal: return new_path # mark node as explored explored.add(_UpperCAmelCase ) # in case there's no path between the 2 nodes return [] def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : dict ,_UpperCAmelCase : Any ,_UpperCAmelCase : Optional[Any] ) -> int: if not graph or start not in graph or target not in graph: return -1 if start == target: return 0 _a : str =[start] _a : Optional[Any] =set(_UpperCAmelCase ) # Keep tab on distances from `start` node. _a : int ={start: 0, target: -1} while queue: _a : str =queue.pop(0 ) if node == target: _a : Optional[Any] =( dist[node] if dist[target] == -1 else min(dist[target] ,dist[node] ) ) for adjacent in graph[node]: if adjacent not in visited: visited.add(_UpperCAmelCase ) queue.append(_UpperCAmelCase ) _a : str =dist[node] + 1 return dist[target] if __name__ == "__main__": print(bfs_shortest_path(demo_graph, '''G''', '''D''')) # returns ['G', 'C', 'A', 'B', 'D'] print(bfs_shortest_path_distance(demo_graph, '''G''', '''D''')) # returns 4
276
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available A__: List[str] = { '''configuration_chinese_clip''': [ '''CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ChineseCLIPConfig''', '''ChineseCLIPOnnxConfig''', '''ChineseCLIPTextConfig''', '''ChineseCLIPVisionConfig''', ], '''processing_chinese_clip''': ['''ChineseCLIPProcessor'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Optional[int] = ['''ChineseCLIPFeatureExtractor'''] A__: Any = ['''ChineseCLIPImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Dict = [ '''CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ChineseCLIPModel''', '''ChineseCLIPPreTrainedModel''', '''ChineseCLIPTextModel''', '''ChineseCLIPVisionModel''', ] if TYPE_CHECKING: from .configuration_chinese_clip import ( CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, ChineseCLIPConfig, ChineseCLIPOnnxConfig, ChineseCLIPTextConfig, ChineseCLIPVisionConfig, ) from .processing_chinese_clip import ChineseCLIPProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_chinese_clip import ChineseCLIPFeatureExtractor, ChineseCLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_chinese_clip import ( CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, ChineseCLIPModel, ChineseCLIPPreTrainedModel, ChineseCLIPTextModel, ChineseCLIPVisionModel, ) else: import sys A__: str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
276
1
'''simple docstring''' import inspect import unittest from datasets import load_dataset from packaging import version from transformers import BeitConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_MAPPING, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation, BeitModel, ) from transformers.models.beit.modeling_beit import BEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): import PIL from PIL import Image from transformers import BeitImageProcessor class A__ : def __init__( self :Optional[int] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :List[Any]=1_0_0 , SCREAMING_SNAKE_CASE :str=1_3 , SCREAMING_SNAKE_CASE :List[str]=3_0 , SCREAMING_SNAKE_CASE :str=2 , SCREAMING_SNAKE_CASE :int=3 , SCREAMING_SNAKE_CASE :Tuple=True , SCREAMING_SNAKE_CASE :List[str]=True , SCREAMING_SNAKE_CASE :Union[str, Any]=3_2 , SCREAMING_SNAKE_CASE :Dict=4 , SCREAMING_SNAKE_CASE :Optional[Any]=4 , SCREAMING_SNAKE_CASE :str=3_7 , SCREAMING_SNAKE_CASE :Tuple="gelu" , SCREAMING_SNAKE_CASE :List[Any]=0.1 , SCREAMING_SNAKE_CASE :Optional[int]=0.1 , SCREAMING_SNAKE_CASE :List[Any]=1_0 , SCREAMING_SNAKE_CASE :Any=0.02 , SCREAMING_SNAKE_CASE :Any=3 , SCREAMING_SNAKE_CASE :Dict=None , SCREAMING_SNAKE_CASE :List[Any]=[0, 1, 2, 3] , ) -> Dict: '''simple docstring''' _a : Tuple =parent _a : Dict =1_0_0 _a : List[Any] =batch_size _a : Dict =image_size _a : Union[str, Any] =patch_size _a : Any =num_channels _a : Optional[int] =is_training _a : Optional[int] =use_labels _a : List[str] =hidden_size _a : Dict =num_hidden_layers _a : Any =num_attention_heads _a : int =intermediate_size _a : Dict =hidden_act _a : str =hidden_dropout_prob _a : int =attention_probs_dropout_prob _a : Optional[Any] =type_sequence_label_size _a : Optional[int] =initializer_range _a : Optional[int] =scope _a : Tuple =out_indices _a : Tuple =num_labels # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) _a : Optional[int] =(image_size // patch_size) ** 2 _a : Optional[Any] =num_patches + 1 def __UpperCAmelCase ( self :Any ) -> List[str]: '''simple docstring''' _a : Tuple =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _a : Dict =None _a : int =None if self.use_labels: _a : Optional[int] =ids_tensor([self.batch_size] , self.type_sequence_label_size ) _a : List[Any] =ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) _a : Union[str, Any] =self.get_config() return config, pixel_values, labels, pixel_labels def __UpperCAmelCase ( self :Optional[int] ) -> List[Any]: '''simple docstring''' return BeitConfig( vocab_size=self.vocab_size , 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=SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , out_indices=self.out_indices , ) def __UpperCAmelCase ( self :int , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :Dict ) -> Any: '''simple docstring''' _a : List[Any] =BeitModel(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() _a : Optional[Any] =model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self :Any , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :Any ) -> str: '''simple docstring''' _a : Optional[Any] =BeitForMaskedImageModeling(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() _a : List[Any] =model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length - 1, self.vocab_size) ) def __UpperCAmelCase ( self :List[str] , SCREAMING_SNAKE_CASE :Optional[int] , SCREAMING_SNAKE_CASE :List[Any] , SCREAMING_SNAKE_CASE :List[Any] , SCREAMING_SNAKE_CASE :Tuple ) -> Optional[Any]: '''simple docstring''' _a : str =self.type_sequence_label_size _a : Union[str, Any] =BeitForImageClassification(SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() _a : Union[str, Any] =model(SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images _a : Optional[Any] =1 _a : Optional[int] =BeitForImageClassification(SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() _a : str =floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) _a : Tuple =model(SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Optional[int] , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :Union[str, Any] ) -> str: '''simple docstring''' _a : Any =self.num_labels _a : List[Any] =BeitForSemanticSegmentation(SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() _a : List[Any] =model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2) ) _a : Dict =model(SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2) ) def __UpperCAmelCase ( self :Tuple ) -> List[str]: '''simple docstring''' _a : int =self.prepare_config_and_inputs() _a , _a , _a , _a : List[str] =config_and_inputs _a : Dict ={"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class A__ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): __UpperCamelCase : Tuple = ( (BeitModel, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation) if is_torch_available() else () ) __UpperCamelCase : List[str] = ( { "feature-extraction": BeitModel, "image-classification": BeitForImageClassification, "image-segmentation": BeitForSemanticSegmentation, } if is_torch_available() else {} ) __UpperCamelCase : List[Any] = False __UpperCamelCase : Optional[int] = False __UpperCamelCase : List[Any] = False def __UpperCAmelCase ( self :List[Any] ) -> Dict: '''simple docstring''' _a : Dict =BeitModelTester(self ) _a : List[str] =ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , has_text_modality=SCREAMING_SNAKE_CASE , hidden_size=3_7 ) def __UpperCAmelCase ( self :str ) -> Optional[int]: '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason="""BEiT does not use inputs_embeds""" ) def __UpperCAmelCase ( self :Any ) -> Tuple: '''simple docstring''' pass @require_torch_multi_gpu @unittest.skip(reason="""BEiT has some layers using `add_module` which doesn't work well with `nn.DataParallel`""" ) def __UpperCAmelCase ( self :Union[str, Any] ) -> Dict: '''simple docstring''' pass def __UpperCAmelCase ( self :Any ) -> Tuple: '''simple docstring''' _a , _a : Union[str, Any] =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a : Union[str, Any] =model_class(SCREAMING_SNAKE_CASE ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) _a : List[Any] =model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE , nn.Linear ) ) def __UpperCAmelCase ( self :str ) -> Optional[int]: '''simple docstring''' _a , _a : Union[str, Any] =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a : Optional[Any] =model_class(SCREAMING_SNAKE_CASE ) _a : int =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _a : Dict =[*signature.parameters.keys()] _a : str =["""pixel_values"""] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Dict ) -> Optional[int]: '''simple docstring''' _a : Tuple =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :List[Any] ) -> int: '''simple docstring''' _a : Optional[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Dict ) -> Optional[int]: '''simple docstring''' _a : List[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Union[str, Any] ) -> Any: '''simple docstring''' _a : List[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :str ) -> Optional[Any]: '''simple docstring''' if not self.model_tester.is_training: return _a , _a : int =self.model_tester.prepare_config_and_inputs_for_common() _a : Optional[Any] =True for model_class in self.all_model_classes: # we don't test BeitForMaskedImageModeling if model_class in [*get_values(SCREAMING_SNAKE_CASE ), BeitForMaskedImageModeling]: continue _a : Tuple =model_class(SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.train() _a : Optional[int] =self._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , return_labels=SCREAMING_SNAKE_CASE ) _a : List[Any] =model(**SCREAMING_SNAKE_CASE ).loss loss.backward() def __UpperCAmelCase ( self :int ) -> Any: '''simple docstring''' _a , _a : Optional[int] =self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return _a : List[str] =False _a : int =True for model_class in self.all_model_classes: # we don't test BeitForMaskedImageModeling if ( model_class in [*get_values(SCREAMING_SNAKE_CASE ), BeitForMaskedImageModeling] or not model_class.supports_gradient_checkpointing ): continue _a : Any =model_class(SCREAMING_SNAKE_CASE ) model.gradient_checkpointing_enable() model.to(SCREAMING_SNAKE_CASE ) model.train() _a : Tuple =self._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , return_labels=SCREAMING_SNAKE_CASE ) _a : Dict =model(**SCREAMING_SNAKE_CASE ).loss loss.backward() def __UpperCAmelCase ( self :List[str] ) -> str: '''simple docstring''' _a , _a : Any =self.model_tester.prepare_config_and_inputs_for_common() _a : Union[str, Any] =_config_zero_init(SCREAMING_SNAKE_CASE ) for model_class in self.all_model_classes: _a : Dict =model_class(config=SCREAMING_SNAKE_CASE ) for name, param in model.named_parameters(): # we skip lambda parameters as these require special initial values # determined by config.layer_scale_init_value if "lambda" in name: continue if param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=f"Parameter {name} of model {model_class} seems not properly initialized" , ) @slow def __UpperCAmelCase ( self :str ) -> str: '''simple docstring''' for model_name in BEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _a : Union[str, Any] =BeitModel.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) def SCREAMING_SNAKE_CASE_ ( ) -> Union[str, Any]: _a : List[Any] =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class A__ ( unittest.TestCase ): @cached_property def __UpperCAmelCase ( self :Dict ) -> str: '''simple docstring''' return BeitImageProcessor.from_pretrained("""microsoft/beit-base-patch16-224""" ) if is_vision_available() else None @slow def __UpperCAmelCase ( self :Union[str, Any] ) -> str: '''simple docstring''' _a : Union[str, Any] =BeitForMaskedImageModeling.from_pretrained("""microsoft/beit-base-patch16-224-pt22k""" ).to(SCREAMING_SNAKE_CASE ) _a : Tuple =self.default_image_processor _a : Union[str, Any] =prepare_img() _a : Tuple =image_processor(images=SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).pixel_values.to(SCREAMING_SNAKE_CASE ) # prepare bool_masked_pos _a : int =torch.ones((1, 1_9_6) , dtype=torch.bool ).to(SCREAMING_SNAKE_CASE ) # forward pass with torch.no_grad(): _a : Any =model(pixel_values=SCREAMING_SNAKE_CASE , bool_masked_pos=SCREAMING_SNAKE_CASE ) _a : int =outputs.logits # verify the logits _a : Any =torch.Size((1, 1_9_6, 8_1_9_2) ) self.assertEqual(logits.shape , SCREAMING_SNAKE_CASE ) _a : Optional[int] =torch.tensor( [[-3.2_437, 0.5_072, -13.9_174], [-3.2_456, 0.4_948, -13.9_401], [-3.2_033, 0.5_121, -13.8_550]] ).to(SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(logits[bool_masked_pos][:3, :3] , SCREAMING_SNAKE_CASE , atol=1e-2 ) ) @slow def __UpperCAmelCase ( self :int ) -> Tuple: '''simple docstring''' _a : List[str] =BeitForImageClassification.from_pretrained("""microsoft/beit-base-patch16-224""" ).to(SCREAMING_SNAKE_CASE ) _a : Dict =self.default_image_processor _a : Tuple =prepare_img() _a : str =image_processor(images=SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).to(SCREAMING_SNAKE_CASE ) # forward pass with torch.no_grad(): _a : Union[str, Any] =model(**SCREAMING_SNAKE_CASE ) _a : int =outputs.logits # verify the logits _a : Optional[Any] =torch.Size((1, 1_0_0_0) ) self.assertEqual(logits.shape , SCREAMING_SNAKE_CASE ) _a : Optional[int] =torch.tensor([-1.2_385, -1.0_987, -1.0_108] ).to(SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(logits[0, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) ) _a : List[Any] =2_8_1 self.assertEqual(logits.argmax(-1 ).item() , SCREAMING_SNAKE_CASE ) @slow def __UpperCAmelCase ( self :Any ) -> Any: '''simple docstring''' _a : int =BeitForImageClassification.from_pretrained("""microsoft/beit-large-patch16-224-pt22k-ft22k""" ).to( SCREAMING_SNAKE_CASE ) _a : List[Any] =self.default_image_processor _a : Optional[Any] =prepare_img() _a : Optional[Any] =image_processor(images=SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).to(SCREAMING_SNAKE_CASE ) # forward pass with torch.no_grad(): _a : Any =model(**SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =outputs.logits # verify the logits _a : Tuple =torch.Size((1, 2_1_8_4_1) ) self.assertEqual(logits.shape , SCREAMING_SNAKE_CASE ) _a : List[str] =torch.tensor([1.6_881, -0.2_787, 0.5_901] ).to(SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(logits[0, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) ) _a : List[str] =2_3_9_6 self.assertEqual(logits.argmax(-1 ).item() , SCREAMING_SNAKE_CASE ) @slow def __UpperCAmelCase ( self :int ) -> Any: '''simple docstring''' _a : Union[str, Any] =BeitForSemanticSegmentation.from_pretrained("""microsoft/beit-base-finetuned-ade-640-640""" ) _a : List[Any] =model.to(SCREAMING_SNAKE_CASE ) _a : Tuple =BeitImageProcessor(do_resize=SCREAMING_SNAKE_CASE , size=6_4_0 , do_center_crop=SCREAMING_SNAKE_CASE ) _a : Tuple =load_dataset("""hf-internal-testing/fixtures_ade20k""" , split="""test""" ) _a : Tuple =Image.open(ds[0]["""file"""] ) _a : List[str] =image_processor(images=SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).to(SCREAMING_SNAKE_CASE ) # forward pass with torch.no_grad(): _a : Any =model(**SCREAMING_SNAKE_CASE ) _a : Tuple =outputs.logits # verify the logits _a : List[str] =torch.Size((1, 1_5_0, 1_6_0, 1_6_0) ) self.assertEqual(logits.shape , SCREAMING_SNAKE_CASE ) _a : Optional[Any] =version.parse(PIL.__version__ ) < version.parse("""9.0.0""" ) if is_pillow_less_than_a: _a : Dict =torch.tensor( [ [[-4.9_225, -2.3_954, -3.0_522], [-2.8_822, -1.0_046, -1.7_561], [-2.9_549, -1.3_228, -2.1_347]], [[-5.8_168, -3.4_129, -4.0_778], [-3.8_651, -2.2_214, -3.0_277], [-3.8_356, -2.4_643, -3.3_535]], [[-0.0_078, 3.9_952, 4.0_754], [2.9_856, 4.6_944, 5.0_035], [3.2_413, 4.7_813, 4.9_969]], ] , device=SCREAMING_SNAKE_CASE , ) else: _a : List[str] =torch.tensor( [ [[-4.8_960, -2.3_688, -3.0_355], [-2.8_478, -0.9_836, -1.7_418], [-2.9_449, -1.3_332, -2.1_456]], [[-5.8_081, -3.4_124, -4.1_006], [-3.8_561, -2.2_081, -3.0_323], [-3.8_365, -2.4_601, -3.3_669]], [[-0.0_309, 3.9_868, 4.0_540], [2.9_640, 4.6_877, 4.9_976], [3.2_081, 4.7_690, 4.9_942]], ] , device=SCREAMING_SNAKE_CASE , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) ) @slow def __UpperCAmelCase ( self :int ) -> List[Any]: '''simple docstring''' _a : Optional[int] =BeitForSemanticSegmentation.from_pretrained("""microsoft/beit-base-finetuned-ade-640-640""" ) _a : List[str] =model.to(SCREAMING_SNAKE_CASE ) _a : List[str] =BeitImageProcessor(do_resize=SCREAMING_SNAKE_CASE , size=6_4_0 , do_center_crop=SCREAMING_SNAKE_CASE ) _a : List[str] =load_dataset("""hf-internal-testing/fixtures_ade20k""" , split="""test""" ) _a : Tuple =Image.open(ds[0]["""file"""] ) _a : Tuple =image_processor(images=SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).to(SCREAMING_SNAKE_CASE ) # forward pass with torch.no_grad(): _a : Dict =model(**SCREAMING_SNAKE_CASE ) _a : Dict =outputs.logits.detach().cpu() _a : Optional[Any] =image_processor.post_process_semantic_segmentation(outputs=SCREAMING_SNAKE_CASE , target_sizes=[(5_0_0, 3_0_0)] ) _a : List[str] =torch.Size((5_0_0, 3_0_0) ) self.assertEqual(segmentation[0].shape , SCREAMING_SNAKE_CASE ) _a : List[str] =image_processor.post_process_semantic_segmentation(outputs=SCREAMING_SNAKE_CASE ) _a : Any =torch.Size((1_6_0, 1_6_0) ) self.assertEqual(segmentation[0].shape , SCREAMING_SNAKE_CASE )
276
'''simple docstring''' class A__ : def __init__( self :List[Any] ) -> None: '''simple docstring''' _a : dict[str, TrieNode] ={} # Mapping from char to TrieNode _a : List[str] =False def __UpperCAmelCase ( self :Tuple , SCREAMING_SNAKE_CASE :list[str] ) -> None: '''simple docstring''' for word in words: self.insert(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :str ) -> None: '''simple docstring''' _a : str =self for char in word: if char not in curr.nodes: _a : Dict =TrieNode() _a : List[Any] =curr.nodes[char] _a : int =True def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :str ) -> bool: '''simple docstring''' _a : int =self for char in word: if char not in curr.nodes: return False _a : List[Any] =curr.nodes[char] return curr.is_leaf def __UpperCAmelCase ( self :Dict , SCREAMING_SNAKE_CASE :str ) -> None: '''simple docstring''' def _delete(SCREAMING_SNAKE_CASE :TrieNode , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :int ) -> bool: if index == len(SCREAMING_SNAKE_CASE ): # If word does not exist if not curr.is_leaf: return False _a : Any =False return len(curr.nodes ) == 0 _a : int =word[index] _a : int =curr.nodes.get(SCREAMING_SNAKE_CASE ) # If char not in current trie node if not char_node: return False # Flag to check if node can be deleted _a : List[Any] =_delete(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , index + 1 ) if delete_curr: del curr.nodes[char] return len(curr.nodes ) == 0 return delete_curr _delete(self , SCREAMING_SNAKE_CASE , 0 ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : TrieNode ,_UpperCAmelCase : str ) -> None: if node.is_leaf: print(_UpperCAmelCase ,end=""" """ ) for key, value in node.nodes.items(): print_words(_UpperCAmelCase ,word + key ) def SCREAMING_SNAKE_CASE_ ( ) -> bool: _a : List[str] ="""banana bananas bandana band apple all beast""".split() _a : List[Any] =TrieNode() root.insert_many(_UpperCAmelCase ) # print_words(root, "") assert all(root.find(_UpperCAmelCase ) for word in words ) assert root.find("""banana""" ) assert not root.find("""bandanas""" ) assert not root.find("""apps""" ) assert root.find("""apple""" ) assert root.find("""all""" ) root.delete("""all""" ) assert not root.find("""all""" ) root.delete("""banana""" ) assert not root.find("""banana""" ) assert root.find("""bananas""" ) return True def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : bool ) -> None: print(str(_UpperCAmelCase ) ,"""works!""" if passes else """doesn't work :(""" ) def SCREAMING_SNAKE_CASE_ ( ) -> None: assert test_trie() def SCREAMING_SNAKE_CASE_ ( ) -> None: print_results("""Testing trie functionality""" ,test_trie() ) if __name__ == "__main__": main()
276
1
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A__: Tuple = logging.get_logger(__name__) A__: int = { '''roberta-base''': '''https://huggingface.co/roberta-base/resolve/main/config.json''', '''roberta-large''': '''https://huggingface.co/roberta-large/resolve/main/config.json''', '''roberta-large-mnli''': '''https://huggingface.co/roberta-large-mnli/resolve/main/config.json''', '''distilroberta-base''': '''https://huggingface.co/distilroberta-base/resolve/main/config.json''', '''roberta-base-openai-detector''': '''https://huggingface.co/roberta-base-openai-detector/resolve/main/config.json''', '''roberta-large-openai-detector''': '''https://huggingface.co/roberta-large-openai-detector/resolve/main/config.json''', } class A__ ( UpperCAmelCase__ ): __UpperCamelCase : Tuple = "roberta" def __init__( self :List[Any] , SCREAMING_SNAKE_CASE :List[str]=5_0_2_6_5 , SCREAMING_SNAKE_CASE :Optional[int]=7_6_8 , SCREAMING_SNAKE_CASE :List[str]=1_2 , SCREAMING_SNAKE_CASE :Dict=1_2 , SCREAMING_SNAKE_CASE :List[Any]=3_0_7_2 , SCREAMING_SNAKE_CASE :List[str]="gelu" , SCREAMING_SNAKE_CASE :Tuple=0.1 , SCREAMING_SNAKE_CASE :List[Any]=0.1 , SCREAMING_SNAKE_CASE :str=5_1_2 , SCREAMING_SNAKE_CASE :List[Any]=2 , SCREAMING_SNAKE_CASE :List[Any]=0.02 , SCREAMING_SNAKE_CASE :Optional[int]=1e-12 , SCREAMING_SNAKE_CASE :Optional[Any]=1 , SCREAMING_SNAKE_CASE :str=0 , SCREAMING_SNAKE_CASE :Dict=2 , SCREAMING_SNAKE_CASE :Dict="absolute" , SCREAMING_SNAKE_CASE :Tuple=True , SCREAMING_SNAKE_CASE :Any=None , **SCREAMING_SNAKE_CASE :List[str] , ) -> Union[str, Any]: '''simple docstring''' super().__init__(pad_token_id=SCREAMING_SNAKE_CASE , bos_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) _a : List[str] =vocab_size _a : List[Any] =hidden_size _a : int =num_hidden_layers _a : Optional[int] =num_attention_heads _a : Optional[Any] =hidden_act _a : Union[str, Any] =intermediate_size _a : Optional[Any] =hidden_dropout_prob _a : str =attention_probs_dropout_prob _a : List[Any] =max_position_embeddings _a : List[str] =type_vocab_size _a : Optional[Any] =initializer_range _a : List[Any] =layer_norm_eps _a : Tuple =position_embedding_type _a : str =use_cache _a : Any =classifier_dropout class A__ ( UpperCAmelCase__ ): @property def __UpperCAmelCase ( self :Tuple ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task == "multiple-choice": _a : str ={0: """batch""", 1: """choice""", 2: """sequence"""} else: _a : Optional[int] ={0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ] )
276
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available A__: str = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Tuple = ['''GPTSw3Tokenizer'''] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_swa import GPTSwaTokenizer else: import sys A__: str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
276
1
'''simple docstring''' import sys from collections import defaultdict class A__ : def __init__( self :Optional[Any] ) -> List[str]: '''simple docstring''' _a : List[Any] =[] def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :List[Any] ) -> Union[str, Any]: '''simple docstring''' return self.node_position[vertex] def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :str ) -> str: '''simple docstring''' _a : Dict =pos def __UpperCAmelCase ( self :Any , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :List[Any] , SCREAMING_SNAKE_CASE :Optional[int] ) -> Optional[int]: '''simple docstring''' if start > size // 2 - 1: return else: if 2 * start + 2 >= size: _a : Union[str, Any] =2 * start + 1 else: if heap[2 * start + 1] < heap[2 * start + 2]: _a : List[Any] =2 * start + 1 else: _a : List[str] =2 * start + 2 if heap[smallest_child] < heap[start]: _a , _a : Tuple =heap[smallest_child], positions[smallest_child] _a , _a : Optional[Any] =( heap[start], positions[start], ) _a , _a : str =temp, tempa _a : int =self.get_position(positions[smallest_child] ) self.set_position( positions[smallest_child] , self.get_position(positions[start] ) ) self.set_position(positions[start] , SCREAMING_SNAKE_CASE ) self.top_to_bottom(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :List[Any] , SCREAMING_SNAKE_CASE :List[Any] , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :int ) -> Dict: '''simple docstring''' _a : Optional[int] =position[index] while index != 0: _a : Optional[int] =int((index - 2) / 2 ) if index % 2 == 0 else int((index - 1) / 2 ) if val < heap[parent]: _a : int =heap[parent] _a : Optional[int] =position[parent] self.set_position(position[parent] , SCREAMING_SNAKE_CASE ) else: _a : Optional[Any] =val _a : Union[str, Any] =temp self.set_position(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) break _a : int =parent else: _a : Dict =val _a : List[Any] =temp self.set_position(SCREAMING_SNAKE_CASE , 0 ) def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :List[Any] ) -> List[str]: '''simple docstring''' _a : Dict =len(SCREAMING_SNAKE_CASE ) // 2 - 1 for i in range(SCREAMING_SNAKE_CASE , -1 , -1 ): self.top_to_bottom(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , len(SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :str , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Optional[int] ) -> Optional[Any]: '''simple docstring''' _a : str =positions[0] _a : List[Any] =sys.maxsize self.top_to_bottom(SCREAMING_SNAKE_CASE , 0 , len(SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE ) return temp def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Union[str, Any] ) -> List[str]: _a : str =Heap() _a : Any =[0] * len(_UpperCAmelCase ) _a : Tuple =[-1] * len(_UpperCAmelCase ) # Neighboring Tree Vertex of selected vertex # Minimum Distance of explored vertex with neighboring vertex of partial tree # formed in graph _a : List[str] =[] # Heap of Distance of vertices from their neighboring vertex _a : Optional[int] =[] for vertex in range(len(_UpperCAmelCase ) ): distance_tv.append(sys.maxsize ) positions.append(_UpperCAmelCase ) heap.node_position.append(_UpperCAmelCase ) _a : Optional[int] =[] _a : Optional[Any] =1 _a : List[str] =sys.maxsize for neighbor, distance in adjacency_list[0]: _a : List[Any] =0 _a : Optional[int] =distance heap.heapify(_UpperCAmelCase ,_UpperCAmelCase ) for _ in range(1 ,len(_UpperCAmelCase ) ): _a : Tuple =heap.delete_minimum(_UpperCAmelCase ,_UpperCAmelCase ) if visited[vertex] == 0: tree_edges.append((nbr_tv[vertex], vertex) ) _a : Optional[int] =1 for neighbor, distance in adjacency_list[vertex]: if ( visited[neighbor] == 0 and distance < distance_tv[heap.get_position(_UpperCAmelCase )] ): _a : Union[str, Any] =distance heap.bottom_to_top( _UpperCAmelCase ,heap.get_position(_UpperCAmelCase ) ,_UpperCAmelCase ,_UpperCAmelCase ) _a : List[str] =vertex return tree_edges if __name__ == "__main__": # pragma: no cover # < --------- Prims Algorithm --------- > A__: List[str] = int(input('''Enter number of edges: ''').strip()) A__: List[Any] = defaultdict(list) for _ in range(edges_number): A__: Union[str, Any] = [int(x) for x in input().strip().split()] adjacency_list[edge[0]].append([edge[1], edge[2]]) adjacency_list[edge[1]].append([edge[0], edge[2]]) print(prisms_algorithm(adjacency_list))
276
'''simple docstring''' import importlib.metadata import warnings from copy import deepcopy from packaging import version from ..utils import logging from .import_utils import is_accelerate_available, is_bitsandbytes_available if is_bitsandbytes_available(): import bitsandbytes as bnb import torch import torch.nn as nn from ..pytorch_utils import ConvaD if is_accelerate_available(): from accelerate import init_empty_weights from accelerate.utils import find_tied_parameters A__: str = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[Any] ,_UpperCAmelCase : List[str] ,_UpperCAmelCase : int ,_UpperCAmelCase : int=None ,_UpperCAmelCase : Optional[Any]=None ) -> Optional[Any]: # Recurse if needed if "." in tensor_name: _a : Union[str, Any] =tensor_name.split(""".""" ) for split in splits[:-1]: _a : Optional[Any] =getattr(_UpperCAmelCase ,_UpperCAmelCase ) if new_module is None: raise ValueError(F"{module} has no attribute {split}." ) _a : Optional[int] =new_module _a : Optional[int] =splits[-1] if tensor_name not in module._parameters and tensor_name not in module._buffers: raise ValueError(F"{module} does not have a parameter or a buffer named {tensor_name}." ) _a : Optional[Any] =tensor_name in module._buffers _a : str =getattr(_UpperCAmelCase ,_UpperCAmelCase ) if old_value.device == torch.device("""meta""" ) and device not in ["meta", torch.device("""meta""" )] and value is None: raise ValueError(F"{tensor_name} is on the meta device, we need a `value` to put in on {device}." ) _a : int =False _a : Tuple =False if is_buffer or not is_bitsandbytes_available(): _a : str =False _a : Optional[Any] =False else: _a : int =hasattr(bnb.nn ,"""Params4bit""" ) and isinstance(module._parameters[tensor_name] ,bnb.nn.Paramsabit ) _a : int =isinstance(module._parameters[tensor_name] ,bnb.nn.IntaParams ) if is_abit or is_abit: _a : Any =module._parameters[tensor_name] if param.device.type != "cuda": if value is None: _a : int =old_value.to(_UpperCAmelCase ) elif isinstance(_UpperCAmelCase ,torch.Tensor ): _a : str =value.to("""cpu""" ) if value.dtype == torch.inta: _a : int =version.parse(importlib.metadata.version("""bitsandbytes""" ) ) > version.parse( """0.37.2""" ) if not is_abit_serializable: raise ValueError( """Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. """ """Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`.""" ) else: _a : Dict =torch.tensor(_UpperCAmelCase ,device="""cpu""" ) # Support models using `Conv1D` in place of `nn.Linear` (e.g. gpt2) by transposing the weight matrix prior to quantization. # Since weights are saved in the correct "orientation", we skip transposing when loading. if issubclass(module.source_cls ,_UpperCAmelCase ) and fpaa_statistics is None: _a : int =new_value.T _a : Any =old_value.__dict__ if is_abit: _a : Any =bnb.nn.IntaParams(_UpperCAmelCase ,requires_grad=_UpperCAmelCase ,**_UpperCAmelCase ).to(_UpperCAmelCase ) elif is_abit: _a : Union[str, Any] =bnb.nn.Paramsabit(_UpperCAmelCase ,requires_grad=_UpperCAmelCase ,**_UpperCAmelCase ).to(_UpperCAmelCase ) _a : List[Any] =new_value if fpaa_statistics is not None: setattr(module.weight ,"""SCB""" ,fpaa_statistics.to(_UpperCAmelCase ) ) else: if value is None: _a : str =old_value.to(_UpperCAmelCase ) elif isinstance(_UpperCAmelCase ,torch.Tensor ): _a : Any =value.to(_UpperCAmelCase ) else: _a : str =torch.tensor(_UpperCAmelCase ,device=_UpperCAmelCase ) if is_buffer: _a : Optional[int] =new_value else: _a : Optional[Any] =nn.Parameter(_UpperCAmelCase ,requires_grad=old_value.requires_grad ) _a : Tuple =new_value def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : Union[str, Any]=None ,_UpperCAmelCase : List[Any]=None ,_UpperCAmelCase : str=None ,_UpperCAmelCase : Union[str, Any]=False ) -> Dict: for name, module in model.named_children(): if current_key_name is None: _a : Optional[int] =[] current_key_name.append(_UpperCAmelCase ) if (isinstance(_UpperCAmelCase ,nn.Linear ) or isinstance(_UpperCAmelCase ,_UpperCAmelCase )) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` if not any(key in """.""".join(_UpperCAmelCase ) for key in modules_to_not_convert ): with init_empty_weights(): if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): _a , _a : int =module.weight.shape else: _a : List[str] =module.in_features _a : Tuple =module.out_features if quantization_config.quantization_method() == "llm_int8": _a : Optional[Any] =bnb.nn.LinearabitLt( _UpperCAmelCase ,_UpperCAmelCase ,module.bias is not None ,has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight ,threshold=quantization_config.llm_inta_threshold ,) _a : Optional[Any] =True else: if ( quantization_config.llm_inta_skip_modules is not None and name in quantization_config.llm_inta_skip_modules ): pass else: _a : Dict =bnb.nn.Linearabit( _UpperCAmelCase ,_UpperCAmelCase ,module.bias is not None ,quantization_config.bnb_abit_compute_dtype ,compress_statistics=quantization_config.bnb_abit_use_double_quant ,quant_type=quantization_config.bnb_abit_quant_type ,) _a : List[Any] =True # Store the module class in case we need to transpose the weight later _a : int =type(_UpperCAmelCase ) # Force requires grad to False to avoid unexpected errors model._modules[name].requires_grad_(_UpperCAmelCase ) if len(list(module.children() ) ) > 0: _a , _a : List[Any] =_replace_with_bnb_linear( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,has_been_replaced=_UpperCAmelCase ,) # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : int=None ,_UpperCAmelCase : Union[str, Any]=None ,_UpperCAmelCase : Any=None ) -> Tuple: _a : Dict =["""lm_head"""] if modules_to_not_convert is None else modules_to_not_convert _a , _a : List[Any] =_replace_with_bnb_linear( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) if not has_been_replaced: logger.warning( """You are loading your model in 8bit or 4bit but no linear modules were found in your model.""" """ Please double check your model architecture, or submit an issue on github if you think this is""" """ a bug.""" ) return model def SCREAMING_SNAKE_CASE_ ( *_UpperCAmelCase : Any ,**_UpperCAmelCase : Any ) -> str: warnings.warn( """`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead""" ,_UpperCAmelCase ,) return replace_with_bnb_linear(*_UpperCAmelCase ,**_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( *_UpperCAmelCase : str ,**_UpperCAmelCase : Optional[int] ) -> Optional[int]: warnings.warn( """`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead""" ,_UpperCAmelCase ,) return set_module_quantized_tensor_to_device(*_UpperCAmelCase ,**_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ) -> Union[str, Any]: _a : Any =deepcopy(_UpperCAmelCase ) # this has 0 cost since it is done inside `init_empty_weights` context manager` tied_model.tie_weights() _a : List[Any] =find_tied_parameters(_UpperCAmelCase ) # For compatibility with Accelerate < 0.18 if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): _a : str =sum(list(tied_params.values() ) ,[] ) + list(tied_params.keys() ) else: _a : Optional[int] =sum(_UpperCAmelCase ,[] ) _a : List[Any] =len(_UpperCAmelCase ) > 0 # Check if it is a base model _a : Tuple =not hasattr(_UpperCAmelCase ,model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head _a : List[Any] =list(model.named_children() ) _a : Dict =[list_modules[-1][0]] # add last module together with tied weights _a : List[str] =set(_UpperCAmelCase ) - set(_UpperCAmelCase ) _a : str =list(set(_UpperCAmelCase ) ) + list(_UpperCAmelCase ) # remove ".weight" from the keys _a : List[Any] =[""".weight""", """.bias"""] _a : Any =[] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: _a : Any =name.replace(_UpperCAmelCase ,"""""" ) filtered_module_names.append(_UpperCAmelCase ) return filtered_module_names
276
1
'''simple docstring''' from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A__: str = { '''configuration_informer''': [ '''INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''InformerConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: List[str] = [ '''INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''InformerForPrediction''', '''InformerModel''', '''InformerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_informer import INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, InformerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_informer import ( INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, InformerForPrediction, InformerModel, InformerPreTrainedModel, ) else: import sys A__: Any = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
276
'''simple docstring''' import logging import os from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union from filelock import FileLock from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available A__: int = logging.getLogger(__name__) @dataclass class A__ : __UpperCamelCase : str __UpperCamelCase : List[str] __UpperCamelCase : Optional[List[str]] @dataclass class A__ : __UpperCamelCase : List[int] __UpperCamelCase : List[int] __UpperCamelCase : Optional[List[int]] = None __UpperCamelCase : Optional[List[int]] = None class A__ ( UpperCAmelCase__ ): __UpperCamelCase : str = "train" __UpperCamelCase : Tuple = "dev" __UpperCamelCase : str = "test" class A__ : @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :Union[Split, str] ) -> List[InputExample]: '''simple docstring''' raise NotImplementedError @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :str ) -> List[str]: '''simple docstring''' raise NotImplementedError @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :List[InputExample] , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :PreTrainedTokenizer , SCREAMING_SNAKE_CASE :str=False , SCREAMING_SNAKE_CASE :Optional[Any]="[CLS]" , SCREAMING_SNAKE_CASE :Optional[int]=1 , SCREAMING_SNAKE_CASE :Any="[SEP]" , SCREAMING_SNAKE_CASE :List[Any]=False , SCREAMING_SNAKE_CASE :Union[str, Any]=False , SCREAMING_SNAKE_CASE :List[str]=0 , SCREAMING_SNAKE_CASE :str=0 , SCREAMING_SNAKE_CASE :Dict=-1_0_0 , SCREAMING_SNAKE_CASE :Optional[int]=0 , SCREAMING_SNAKE_CASE :Tuple=True , ) -> List[InputFeatures]: '''simple docstring''' _a : str ={label: i for i, label in enumerate(SCREAMING_SNAKE_CASE )} _a : Tuple =[] for ex_index, example in enumerate(SCREAMING_SNAKE_CASE ): if ex_index % 1_0_0_0_0 == 0: logger.info("""Writing example %d of %d""" , SCREAMING_SNAKE_CASE , len(SCREAMING_SNAKE_CASE ) ) _a : Optional[Any] =[] _a : List[Any] =[] for word, label in zip(example.words , example.labels ): _a : Optional[int] =tokenizer.tokenize(SCREAMING_SNAKE_CASE ) # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space. if len(SCREAMING_SNAKE_CASE ) > 0: tokens.extend(SCREAMING_SNAKE_CASE ) # Use the real label id for the first token of the word, and padding ids for the remaining tokens label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(SCREAMING_SNAKE_CASE ) - 1) ) # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa. _a : Optional[int] =tokenizer.num_special_tokens_to_add() if len(SCREAMING_SNAKE_CASE ) > max_seq_length - special_tokens_count: _a : List[Any] =tokens[: (max_seq_length - special_tokens_count)] _a : Tuple =label_ids[: (max_seq_length - special_tokens_count)] # The convention in BERT is: # (a) For sequence pairs: # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP] # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1 # (b) For single sequences: # tokens: [CLS] the dog is hairy . [SEP] # type_ids: 0 0 0 0 0 0 0 # # Where "type_ids" are used to indicate whether this is the first # sequence or the second sequence. The embedding vectors for `type=0` and # `type=1` were learned during pre-training and are added to the wordpiece # embedding vector (and position vector). This is not *strictly* necessary # since the [SEP] token unambiguously separates the sequences, but it makes # it easier for the model to learn the concept of sequences. # # For classification tasks, the first vector (corresponding to [CLS]) is # used as the "sentence vector". Note that this only makes sense because # the entire model is fine-tuned. tokens += [sep_token] label_ids += [pad_token_label_id] if sep_token_extra: # roberta uses an extra separator b/w pairs of sentences tokens += [sep_token] label_ids += [pad_token_label_id] _a : Dict =[sequence_a_segment_id] * len(SCREAMING_SNAKE_CASE ) if cls_token_at_end: tokens += [cls_token] label_ids += [pad_token_label_id] segment_ids += [cls_token_segment_id] else: _a : Any =[cls_token] + tokens _a : Dict =[pad_token_label_id] + label_ids _a : Union[str, Any] =[cls_token_segment_id] + segment_ids _a : List[str] =tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE ) # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. _a : Optional[int] =[1 if mask_padding_with_zero else 0] * len(SCREAMING_SNAKE_CASE ) # Zero-pad up to the sequence length. _a : Union[str, Any] =max_seq_length - len(SCREAMING_SNAKE_CASE ) if pad_on_left: _a : Optional[Any] =([pad_token] * padding_length) + input_ids _a : Optional[int] =([0 if mask_padding_with_zero else 1] * padding_length) + input_mask _a : Union[str, Any] =([pad_token_segment_id] * padding_length) + segment_ids _a : Dict =([pad_token_label_id] * padding_length) + label_ids else: input_ids += [pad_token] * padding_length input_mask += [0 if mask_padding_with_zero else 1] * padding_length segment_ids += [pad_token_segment_id] * padding_length label_ids += [pad_token_label_id] * padding_length assert len(SCREAMING_SNAKE_CASE ) == max_seq_length assert len(SCREAMING_SNAKE_CASE ) == max_seq_length assert len(SCREAMING_SNAKE_CASE ) == max_seq_length assert len(SCREAMING_SNAKE_CASE ) == max_seq_length if ex_index < 5: logger.info("""*** Example ***""" ) logger.info("""guid: %s""" , example.guid ) logger.info("""tokens: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in tokens] ) ) logger.info("""input_ids: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in input_ids] ) ) logger.info("""input_mask: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in input_mask] ) ) logger.info("""segment_ids: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in segment_ids] ) ) logger.info("""label_ids: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in label_ids] ) ) if "token_type_ids" not in tokenizer.model_input_names: _a : Tuple =None features.append( InputFeatures( input_ids=SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , token_type_ids=SCREAMING_SNAKE_CASE , label_ids=SCREAMING_SNAKE_CASE ) ) return features if is_torch_available(): import torch from torch import nn from torch.utils.data import Dataset class A__ ( UpperCAmelCase__ ): __UpperCamelCase : List[InputFeatures] __UpperCamelCase : int = nn.CrossEntropyLoss().ignore_index def __init__( self :Dict , SCREAMING_SNAKE_CASE :TokenClassificationTask , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :PreTrainedTokenizer , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Optional[int] = None , SCREAMING_SNAKE_CASE :int=False , SCREAMING_SNAKE_CASE :Split = Split.train , ) -> List[str]: '''simple docstring''' # Load data features from cache or dataset file _a : Optional[Any] =os.path.join( SCREAMING_SNAKE_CASE , """cached_{}_{}_{}""".format(mode.value , tokenizer.__class__.__name__ , str(SCREAMING_SNAKE_CASE ) ) , ) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. _a : List[str] =cached_features_file + """.lock""" with FileLock(SCREAMING_SNAKE_CASE ): if os.path.exists(SCREAMING_SNAKE_CASE ) and not overwrite_cache: logger.info(f"Loading features from cached file {cached_features_file}" ) _a : Any =torch.load(SCREAMING_SNAKE_CASE ) else: logger.info(f"Creating features from dataset file at {data_dir}" ) _a : Any =token_classification_task.read_examples_from_file(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # TODO clean up all this to leverage built-in features of tokenizers _a : List[str] =token_classification_task.convert_examples_to_features( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cls_token_at_end=bool(model_type in ["""xlnet"""] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ["""xlnet"""] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=SCREAMING_SNAKE_CASE , pad_on_left=bool(tokenizer.padding_side == """left""" ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info(f"Saving features into cached file {cached_features_file}" ) torch.save(self.features , SCREAMING_SNAKE_CASE ) def __len__( self :Optional[int] ) -> Union[str, Any]: '''simple docstring''' return len(self.features ) def __getitem__( self :Dict , SCREAMING_SNAKE_CASE :int ) -> InputFeatures: '''simple docstring''' return self.features[i] if is_tf_available(): import tensorflow as tf class A__ : __UpperCamelCase : List[InputFeatures] __UpperCamelCase : int = -100 def __init__( self :str , SCREAMING_SNAKE_CASE :TokenClassificationTask , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :PreTrainedTokenizer , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Optional[int] = None , SCREAMING_SNAKE_CASE :str=False , SCREAMING_SNAKE_CASE :Split = Split.train , ) -> Any: '''simple docstring''' _a : Tuple =token_classification_task.read_examples_from_file(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # TODO clean up all this to leverage built-in features of tokenizers _a : List[Any] =token_classification_task.convert_examples_to_features( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cls_token_at_end=bool(model_type in ["""xlnet"""] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ["""xlnet"""] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=SCREAMING_SNAKE_CASE , pad_on_left=bool(tokenizer.padding_side == """left""" ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) def gen(): for ex in self.features: if ex.token_type_ids is None: yield ( {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label_ids, ) else: yield ( { "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label_ids, ) if "token_type_ids" not in tokenizer.model_input_names: _a : Union[str, Any] =tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE , ({"""input_ids""": tf.intaa, """attention_mask""": tf.intaa}, tf.intaa) , ( {"""input_ids""": tf.TensorShape([None] ), """attention_mask""": tf.TensorShape([None] )}, tf.TensorShape([None] ), ) , ) else: _a : Union[str, Any] =tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE , ({"""input_ids""": tf.intaa, """attention_mask""": tf.intaa, """token_type_ids""": tf.intaa}, tf.intaa) , ( { """input_ids""": tf.TensorShape([None] ), """attention_mask""": tf.TensorShape([None] ), """token_type_ids""": tf.TensorShape([None] ), }, tf.TensorShape([None] ), ) , ) def __UpperCAmelCase ( self :Tuple ) -> Any: '''simple docstring''' _a : List[Any] =self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features ) ) ) return self.dataset def __len__( self :str ) -> Optional[int]: '''simple docstring''' return len(self.features ) def __getitem__( self :int , SCREAMING_SNAKE_CASE :str ) -> InputFeatures: '''simple docstring''' return self.features[i]
276
1
'''simple docstring''' A__: List[Any] = '''0.18.2''' from .configuration_utils import ConfigMixin from .utils import ( OptionalDependencyNotAvailable, is_flax_available, is_inflect_available, is_invisible_watermark_available, is_k_diffusion_available, is_k_diffusion_version, is_librosa_available, is_note_seq_available, is_onnx_available, is_scipy_available, is_torch_available, is_torchsde_available, is_transformers_available, is_transformers_version, is_unidecode_available, logging, ) try: if not is_onnx_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_onnx_objects import * # noqa F403 else: from .pipelines import OnnxRuntimeModel try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_pt_objects import * # noqa F403 else: from .models import ( AutoencoderKL, ControlNetModel, ModelMixin, PriorTransformer, TaFilmDecoder, TransformeraDModel, UNetaDModel, UNetaDConditionModel, UNetaDModel, UNetaDConditionModel, VQModel, ) from .optimization import ( get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, get_scheduler, ) from .pipelines import ( AudioPipelineOutput, ConsistencyModelPipeline, DanceDiffusionPipeline, DDIMPipeline, DDPMPipeline, DiffusionPipeline, DiTPipeline, ImagePipelineOutput, KarrasVePipeline, LDMPipeline, LDMSuperResolutionPipeline, PNDMPipeline, RePaintPipeline, ScoreSdeVePipeline, ) from .schedulers import ( CMStochasticIterativeScheduler, DDIMInverseScheduler, DDIMParallelScheduler, DDIMScheduler, DDPMParallelScheduler, DDPMScheduler, DEISMultistepScheduler, DPMSolverMultistepInverseScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, HeunDiscreteScheduler, IPNDMScheduler, KarrasVeScheduler, KDPMaAncestralDiscreteScheduler, KDPMaDiscreteScheduler, PNDMScheduler, RePaintScheduler, SchedulerMixin, ScoreSdeVeScheduler, UnCLIPScheduler, UniPCMultistepScheduler, VQDiffusionScheduler, ) from .training_utils import EMAModel try: if not (is_torch_available() and is_scipy_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_scipy_objects import * # noqa F403 else: from .schedulers import LMSDiscreteScheduler try: if not (is_torch_available() and is_torchsde_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_torchsde_objects import * # noqa F403 else: from .schedulers import DPMSolverSDEScheduler try: if not (is_torch_available() and is_transformers_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipelines import ( AltDiffusionImgaImgPipeline, AltDiffusionPipeline, AudioLDMPipeline, CycleDiffusionPipeline, IFImgaImgPipeline, IFImgaImgSuperResolutionPipeline, IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, IFPipeline, IFSuperResolutionPipeline, ImageTextPipelineOutput, KandinskyImgaImgPipeline, KandinskyInpaintPipeline, KandinskyPipeline, KandinskyPriorPipeline, KandinskyVaaControlnetImgaImgPipeline, KandinskyVaaControlnetPipeline, KandinskyVaaImgaImgPipeline, KandinskyVaaInpaintPipeline, KandinskyVaaPipeline, KandinskyVaaPriorEmbaEmbPipeline, KandinskyVaaPriorPipeline, LDMTextToImagePipeline, PaintByExamplePipeline, SemanticStableDiffusionPipeline, ShapEImgaImgPipeline, ShapEPipeline, StableDiffusionAttendAndExcitePipeline, StableDiffusionControlNetImgaImgPipeline, StableDiffusionControlNetInpaintPipeline, StableDiffusionControlNetPipeline, StableDiffusionDepthaImgPipeline, StableDiffusionDiffEditPipeline, StableDiffusionImageVariationPipeline, StableDiffusionImgaImgPipeline, StableDiffusionInpaintPipeline, StableDiffusionInpaintPipelineLegacy, StableDiffusionInstructPixaPixPipeline, StableDiffusionLatentUpscalePipeline, StableDiffusionLDMaDPipeline, StableDiffusionModelEditingPipeline, StableDiffusionPanoramaPipeline, StableDiffusionParadigmsPipeline, StableDiffusionPipeline, StableDiffusionPipelineSafe, StableDiffusionPixaPixZeroPipeline, StableDiffusionSAGPipeline, StableDiffusionUpscalePipeline, StableUnCLIPImgaImgPipeline, StableUnCLIPPipeline, TextToVideoSDPipeline, TextToVideoZeroPipeline, UnCLIPImageVariationPipeline, UnCLIPPipeline, UniDiffuserModel, UniDiffuserPipeline, UniDiffuserTextDecoder, VersatileDiffusionDualGuidedPipeline, VersatileDiffusionImageVariationPipeline, VersatileDiffusionPipeline, VersatileDiffusionTextToImagePipeline, VideoToVideoSDPipeline, VQDiffusionPipeline, ) try: if not (is_torch_available() and is_transformers_available() and is_invisible_watermark_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_transformers_and_invisible_watermark_objects import * # noqa F403 else: from .pipelines import StableDiffusionXLImgaImgPipeline, StableDiffusionXLPipeline try: if not (is_torch_available() and is_transformers_available() and is_k_diffusion_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_transformers_and_k_diffusion_objects import * # noqa F403 else: from .pipelines import StableDiffusionKDiffusionPipeline try: if not (is_torch_available() and is_transformers_available() and is_onnx_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_transformers_and_onnx_objects import * # noqa F403 else: from .pipelines import ( OnnxStableDiffusionImgaImgPipeline, OnnxStableDiffusionInpaintPipeline, OnnxStableDiffusionInpaintPipelineLegacy, OnnxStableDiffusionPipeline, OnnxStableDiffusionUpscalePipeline, StableDiffusionOnnxPipeline, ) try: if not (is_torch_available() and is_librosa_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_librosa_objects import * # noqa F403 else: from .pipelines import AudioDiffusionPipeline, Mel try: if not (is_transformers_available() and is_torch_available() and is_note_seq_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_transformers_and_torch_and_note_seq_objects import * # noqa F403 else: from .pipelines import SpectrogramDiffusionPipeline try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_flax_objects import * # noqa F403 else: from .models.controlnet_flax import FlaxControlNetModel from .models.modeling_flax_utils import FlaxModelMixin from .models.unet_ad_condition_flax import FlaxUNetaDConditionModel from .models.vae_flax import FlaxAutoencoderKL from .pipelines import FlaxDiffusionPipeline from .schedulers import ( FlaxDDIMScheduler, FlaxDDPMScheduler, FlaxDPMSolverMultistepScheduler, FlaxKarrasVeScheduler, FlaxLMSDiscreteScheduler, FlaxPNDMScheduler, FlaxSchedulerMixin, FlaxScoreSdeVeScheduler, ) try: if not (is_flax_available() and is_transformers_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_flax_and_transformers_objects import * # noqa F403 else: from .pipelines import ( FlaxStableDiffusionControlNetPipeline, FlaxStableDiffusionImgaImgPipeline, FlaxStableDiffusionInpaintPipeline, FlaxStableDiffusionPipeline, ) try: if not (is_note_seq_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_note_seq_objects import * # noqa F403 else: from .pipelines import MidiProcessor
276
'''simple docstring''' from __future__ import annotations class A__ : def __init__( self :Union[str, Any] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :str ) -> Optional[int]: '''simple docstring''' _a , _a : List[str] =text, pattern _a , _a : Union[str, Any] =len(SCREAMING_SNAKE_CASE ), len(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Optional[int] , SCREAMING_SNAKE_CASE :str ) -> int: '''simple docstring''' for i in range(self.patLen - 1 , -1 , -1 ): if char == self.pattern[i]: return i return -1 def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :int ) -> int: '''simple docstring''' for i in range(self.patLen - 1 , -1 , -1 ): if self.pattern[i] != self.text[current_pos + i]: return current_pos + i return -1 def __UpperCAmelCase ( self :Union[str, Any] ) -> list[int]: '''simple docstring''' # searches pattern in text and returns index positions _a : Union[str, Any] =[] for i in range(self.textLen - self.patLen + 1 ): _a : Any =self.mismatch_in_text(SCREAMING_SNAKE_CASE ) if mismatch_index == -1: positions.append(SCREAMING_SNAKE_CASE ) else: _a : int =self.match_in_pattern(self.text[mismatch_index] ) _a : List[str] =( mismatch_index - match_index ) # shifting index lgtm [py/multiple-definition] return positions A__: Any = '''ABAABA''' A__: int = '''AB''' A__: Optional[int] = BoyerMooreSearch(text, pattern) A__: Optional[Any] = bms.bad_character_heuristic() if len(positions) == 0: print('''No match found''') else: print('''Pattern found in following positions: ''') print(positions)
276
1
'''simple docstring''' import logging import random import ray from transformers import RagConfig, RagRetriever, RagTokenizer from transformers.models.rag.retrieval_rag import CustomHFIndex A__: Dict = logging.getLogger(__name__) class A__ : def __init__( self :int ) -> List[str]: '''simple docstring''' _a : Dict =False def __UpperCAmelCase ( self :str , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Any ) -> Union[str, Any]: '''simple docstring''' if not self.initialized: _a : Optional[Any] =RagRetriever( SCREAMING_SNAKE_CASE , question_encoder_tokenizer=SCREAMING_SNAKE_CASE , generator_tokenizer=SCREAMING_SNAKE_CASE , index=SCREAMING_SNAKE_CASE , init_retrieval=SCREAMING_SNAKE_CASE , ) _a : Optional[Any] =True def __UpperCAmelCase ( self :Union[str, Any] ) -> Union[str, Any]: '''simple docstring''' self.retriever.index.init_index() def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :Optional[int] , SCREAMING_SNAKE_CASE :int ) -> List[Any]: '''simple docstring''' _a , _a : Optional[Any] =self.retriever._main_retrieve(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) return doc_ids, retrieved_doc_embeds class A__ ( UpperCAmelCase__ ): def __init__( self :int , SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Optional[int]=None ) -> str: '''simple docstring''' if index is not None and index.is_initialized() and len(SCREAMING_SNAKE_CASE ) > 0: raise ValueError( """When using Ray for distributed fine-tuning, """ """you'll need to provide the paths instead, """ """as the dataset and the index are loaded """ """separately. More info in examples/rag/use_own_knowledge_dataset.py """ ) super().__init__( SCREAMING_SNAKE_CASE , question_encoder_tokenizer=SCREAMING_SNAKE_CASE , generator_tokenizer=SCREAMING_SNAKE_CASE , index=SCREAMING_SNAKE_CASE , init_retrieval=SCREAMING_SNAKE_CASE , ) _a : int =retrieval_workers if len(self.retrieval_workers ) > 0: ray.get( [ worker.create_rag_retriever.remote(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for worker in self.retrieval_workers ] ) def __UpperCAmelCase ( self :Dict ) -> Optional[int]: '''simple docstring''' logger.info("""initializing retrieval""" ) if len(self.retrieval_workers ) > 0: ray.get([worker.init_retrieval.remote() for worker in self.retrieval_workers] ) else: # Non-distributed training. Load index into this same process. self.index.init_index() def __UpperCAmelCase ( self :Optional[int] , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :str ) -> List[str]: '''simple docstring''' if len(self.retrieval_workers ) > 0: # Select a random retrieval actor. _a : List[str] =self.retrieval_workers[random.randint(0 , len(self.retrieval_workers ) - 1 )] _a , _a : Dict =ray.get(random_worker.retrieve.remote(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) else: _a , _a : Union[str, Any] =self._main_retrieve(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(SCREAMING_SNAKE_CASE ) @classmethod def __UpperCAmelCase ( cls :Optional[int] , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :Tuple=None , **SCREAMING_SNAKE_CASE :Any ) -> List[str]: '''simple docstring''' return super(SCREAMING_SNAKE_CASE , cls ).get_tokenizers(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) @classmethod def __UpperCAmelCase ( cls :Any , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :str=None , **SCREAMING_SNAKE_CASE :List[Any] ) -> Dict: '''simple docstring''' _a : int =kwargs.pop("""config""" , SCREAMING_SNAKE_CASE ) or RagConfig.from_pretrained(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) _a : Optional[int] =RagTokenizer.from_pretrained(SCREAMING_SNAKE_CASE , config=SCREAMING_SNAKE_CASE ) _a : Dict =rag_tokenizer.question_encoder _a : Tuple =rag_tokenizer.generator if indexed_dataset is not None: _a : Dict ="""custom""" _a : List[str] =CustomHFIndex(config.retrieval_vector_size , SCREAMING_SNAKE_CASE ) else: _a : Any =cls._build_index(SCREAMING_SNAKE_CASE ) return cls( SCREAMING_SNAKE_CASE , question_encoder_tokenizer=SCREAMING_SNAKE_CASE , generator_tokenizer=SCREAMING_SNAKE_CASE , retrieval_workers=SCREAMING_SNAKE_CASE , index=SCREAMING_SNAKE_CASE , )
276
'''simple docstring''' 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''' ) A__: Dict = None A__: Tuple = { '''7B''': 1_1008, '''13B''': 1_3824, '''30B''': 1_7920, '''65B''': 2_2016, '''70B''': 2_8672, } A__: Any = { '''7B''': 1, '''7Bf''': 1, '''13B''': 2, '''13Bf''': 2, '''30B''': 4, '''65B''': 8, '''70B''': 8, '''70Bf''': 8, } def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Optional[int]=1 ,_UpperCAmelCase : List[str]=256 ) -> Dict: return multiple_of * ((int(ffn_dim_multiplier * int(8 * n / 3 ) ) + multiple_of - 1) // multiple_of) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[Any] ) -> List[str]: with open(_UpperCAmelCase ,"""r""" ) as f: return json.load(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : Optional[Any] ) -> Tuple: with open(_UpperCAmelCase ,"""w""" ) as f: json.dump(_UpperCAmelCase ,_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : int ,_UpperCAmelCase : List[Any]=True ) -> Union[str, Any]: os.makedirs(_UpperCAmelCase ,exist_ok=_UpperCAmelCase ) _a : Union[str, Any] =os.path.join(_UpperCAmelCase ,"""tmp""" ) os.makedirs(_UpperCAmelCase ,exist_ok=_UpperCAmelCase ) _a : int =read_json(os.path.join(_UpperCAmelCase ,"""params.json""" ) ) _a : int =NUM_SHARDS[model_size] _a : Dict =params["""n_layers"""] _a : Union[str, Any] =params["""n_heads"""] _a : List[str] =n_heads // num_shards _a : int =params["""dim"""] _a : Union[str, Any] =dim // n_heads _a : int =1_0_0_0_0.0 _a : str =1.0 / (base ** (torch.arange(0 ,_UpperCAmelCase ,2 ).float() / dims_per_head)) if "n_kv_heads" in params: _a : str =params["""n_kv_heads"""] # for GQA / MQA _a : Optional[Any] =n_heads_per_shard // num_key_value_heads _a : Optional[int] =dim // num_key_value_heads else: # compatibility with other checkpoints _a : str =n_heads _a : Any =n_heads_per_shard _a : str =dim # permute for sliced rotary def permute(_UpperCAmelCase : Tuple ,_UpperCAmelCase : Optional[int]=n_heads ,_UpperCAmelCase : Optional[int]=dim ,_UpperCAmelCase : List[str]=dim ): return w.view(_UpperCAmelCase ,dima // n_heads // 2 ,2 ,_UpperCAmelCase ).transpose(1 ,2 ).reshape(_UpperCAmelCase ,_UpperCAmelCase ) 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.) _a : Any =torch.load(os.path.join(_UpperCAmelCase ,"""consolidated.00.pth""" ) ,map_location="""cpu""" ) else: # Sharded _a : List[Any] =[ torch.load(os.path.join(_UpperCAmelCase ,F"consolidated.{i:02d}.pth" ) ,map_location="""cpu""" ) for i in range(_UpperCAmelCase ) ] _a : Any =0 _a : Optional[int] ={"""weight_map""": {}} for layer_i in range(_UpperCAmelCase ): _a : List[str] =F"pytorch_model-{layer_i + 1}-of-{n_layers + 1}.bin" if model_size == "7B": # Unsharded _a : List[str] ={ 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. _a : Tuple ={ 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(), } _a : str =permute( torch.cat( [ loaded[i][F"layers.{layer_i}.attention.wq.weight"].view(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) for i in range(_UpperCAmelCase ) ] ,dim=0 ,).reshape(_UpperCAmelCase ,_UpperCAmelCase ) ) _a : Tuple =permute( torch.cat( [ loaded[i][F"layers.{layer_i}.attention.wk.weight"].view( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) for i in range(_UpperCAmelCase ) ] ,dim=0 ,).reshape(_UpperCAmelCase ,_UpperCAmelCase ) ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,) _a : Any =torch.cat( [ loaded[i][F"layers.{layer_i}.attention.wv.weight"].view( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) for i in range(_UpperCAmelCase ) ] ,dim=0 ,).reshape(_UpperCAmelCase ,_UpperCAmelCase ) _a : List[str] =torch.cat( [loaded[i][F"layers.{layer_i}.attention.wo.weight"] for i in range(_UpperCAmelCase )] ,dim=1 ) _a : Union[str, Any] =torch.cat( [loaded[i][F"layers.{layer_i}.feed_forward.w1.weight"] for i in range(_UpperCAmelCase )] ,dim=0 ) _a : Tuple =torch.cat( [loaded[i][F"layers.{layer_i}.feed_forward.w2.weight"] for i in range(_UpperCAmelCase )] ,dim=1 ) _a : Union[str, Any] =torch.cat( [loaded[i][F"layers.{layer_i}.feed_forward.w3.weight"] for i in range(_UpperCAmelCase )] ,dim=0 ) _a : str =inv_freq for k, v in state_dict.items(): _a : Any =filename param_count += v.numel() torch.save(_UpperCAmelCase ,os.path.join(_UpperCAmelCase ,_UpperCAmelCase ) ) _a : Union[str, Any] =F"pytorch_model-{n_layers + 1}-of-{n_layers + 1}.bin" if model_size == "7B": # Unsharded _a : List[str] ={ """model.embed_tokens.weight""": loaded["""tok_embeddings.weight"""], """model.norm.weight""": loaded["""norm.weight"""], """lm_head.weight""": loaded["""output.weight"""], } else: _a : int ={ """model.norm.weight""": loaded[0]["""norm.weight"""], """model.embed_tokens.weight""": torch.cat( [loaded[i]["""tok_embeddings.weight"""] for i in range(_UpperCAmelCase )] ,dim=1 ), """lm_head.weight""": torch.cat([loaded[i]["""output.weight"""] for i in range(_UpperCAmelCase )] ,dim=0 ), } for k, v in state_dict.items(): _a : Dict =filename param_count += v.numel() torch.save(_UpperCAmelCase ,os.path.join(_UpperCAmelCase ,_UpperCAmelCase ) ) # Write configs _a : Tuple ={"""total_size""": param_count * 2} write_json(_UpperCAmelCase ,os.path.join(_UpperCAmelCase ,"""pytorch_model.bin.index.json""" ) ) _a : Optional[Any] =params["""ffn_dim_multiplier"""] if """ffn_dim_multiplier""" in params else 1 _a : int =params["""multiple_of"""] if """multiple_of""" in params else 256 _a : List[Any] =LlamaConfig( hidden_size=_UpperCAmelCase ,intermediate_size=compute_intermediate_size(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) ,num_attention_heads=params["""n_heads"""] ,num_hidden_layers=params["""n_layers"""] ,rms_norm_eps=params["""norm_eps"""] ,num_key_value_heads=_UpperCAmelCase ,) config.save_pretrained(_UpperCAmelCase ) # 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.""" ) _a : Any =LlamaForCausalLM.from_pretrained(_UpperCAmelCase ,torch_dtype=torch.floataa ,low_cpu_mem_usage=_UpperCAmelCase ) # Avoid saving this as part of the config. del model.config._name_or_path print("""Saving in the Transformers format.""" ) model.save_pretrained(_UpperCAmelCase ,safe_serialization=_UpperCAmelCase ) shutil.rmtree(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ,_UpperCAmelCase : int ) -> Optional[Any]: # Initialize the tokenizer based on the `spm` model _a : List[str] =LlamaTokenizer if LlamaTokenizerFast is None else LlamaTokenizerFast print(F"Saving a {tokenizer_class.__name__} to {tokenizer_path}." ) _a : List[Any] =tokenizer_class(_UpperCAmelCase ) tokenizer.save_pretrained(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( ) -> Union[str, Any]: _a : List[str] =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=_UpperCAmelCase ,help="""Whether or not to save using `safetensors`.""" ) _a : Optional[Any] =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 ,) _a : List[Any] =os.path.join(args.input_dir ,"""tokenizer.model""" ) write_tokenizer(args.output_dir ,_UpperCAmelCase ) if __name__ == "__main__": main()
276
1
'''simple docstring''' from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Sequence, Value from .base import TaskTemplate @dataclass(frozen=UpperCAmelCase__ ) class A__ ( UpperCAmelCase__ ): # `task` is not a ClassVar since we want it to be part of the `asdict` output for JSON serialization __UpperCamelCase : str = field(default="question-answering-extractive" , metadata={"include_in_asdict_even_if_is_default": True} ) __UpperCamelCase : ClassVar[Features] = Features({"question": Value("string" ), "context": Value("string" )} ) __UpperCamelCase : ClassVar[Features] = Features( { "answers": Sequence( { "text": Value("string" ), "answer_start": Value("int32" ), } ) } ) __UpperCamelCase : str = "question" __UpperCamelCase : str = "context" __UpperCamelCase : str = "answers" @property def __UpperCAmelCase ( self :List[str] ) -> Dict[str, str]: '''simple docstring''' return {self.question_column: "question", self.context_column: "context", self.answers_column: "answers"}
276
'''simple docstring''' import contextlib import os import sqlitea import pytest from datasets import Dataset, Features, Value from datasets.io.sql import SqlDatasetReader, SqlDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases, require_sqlalchemy def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Any ,_UpperCAmelCase : str ) -> Dict: assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ) 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 @require_sqlalchemy @pytest.mark.parametrize("""keep_in_memory""" ,[False, True] ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Optional[int] ,_UpperCAmelCase : str ) -> Optional[Any]: _a : Any =tmp_path / """cache""" _a : int ={"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): _a : Tuple =SqlDatasetReader( """dataset""" ,"""sqlite:///""" + sqlite_path ,cache_dir=_UpperCAmelCase ,keep_in_memory=_UpperCAmelCase ).read() _check_sql_dataset(_UpperCAmelCase ,_UpperCAmelCase ) @require_sqlalchemy @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 SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[Any] ,_UpperCAmelCase : Dict ,_UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : int ) -> List[Any]: _a : Union[str, Any] =tmp_path / """cache""" _a : str ={"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} _a : Optional[int] =features.copy() if features else default_expected_features _a : Union[str, Any] =( Features({feature: Value(_UpperCAmelCase ) for feature, dtype in features.items()} ) if features is not None else None ) _a : Optional[Any] =SqlDatasetReader("""dataset""" ,"""sqlite:///""" + sqlite_path ,features=_UpperCAmelCase ,cache_dir=_UpperCAmelCase ).read() _check_sql_dataset(_UpperCAmelCase ,_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[Any] ) -> List[str]: with contextlib.closing(sqlitea.connect(_UpperCAmelCase ) ) as con: _a : Any =con.cursor() cur.execute("""SELECT * FROM dataset""" ) for row in cur: yield row @require_sqlalchemy def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Dict ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : List[str] ) -> Union[str, Any]: _a : Union[str, Any] =tmp_path / """cache""" _a : Union[str, Any] =os.path.join(_UpperCAmelCase ,"""tmp.sql""" ) _a : Tuple =SqlDatasetReader("""dataset""" ,"""sqlite:///""" + sqlite_path ,cache_dir=_UpperCAmelCase ).read() SqlDatasetWriter(_UpperCAmelCase ,"""dataset""" ,"""sqlite:///""" + output_sqlite_path ,num_proc=1 ).write() _a : Tuple =iter_sql_file(_UpperCAmelCase ) _a : List[Any] =iter_sql_file(_UpperCAmelCase ) for rowa, rowa in zip(_UpperCAmelCase ,_UpperCAmelCase ): assert rowa == rowa @require_sqlalchemy def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Any ,_UpperCAmelCase : List[Any] ) -> Optional[int]: _a : int =tmp_path / """cache""" _a : Any =os.path.join(_UpperCAmelCase ,"""tmp.sql""" ) _a : Union[str, Any] =SqlDatasetReader("""dataset""" ,"""sqlite:///""" + sqlite_path ,cache_dir=_UpperCAmelCase ).read() SqlDatasetWriter(_UpperCAmelCase ,"""dataset""" ,"""sqlite:///""" + output_sqlite_path ,num_proc=2 ).write() _a : List[Any] =iter_sql_file(_UpperCAmelCase ) _a : str =iter_sql_file(_UpperCAmelCase ) for rowa, rowa in zip(_UpperCAmelCase ,_UpperCAmelCase ): assert rowa == rowa @require_sqlalchemy def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : str ,_UpperCAmelCase : List[Any] ) -> List[str]: _a : List[str] =tmp_path / """cache""" _a : Dict =os.path.join(_UpperCAmelCase ,"""tmp.sql""" ) _a : Optional[Any] =SqlDatasetReader("""dataset""" ,"""sqlite:///""" + sqlite_path ,cache_dir=_UpperCAmelCase ).read() with pytest.raises(_UpperCAmelCase ): SqlDatasetWriter(_UpperCAmelCase ,"""dataset""" ,"""sqlite:///""" + output_sqlite_path ,num_proc=0 ).write()
276
1
'''simple docstring''' import sacrebleu as scb from packaging import version from sacrebleu import CHRF import datasets A__: str = '''\ @inproceedings{popovic-2015-chrf, title = "chr{F}: character n-gram {F}-score for automatic {MT} evaluation", author = "Popovi{\'c}, Maja", booktitle = "Proceedings of the Tenth Workshop on Statistical Machine Translation", month = sep, year = "2015", address = "Lisbon, Portugal", publisher = "Association for Computational Linguistics", url = "https://aclanthology.org/W15-3049", doi = "10.18653/v1/W15-3049", pages = "392--395", } @inproceedings{popovic-2017-chrf, title = "chr{F}++: words helping character n-grams", author = "Popovi{\'c}, Maja", booktitle = "Proceedings of the Second Conference on Machine Translation", month = sep, year = "2017", address = "Copenhagen, Denmark", publisher = "Association for Computational Linguistics", url = "https://aclanthology.org/W17-4770", doi = "10.18653/v1/W17-4770", pages = "612--618", } @inproceedings{post-2018-call, title = "A Call for Clarity in Reporting {BLEU} Scores", author = "Post, Matt", booktitle = "Proceedings of the Third Conference on Machine Translation: Research Papers", month = oct, year = "2018", address = "Belgium, Brussels", publisher = "Association for Computational Linguistics", url = "https://www.aclweb.org/anthology/W18-6319", pages = "186--191", } ''' A__: Optional[int] = '''\ ChrF and ChrF++ are two MT evaluation metrics. They both use the F-score statistic for character n-gram matches, and ChrF++ adds word n-grams as well which correlates more strongly with direct assessment. We use the implementation that is already present in sacrebleu. The implementation here is slightly different from sacrebleu in terms of the required input format. The length of the references and hypotheses lists need to be the same, so you may need to transpose your references compared to sacrebleu\'s required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534 See the README.md file at https://github.com/mjpost/sacreBLEU#chrf--chrf for more information. ''' A__: Dict = ''' Produces ChrF(++) scores for hypotheses given reference translations. Args: predictions (list of str): The predicted sentences. references (list of list of str): The references. There should be one reference sub-list for each prediction sentence. char_order (int): Character n-gram order. Defaults to `6`. word_order (int): Word n-gram order. If equals to `2`, the metric is referred to as chrF++. Defaults to `0`. beta (int): Determine the importance of recall w.r.t precision. Defaults to `2`. lowercase (bool): if `True`, enables case-insensitivity. Defaults to `False`. whitespace (bool): If `True`, include whitespaces when extracting character n-grams. eps_smoothing (bool): If `True`, applies epsilon smoothing similar to reference chrF++.py, NLTK and Moses implementations. If `False`, it takes into account effective match order similar to sacreBLEU < 2.0.0. Defaults to `False`. Returns: \'score\' (float): The chrF (chrF++) score, \'char_order\' (int): The character n-gram order, \'word_order\' (int): The word n-gram order. If equals to 2, the metric is referred to as chrF++, \'beta\' (int): Determine the importance of recall w.r.t precision Examples: Example 1--a simple example of calculating chrF: >>> 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."] >>> 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."]] >>> chrf = datasets.load_metric("chrf") >>> results = chrf.compute(predictions=prediction, references=reference) >>> print(results) {\'score\': 84.64214891738334, \'char_order\': 6, \'word_order\': 0, \'beta\': 2} Example 2--the same example, but with the argument word_order=2, to calculate chrF++ instead of chrF: >>> 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."] >>> 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."]] >>> chrf = datasets.load_metric("chrf") >>> results = chrf.compute(predictions=prediction, ... references=reference, ... word_order=2) >>> print(results) {\'score\': 82.87263732906315, \'char_order\': 6, \'word_order\': 2, \'beta\': 2} Example 3--the same chrF++ example as above, but with `lowercase=True` to normalize all case: >>> 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."] >>> 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."]] >>> chrf = datasets.load_metric("chrf") >>> results = chrf.compute(predictions=prediction, ... references=reference, ... word_order=2, ... lowercase=True) >>> print(results) {\'score\': 92.12853119829202, \'char_order\': 6, \'word_order\': 2, \'beta\': 2} ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A__ ( datasets.Metric ): def __UpperCAmelCase ( self :str ) -> List[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 __UpperCAmelCase ( self :List[str] , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :int = CHRF.CHAR_ORDER , SCREAMING_SNAKE_CASE :int = CHRF.WORD_ORDER , SCREAMING_SNAKE_CASE :int = CHRF.BETA , SCREAMING_SNAKE_CASE :bool = False , SCREAMING_SNAKE_CASE :bool = False , SCREAMING_SNAKE_CASE :bool = False , ) -> Tuple: '''simple docstring''' _a : int =len(references[0] ) if any(len(SCREAMING_SNAKE_CASE ) != references_per_prediction for refs in references ): raise ValueError("""Sacrebleu requires the same number of references for each prediction""" ) _a : int =[[refs[i] for refs in references] for i in range(SCREAMING_SNAKE_CASE )] _a : Optional[int] =CHRF(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) _a : Optional[int] =sb_chrf.corpus_score(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) return { "score": output.score, "char_order": output.char_order, "word_order": output.word_order, "beta": output.beta, }
276
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A__: List[str] = logging.get_logger(__name__) A__: Union[str, Any] = { '''facebook/data2vec-text-base''': '''https://huggingface.co/data2vec/resolve/main/config.json''', } class A__ ( UpperCAmelCase__ ): __UpperCamelCase : int = "data2vec-text" def __init__( self :str , SCREAMING_SNAKE_CASE :Optional[Any]=3_0_5_2_2 , SCREAMING_SNAKE_CASE :Any=7_6_8 , SCREAMING_SNAKE_CASE :List[Any]=1_2 , SCREAMING_SNAKE_CASE :List[str]=1_2 , SCREAMING_SNAKE_CASE :Dict=3_0_7_2 , SCREAMING_SNAKE_CASE :List[str]="gelu" , SCREAMING_SNAKE_CASE :Any=0.1 , SCREAMING_SNAKE_CASE :List[str]=0.1 , SCREAMING_SNAKE_CASE :int=5_1_2 , SCREAMING_SNAKE_CASE :int=2 , SCREAMING_SNAKE_CASE :Union[str, Any]=0.02 , SCREAMING_SNAKE_CASE :Dict=1e-12 , SCREAMING_SNAKE_CASE :int=1 , SCREAMING_SNAKE_CASE :Dict=0 , SCREAMING_SNAKE_CASE :List[Any]=2 , SCREAMING_SNAKE_CASE :str="absolute" , SCREAMING_SNAKE_CASE :Tuple=True , SCREAMING_SNAKE_CASE :Union[str, Any]=None , **SCREAMING_SNAKE_CASE :Union[str, Any] , ) -> List[str]: '''simple docstring''' super().__init__(pad_token_id=SCREAMING_SNAKE_CASE , bos_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) _a : Optional[Any] =vocab_size _a : Optional[Any] =hidden_size _a : Any =num_hidden_layers _a : List[str] =num_attention_heads _a : Union[str, Any] =hidden_act _a : Any =intermediate_size _a : str =hidden_dropout_prob _a : Optional[Any] =attention_probs_dropout_prob _a : Optional[Any] =max_position_embeddings _a : Union[str, Any] =type_vocab_size _a : Tuple =initializer_range _a : Optional[int] =layer_norm_eps _a : Tuple =position_embedding_type _a : int =use_cache _a : List[str] =classifier_dropout class A__ ( UpperCAmelCase__ ): @property def __UpperCAmelCase ( self :int ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' 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), ] )
276
1
'''simple docstring''' import itertools import os import random import tempfile import unittest import numpy as np from datasets import load_dataset from transformers import is_speech_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import WhisperFeatureExtractor if is_torch_available(): import torch A__: Optional[int] = random.Random() def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Dict ,_UpperCAmelCase : List[Any]=1.0 ,_UpperCAmelCase : List[str]=None ,_UpperCAmelCase : List[str]=None ) -> Optional[int]: if rng is None: _a : Optional[int] =global_rng _a : str =[] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch @require_torchaudio class A__ ( unittest.TestCase ): def __init__( self :str , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :Tuple=7 , SCREAMING_SNAKE_CASE :Union[str, Any]=4_0_0 , SCREAMING_SNAKE_CASE :str=2_0_0_0 , SCREAMING_SNAKE_CASE :str=1_0 , SCREAMING_SNAKE_CASE :Tuple=1_6_0 , SCREAMING_SNAKE_CASE :List[str]=8 , SCREAMING_SNAKE_CASE :Optional[int]=0.0 , SCREAMING_SNAKE_CASE :Union[str, Any]=4_0_0_0 , SCREAMING_SNAKE_CASE :Optional[int]=False , SCREAMING_SNAKE_CASE :List[str]=True , ) -> int: '''simple docstring''' _a : List[Any] =parent _a : Optional[Any] =batch_size _a : int =min_seq_length _a : Tuple =max_seq_length _a : List[str] =(self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) _a : List[Any] =padding_value _a : int =sampling_rate _a : List[str] =return_attention_mask _a : Union[str, Any] =do_normalize _a : Tuple =feature_size _a : str =chunk_length _a : Any =hop_length def __UpperCAmelCase ( self :Dict ) -> Dict: '''simple docstring''' return { "feature_size": self.feature_size, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def __UpperCAmelCase ( self :Any , SCREAMING_SNAKE_CASE :List[str]=False , SCREAMING_SNAKE_CASE :Any=False ) -> List[Any]: '''simple docstring''' def _flatten(SCREAMING_SNAKE_CASE :Optional[int] ): return list(itertools.chain(*SCREAMING_SNAKE_CASE ) ) if equal_length: _a : Dict =[floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size _a : Optional[Any] =[ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: _a : str =[np.asarray(SCREAMING_SNAKE_CASE ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class A__ ( UpperCAmelCase__ , unittest.TestCase ): __UpperCamelCase : Union[str, Any] = WhisperFeatureExtractor if is_speech_available() else None def __UpperCAmelCase ( self :List[Any] ) -> Optional[int]: '''simple docstring''' _a : Optional[int] =WhisperFeatureExtractionTester(self ) def __UpperCAmelCase ( self :Optional[Any] ) -> Dict: '''simple docstring''' _a : int =self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: _a : List[Any] =feat_extract_first.save_pretrained(SCREAMING_SNAKE_CASE )[0] check_json_file_has_correct_format(SCREAMING_SNAKE_CASE ) _a : Optional[Any] =self.feature_extraction_class.from_pretrained(SCREAMING_SNAKE_CASE ) _a : Optional[Any] =feat_extract_first.to_dict() _a : Optional[int] =feat_extract_second.to_dict() _a : str =feat_extract_first.mel_filters _a : List[str] =feat_extract_second.mel_filters self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) self.assertEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Dict ) -> Optional[int]: '''simple docstring''' _a : Any =self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: _a : List[Any] =os.path.join(SCREAMING_SNAKE_CASE , """feat_extract.json""" ) feat_extract_first.to_json_file(SCREAMING_SNAKE_CASE ) _a : Dict =self.feature_extraction_class.from_json_file(SCREAMING_SNAKE_CASE ) _a : int =feat_extract_first.to_dict() _a : Any =feat_extract_second.to_dict() _a : List[str] =feat_extract_first.mel_filters _a : List[Any] =feat_extract_second.mel_filters self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) self.assertEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Tuple ) -> Union[str, Any]: '''simple docstring''' # Tests that all call wrap to encode_plus and batch_encode_plus _a : str =self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 _a : List[str] =[floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] _a : str =[np.asarray(SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs] # Test feature size _a : Any =feature_extractor(SCREAMING_SNAKE_CASE , padding="""max_length""" , return_tensors="""np""" ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames ) self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size ) # Test not batched input _a : Dict =feature_extractor(speech_inputs[0] , return_tensors="""np""" ).input_features _a : Optional[Any] =feature_extractor(np_speech_inputs[0] , return_tensors="""np""" ).input_features self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=1e-3 ) ) # Test batched _a : Optional[int] =feature_extractor(SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features _a : Optional[int] =feature_extractor(SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. _a : int =[floats_list((1, x) )[0] for x in (8_0_0, 8_0_0, 8_0_0)] _a : List[str] =np.asarray(SCREAMING_SNAKE_CASE ) _a : Optional[Any] =feature_extractor(SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features _a : Optional[Any] =feature_extractor(SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=1e-3 ) ) # Test truncation required _a : Dict =[floats_list((1, x) )[0] for x in range(2_0_0 , (feature_extractor.n_samples + 5_0_0) , 2_0_0 )] _a : Dict =[np.asarray(SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs] _a : Union[str, Any] =[x[: feature_extractor.n_samples] for x in speech_inputs] _a : Dict =[np.asarray(SCREAMING_SNAKE_CASE ) for speech_input in speech_inputs_truncated] _a : Dict =feature_extractor(SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features _a : Optional[int] =feature_extractor(SCREAMING_SNAKE_CASE , return_tensors="""np""" ).input_features for enc_seq_a, enc_seq_a in zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=1e-3 ) ) def __UpperCAmelCase ( self :int ) -> Optional[int]: '''simple docstring''' import torch _a : List[Any] =self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) _a : int =np.random.rand(1_0_0 , 3_2 ).astype(np.floataa ) _a : Optional[int] =np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: _a : str =feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""np""" ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) _a : Union[str, Any] =feature_extractor.pad([{"""input_features""": inputs}] , return_tensors="""pt""" ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def __UpperCAmelCase ( self :List[Any] , SCREAMING_SNAKE_CASE :Tuple ) -> Union[str, Any]: '''simple docstring''' _a : Optional[Any] =load_dataset("""hf-internal-testing/librispeech_asr_dummy""" , """clean""" , split="""validation""" ) # automatic decoding with librispeech _a : Optional[Any] =ds.sort("""id""" ).select(range(SCREAMING_SNAKE_CASE ) )[:num_samples]["""audio"""] return [x["array"] for x in speech_samples] def __UpperCAmelCase ( self :str ) -> Optional[int]: '''simple docstring''' # fmt: off _a : Any =torch.tensor( [ 0.1_193, -0.0_946, -0.1_098, -0.0_196, 0.0_225, -0.0_690, -0.1_736, 0.0_951, 0.0_971, -0.0_817, -0.0_702, 0.0_162, 0.0_260, 0.0_017, -0.0_192, -0.1_678, 0.0_709, -0.1_867, -0.0_655, -0.0_274, -0.0_234, -0.1_884, -0.0_516, -0.0_554, -0.0_274, -0.1_425, -0.1_423, 0.0_837, 0.0_377, -0.0_854 ] ) # fmt: on _a : Any =self._load_datasamples(1 ) _a : int =WhisperFeatureExtractor() _a : str =feature_extractor(SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).input_features self.assertEqual(input_features.shape , (1, 8_0, 3_0_0_0) ) self.assertTrue(torch.allclose(input_features[0, 0, :3_0] , SCREAMING_SNAKE_CASE , atol=1e-4 ) ) def __UpperCAmelCase ( self :Any ) -> Any: '''simple docstring''' _a : Dict =self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) _a : str =self._load_datasamples(1 )[0] _a : List[Any] =((audio - audio.min()) / (audio.max() - audio.min())) * 6_5_5_3_5 # Rescale to [0, 65535] to show issue _a : Union[str, Any] =feat_extract.zero_mean_unit_var_norm([audio] , attention_mask=SCREAMING_SNAKE_CASE )[0] self.assertTrue(np.all(np.mean(SCREAMING_SNAKE_CASE ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(SCREAMING_SNAKE_CASE ) - 1 ) < 1e-3 ) )
276
'''simple docstring''' from typing import Dict, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import flip_channel_order, resize, to_channel_dimension_format, to_pil_image from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_pytesseract_available, is_vision_available, logging, requires_backends if is_vision_available(): import PIL # soft dependency if is_pytesseract_available(): import pytesseract A__: Union[str, Any] = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : List[str] ) -> int: return [ int(1000 * (box[0] / width) ), int(1000 * (box[1] / height) ), int(1000 * (box[2] / width) ), int(1000 * (box[3] / height) ), ] def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : np.ndarray ,_UpperCAmelCase : Optional[str] ,_UpperCAmelCase : Optional[str] = None ) -> Optional[int]: _a : Any =tesseract_config if tesseract_config is not None else """""" # apply OCR _a : Optional[Any] =to_pil_image(_UpperCAmelCase ) _a , _a : List[Any] =pil_image.size _a : List[str] =pytesseract.image_to_data(_UpperCAmelCase ,lang=_UpperCAmelCase ,output_type="""dict""" ,config=_UpperCAmelCase ) _a , _a , _a , _a , _a : str =data["""text"""], data["""left"""], data["""top"""], data["""width"""], data["""height"""] # filter empty words and corresponding coordinates _a : Tuple =[idx for idx, word in enumerate(_UpperCAmelCase ) if not word.strip()] _a : List[Any] =[word for idx, word in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] _a : Dict =[coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] _a : List[str] =[coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] _a : Union[str, Any] =[coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] _a : Union[str, Any] =[coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] # turn coordinates into (left, top, left+width, top+height) format _a : List[str] =[] for x, y, w, h in zip(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ): _a : int =[x, y, x + w, y + h] actual_boxes.append(_UpperCAmelCase ) # finally, normalize the bounding boxes _a : str =[] for box in actual_boxes: normalized_boxes.append(normalize_box(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) ) assert len(_UpperCAmelCase ) == len(_UpperCAmelCase ), "Not as many words as there are bounding boxes" return words, normalized_boxes class A__ ( UpperCAmelCase__ ): __UpperCamelCase : List[Any] = ["pixel_values"] def __init__( self :Tuple , SCREAMING_SNAKE_CASE :bool = True , SCREAMING_SNAKE_CASE :Dict[str, int] = None , SCREAMING_SNAKE_CASE :PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE :bool = True , SCREAMING_SNAKE_CASE :Optional[str] = None , SCREAMING_SNAKE_CASE :Optional[str] = "" , **SCREAMING_SNAKE_CASE :Tuple , ) -> None: '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE ) _a : List[Any] =size if size is not None else {"""height""": 2_2_4, """width""": 2_2_4} _a : Tuple =get_size_dict(SCREAMING_SNAKE_CASE ) _a : Dict =do_resize _a : Tuple =size _a : str =resample _a : Dict =apply_ocr _a : Union[str, Any] =ocr_lang _a : Dict =tesseract_config def __UpperCAmelCase ( self :List[str] , SCREAMING_SNAKE_CASE :np.ndarray , SCREAMING_SNAKE_CASE :Dict[str, int] , SCREAMING_SNAKE_CASE :PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE :Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE :Dict , ) -> np.ndarray: '''simple docstring''' _a : int =get_size_dict(SCREAMING_SNAKE_CASE ) if "height" not in size or "width" not in size: raise ValueError(f"The size dictionary must contain the keys 'height' and 'width'. Got {size.keys()}" ) _a : Any =(size["""height"""], size["""width"""]) return resize(SCREAMING_SNAKE_CASE , size=SCREAMING_SNAKE_CASE , resample=SCREAMING_SNAKE_CASE , data_format=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Dict , SCREAMING_SNAKE_CASE :ImageInput , SCREAMING_SNAKE_CASE :bool = None , SCREAMING_SNAKE_CASE :Dict[str, int] = None , SCREAMING_SNAKE_CASE :PILImageResampling = None , SCREAMING_SNAKE_CASE :bool = None , SCREAMING_SNAKE_CASE :Optional[str] = None , SCREAMING_SNAKE_CASE :Optional[str] = None , SCREAMING_SNAKE_CASE :Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE :ChannelDimension = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE :Optional[Any] , ) -> PIL.Image.Image: '''simple docstring''' _a : Optional[int] =do_resize if do_resize is not None else self.do_resize _a : Optional[int] =size if size is not None else self.size _a : str =get_size_dict(SCREAMING_SNAKE_CASE ) _a : List[str] =resample if resample is not None else self.resample _a : int =apply_ocr if apply_ocr is not None else self.apply_ocr _a : str =ocr_lang if ocr_lang is not None else self.ocr_lang _a : Union[str, Any] =tesseract_config if tesseract_config is not None else self.tesseract_config _a : List[str] =make_list_of_images(SCREAMING_SNAKE_CASE ) if not valid_images(SCREAMING_SNAKE_CASE ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None: raise ValueError("""Size must be specified if do_resize is True.""" ) # All transformations expect numpy arrays. _a : List[Any] =[to_numpy_array(SCREAMING_SNAKE_CASE ) for image in images] if apply_ocr: requires_backends(self , """pytesseract""" ) _a : Any =[] _a : Any =[] for image in images: _a , _a : int =apply_tesseract(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) words_batch.append(SCREAMING_SNAKE_CASE ) boxes_batch.append(SCREAMING_SNAKE_CASE ) if do_resize: _a : Union[str, Any] =[self.resize(image=SCREAMING_SNAKE_CASE , size=SCREAMING_SNAKE_CASE , resample=SCREAMING_SNAKE_CASE ) for image in images] # flip color channels from RGB to BGR (as Detectron2 requires this) _a : Dict =[flip_channel_order(SCREAMING_SNAKE_CASE ) for image in images] _a : str =[to_channel_dimension_format(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for image in images] _a : str =BatchFeature(data={"""pixel_values""": images} , tensor_type=SCREAMING_SNAKE_CASE ) if apply_ocr: _a : List[Any] =words_batch _a : Dict =boxes_batch return data
276
1
'''simple docstring''' def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ,_UpperCAmelCase : int ) -> str: if a < 0 or b < 0: raise ValueError("""the value of both inputs must be positive""" ) _a : Dict =str(bin(_UpperCAmelCase ) )[2:] # remove the leading "0b" _a : Tuple =str(bin(_UpperCAmelCase ) )[2:] # remove the leading "0b" _a : Dict =max(len(_UpperCAmelCase ) ,len(_UpperCAmelCase ) ) return "0b" + "".join( str(int(char_a == """1""" and char_b == """1""" ) ) for char_a, char_b in zip(a_binary.zfill(_UpperCAmelCase ) ,b_binary.zfill(_UpperCAmelCase ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
276
'''simple docstring''' from __future__ import annotations import requests def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ) -> dict: _a : Any =F"https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty" return requests.get(_UpperCAmelCase ).json() def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int = 10 ) -> list[dict]: _a : Union[str, Any] ="""https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty""" _a : int =requests.get(_UpperCAmelCase ).json()[:max_stories] return [get_hackernews_story(_UpperCAmelCase ) for story_id in story_ids] def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int = 10 ) -> str: _a : Union[str, Any] =hackernews_top_stories(_UpperCAmelCase ) return "\n".join("""* [{title}]({url})""".format(**_UpperCAmelCase ) for story in stories ) if __name__ == "__main__": print(hackernews_top_stories_as_markdown())
276
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) A__: List[str] = {'''configuration_mbart''': ['''MBART_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MBartConfig''', '''MBartOnnxConfig''']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: int = ['''MBartTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Any = ['''MBartTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: List[str] = [ '''MBART_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MBartForCausalLM''', '''MBartForConditionalGeneration''', '''MBartForQuestionAnswering''', '''MBartForSequenceClassification''', '''MBartModel''', '''MBartPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Tuple = [ '''TFMBartForConditionalGeneration''', '''TFMBartModel''', '''TFMBartPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: str = [ '''FlaxMBartForConditionalGeneration''', '''FlaxMBartForQuestionAnswering''', '''FlaxMBartForSequenceClassification''', '''FlaxMBartModel''', '''FlaxMBartPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_mbart import MBART_PRETRAINED_CONFIG_ARCHIVE_MAP, MBartConfig, MBartOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart import MBartTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart_fast import MBartTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mbart import ( MBART_PRETRAINED_MODEL_ARCHIVE_LIST, MBartForCausalLM, MBartForConditionalGeneration, MBartForQuestionAnswering, MBartForSequenceClassification, MBartModel, MBartPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mbart import TFMBartForConditionalGeneration, TFMBartModel, TFMBartPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_mbart import ( FlaxMBartForConditionalGeneration, FlaxMBartForQuestionAnswering, FlaxMBartForSequenceClassification, FlaxMBartModel, FlaxMBartPreTrainedModel, ) else: import sys A__: Optional[int] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
276
'''simple docstring''' from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .modeling_utils import ModelMixin from .vae import Decoder, DecoderOutput, Encoder, VectorQuantizer @dataclass class A__ ( UpperCAmelCase__ ): __UpperCamelCase : torch.FloatTensor class A__ ( UpperCAmelCase__ , UpperCAmelCase__ ): @register_to_config def __init__( self :Optional[Any] , SCREAMING_SNAKE_CASE :int = 3 , SCREAMING_SNAKE_CASE :int = 3 , SCREAMING_SNAKE_CASE :Tuple[str] = ("DownEncoderBlock2D",) , SCREAMING_SNAKE_CASE :Tuple[str] = ("UpDecoderBlock2D",) , SCREAMING_SNAKE_CASE :Tuple[int] = (6_4,) , SCREAMING_SNAKE_CASE :int = 1 , SCREAMING_SNAKE_CASE :str = "silu" , SCREAMING_SNAKE_CASE :int = 3 , SCREAMING_SNAKE_CASE :int = 3_2 , SCREAMING_SNAKE_CASE :int = 2_5_6 , SCREAMING_SNAKE_CASE :int = 3_2 , SCREAMING_SNAKE_CASE :Optional[int] = None , SCREAMING_SNAKE_CASE :float = 0.18_215 , SCREAMING_SNAKE_CASE :str = "group" , ) -> Optional[int]: '''simple docstring''' super().__init__() # pass init params to Encoder _a : Union[str, Any] =Encoder( in_channels=SCREAMING_SNAKE_CASE , out_channels=SCREAMING_SNAKE_CASE , down_block_types=SCREAMING_SNAKE_CASE , block_out_channels=SCREAMING_SNAKE_CASE , layers_per_block=SCREAMING_SNAKE_CASE , act_fn=SCREAMING_SNAKE_CASE , norm_num_groups=SCREAMING_SNAKE_CASE , double_z=SCREAMING_SNAKE_CASE , ) _a : Optional[int] =vq_embed_dim if vq_embed_dim is not None else latent_channels _a : Optional[int] =nn.Convad(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , 1 ) _a : str =VectorQuantizer(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , beta=0.25 , remap=SCREAMING_SNAKE_CASE , sane_index_shape=SCREAMING_SNAKE_CASE ) _a : List[str] =nn.Convad(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , 1 ) # pass init params to Decoder _a : List[str] =Decoder( in_channels=SCREAMING_SNAKE_CASE , out_channels=SCREAMING_SNAKE_CASE , up_block_types=SCREAMING_SNAKE_CASE , block_out_channels=SCREAMING_SNAKE_CASE , layers_per_block=SCREAMING_SNAKE_CASE , act_fn=SCREAMING_SNAKE_CASE , norm_num_groups=SCREAMING_SNAKE_CASE , norm_type=SCREAMING_SNAKE_CASE , ) @apply_forward_hook def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :torch.FloatTensor , SCREAMING_SNAKE_CASE :bool = True ) -> VQEncoderOutput: '''simple docstring''' _a : Optional[int] =self.encoder(SCREAMING_SNAKE_CASE ) _a : int =self.quant_conv(SCREAMING_SNAKE_CASE ) if not return_dict: return (h,) return VQEncoderOutput(latents=SCREAMING_SNAKE_CASE ) @apply_forward_hook def __UpperCAmelCase ( self :List[Any] , SCREAMING_SNAKE_CASE :torch.FloatTensor , SCREAMING_SNAKE_CASE :bool = False , SCREAMING_SNAKE_CASE :bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: '''simple docstring''' # also go through quantization layer if not force_not_quantize: _a , _a , _a : Tuple =self.quantize(SCREAMING_SNAKE_CASE ) else: _a : str =h _a : Dict =self.post_quant_conv(SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =self.decoder(SCREAMING_SNAKE_CASE , quant if self.config.norm_type == """spatial""" else None ) if not return_dict: return (dec,) return DecoderOutput(sample=SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :torch.FloatTensor , SCREAMING_SNAKE_CASE :bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: '''simple docstring''' _a : Tuple =sample _a : int =self.encode(SCREAMING_SNAKE_CASE ).latents _a : List[Any] =self.decode(SCREAMING_SNAKE_CASE ).sample if not return_dict: return (dec,) return DecoderOutput(sample=SCREAMING_SNAKE_CASE )
276
1
'''simple docstring''' from unittest import TestCase from datasets import Sequence, Value from datasets.arrow_dataset import Dataset class A__ ( UpperCAmelCase__ ): def __UpperCAmelCase ( self :Optional[Any] ) -> int: '''simple docstring''' return [ {"col_1": 3, "col_2": "a"}, {"col_1": 2, "col_2": "b"}, {"col_1": 1, "col_2": "c"}, {"col_1": 0, "col_2": "d"}, ] def __UpperCAmelCase ( self :Optional[Any] ) -> Union[str, Any]: '''simple docstring''' _a : List[Any] ={"""col_1""": [3, 2, 1, 0], """col_2""": ["""a""", """b""", """c""", """d"""]} return Dataset.from_dict(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :int ) -> Optional[Any]: '''simple docstring''' _a : Dict =self._create_example_records() _a : Dict =Dataset.from_list(SCREAMING_SNAKE_CASE ) self.assertListEqual(dset.column_names , ["""col_1""", """col_2"""] ) for i, r in enumerate(SCREAMING_SNAKE_CASE ): self.assertDictEqual(SCREAMING_SNAKE_CASE , example_records[i] ) def __UpperCAmelCase ( self :Dict ) -> Dict: '''simple docstring''' _a : Any =self._create_example_records() _a : Union[str, Any] =Dataset.from_list(SCREAMING_SNAKE_CASE ) _a : Dict =Dataset.from_dict({k: [r[k] for r in example_records] for k in example_records[0]} ) self.assertEqual(dset.info , dset_from_dict.info ) def __UpperCAmelCase ( self :Any ) -> Union[str, Any]: # checks what happens with missing columns '''simple docstring''' _a : Dict =[{"""col_1""": 1}, {"""col_2""": """x"""}] _a : Dict =Dataset.from_list(SCREAMING_SNAKE_CASE ) self.assertDictEqual(dset[0] , {"""col_1""": 1} ) self.assertDictEqual(dset[1] , {"""col_1""": None} ) # NB: first record is used for columns def __UpperCAmelCase ( self :Optional[int] ) -> int: # checks if the type can be inferred from the second record '''simple docstring''' _a : Any =[{"""col_1""": []}, {"""col_1""": [1, 2]}] _a : List[str] =Dataset.from_list(SCREAMING_SNAKE_CASE ) self.assertEqual(dset.info.features["""col_1"""] , Sequence(Value("""int64""" ) ) ) def __UpperCAmelCase ( self :int ) -> int: '''simple docstring''' _a : Any =Dataset.from_list([] ) self.assertEqual(len(SCREAMING_SNAKE_CASE ) , 0 ) self.assertListEqual(dset.column_names , [] )
276
'''simple docstring''' import unittest from transformers import EsmConfig, is_torch_available from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import EsmForMaskedLM, EsmForSequenceClassification, EsmForTokenClassification, EsmModel from transformers.models.esm.modeling_esm import ( ESM_PRETRAINED_MODEL_ARCHIVE_LIST, EsmEmbeddings, create_position_ids_from_input_ids, ) class A__ : def __init__( self :Tuple , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :Optional[int]=1_3 , SCREAMING_SNAKE_CASE :Optional[int]=7 , SCREAMING_SNAKE_CASE :Tuple=False , SCREAMING_SNAKE_CASE :Dict=True , SCREAMING_SNAKE_CASE :Optional[int]=False , SCREAMING_SNAKE_CASE :Optional[Any]=True , SCREAMING_SNAKE_CASE :List[str]=3_3 , SCREAMING_SNAKE_CASE :Tuple=3_2 , SCREAMING_SNAKE_CASE :Tuple=5 , SCREAMING_SNAKE_CASE :int=4 , SCREAMING_SNAKE_CASE :Union[str, Any]=3_7 , SCREAMING_SNAKE_CASE :List[str]="gelu" , SCREAMING_SNAKE_CASE :Optional[Any]=0.1 , SCREAMING_SNAKE_CASE :Tuple=0.1 , SCREAMING_SNAKE_CASE :str=5_1_2 , SCREAMING_SNAKE_CASE :Dict=1_6 , SCREAMING_SNAKE_CASE :Dict=2 , SCREAMING_SNAKE_CASE :Union[str, Any]=0.02 , SCREAMING_SNAKE_CASE :str=3 , SCREAMING_SNAKE_CASE :List[str]=4 , SCREAMING_SNAKE_CASE :List[str]=None , ) -> Union[str, Any]: '''simple docstring''' _a : Union[str, Any] =parent _a : List[Any] =batch_size _a : Optional[int] =seq_length _a : Union[str, Any] =is_training _a : List[Any] =use_input_mask _a : Optional[int] =use_token_type_ids _a : int =use_labels _a : List[str] =vocab_size _a : List[Any] =hidden_size _a : int =num_hidden_layers _a : Tuple =num_attention_heads _a : Any =intermediate_size _a : str =hidden_act _a : Union[str, Any] =hidden_dropout_prob _a : Union[str, Any] =attention_probs_dropout_prob _a : str =max_position_embeddings _a : Dict =type_vocab_size _a : Tuple =type_sequence_label_size _a : Dict =initializer_range _a : List[str] =num_labels _a : Tuple =num_choices _a : int =scope def __UpperCAmelCase ( self :Union[str, Any] ) -> str: '''simple docstring''' _a : Optional[int] =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _a : List[Any] =None if self.use_input_mask: _a : Any =random_attention_mask([self.batch_size, self.seq_length] ) _a : Optional[int] =None _a : str =None _a : Dict =None if self.use_labels: _a : Dict =ids_tensor([self.batch_size] , self.type_sequence_label_size ) _a : str =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _a : List[str] =ids_tensor([self.batch_size] , self.num_choices ) _a : List[Any] =self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCAmelCase ( self :str ) -> Optional[int]: '''simple docstring''' return EsmConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , pad_token_id=1 , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) def __UpperCAmelCase ( self :List[str] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :int ) -> Tuple: '''simple docstring''' _a : Any =EsmModel(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() _a : Optional[Any] =model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =model(SCREAMING_SNAKE_CASE ) _a : str =model(SCREAMING_SNAKE_CASE ) 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 __UpperCAmelCase ( self :str , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :Optional[Any] ) -> Dict: '''simple docstring''' _a : str =EsmForMaskedLM(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() _a : Union[str, Any] =model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :List[Any] , SCREAMING_SNAKE_CASE :Union[str, Any] ) -> Optional[Any]: '''simple docstring''' _a : int =self.num_labels _a : Tuple =EsmForTokenClassification(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() _a : Tuple =model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCAmelCase ( self :Dict ) -> List[str]: '''simple docstring''' _a : Optional[Any] =self.prepare_config_and_inputs() ( ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ) : Any =config_and_inputs _a : List[Any] ={"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class A__ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): __UpperCamelCase : Any = False __UpperCamelCase : Any = ( ( EsmForMaskedLM, EsmModel, EsmForSequenceClassification, EsmForTokenClassification, ) if is_torch_available() else () ) __UpperCamelCase : str = () __UpperCamelCase : List[str] = ( { "feature-extraction": EsmModel, "fill-mask": EsmForMaskedLM, "text-classification": EsmForSequenceClassification, "token-classification": EsmForTokenClassification, "zero-shot": EsmForSequenceClassification, } if is_torch_available() else {} ) __UpperCamelCase : Union[str, Any] = True def __UpperCAmelCase ( self :Optional[int] ) -> int: '''simple docstring''' _a : Dict =EsmModelTester(self ) _a : Optional[Any] =ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , hidden_size=3_7 ) def __UpperCAmelCase ( self :Tuple ) -> List[Any]: '''simple docstring''' self.config_tester.run_common_tests() def __UpperCAmelCase ( self :Optional[int] ) -> str: '''simple docstring''' _a : List[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :List[Any] ) -> Dict: '''simple docstring''' _a : List[str] =self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: _a : Dict =type self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Dict ) -> List[str]: '''simple docstring''' _a : Tuple =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :List[Any] ) -> List[str]: '''simple docstring''' _a : str =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE ) @slow def __UpperCAmelCase ( self :str ) -> Dict: '''simple docstring''' for model_name in ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _a : Union[str, Any] =EsmModel.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Tuple ) -> int: '''simple docstring''' _a : Optional[Any] =self.model_tester.prepare_config_and_inputs()[0] _a : Dict =EsmEmbeddings(config=SCREAMING_SNAKE_CASE ) _a : Tuple =torch.as_tensor([[1_2, 3_1, 1_3, model.padding_idx]] ) _a : Optional[Any] =torch.as_tensor( [ [ 0 + model.padding_idx + 1, 1 + model.padding_idx + 1, 2 + model.padding_idx + 1, model.padding_idx, ] ] ) _a : Any =create_position_ids_from_input_ids(SCREAMING_SNAKE_CASE , model.padding_idx ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) ) def __UpperCAmelCase ( self :Optional[Any] ) -> Tuple: '''simple docstring''' _a : List[Any] =self.model_tester.prepare_config_and_inputs()[0] _a : Optional[int] =EsmEmbeddings(config=SCREAMING_SNAKE_CASE ) _a : Tuple =torch.empty(2 , 4 , 3_0 ) _a : str =[ 0 + embeddings.padding_idx + 1, 1 + embeddings.padding_idx + 1, 2 + embeddings.padding_idx + 1, 3 + embeddings.padding_idx + 1, ] _a : int =torch.as_tensor([expected_single_positions, expected_single_positions] ) _a : Any =embeddings.create_position_ids_from_inputs_embeds(SCREAMING_SNAKE_CASE ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) ) @unittest.skip("""Esm does not support embedding resizing""" ) def __UpperCAmelCase ( self :Tuple ) -> List[str]: '''simple docstring''' pass @unittest.skip("""Esm does not support embedding resizing""" ) def __UpperCAmelCase ( self :str ) -> Any: '''simple docstring''' pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def __UpperCAmelCase ( self :Dict ) -> Any: '''simple docstring''' pass @require_torch class A__ ( UpperCAmelCase__ ): @slow def __UpperCAmelCase ( self :List[Any] ) -> str: '''simple docstring''' with torch.no_grad(): _a : Optional[int] =EsmForMaskedLM.from_pretrained("""facebook/esm2_t6_8M_UR50D""" ) model.eval() _a : Any =torch.tensor([[0, 1, 2, 3, 4, 5]] ) _a : Tuple =model(SCREAMING_SNAKE_CASE )[0] _a : int =3_3 _a : Tuple =torch.Size((1, 6, vocab_size) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =torch.tensor( [[[8.9_215, -10.5_898, -6.4_671], [-6.3_967, -13.9_114, -1.1_212], [-7.7_812, -13.9_516, -3.7_406]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) ) @slow def __UpperCAmelCase ( self :Union[str, Any] ) -> Tuple: '''simple docstring''' with torch.no_grad(): _a : Any =EsmModel.from_pretrained("""facebook/esm2_t6_8M_UR50D""" ) model.eval() _a : Any =torch.tensor([[0, 6, 4, 1_3, 5, 4, 1_6, 1_2, 1_1, 7, 2]] ) _a : int =model(SCREAMING_SNAKE_CASE )[0] # compare the actual values for a slice. _a : str =torch.tensor( [[[0.1_444, 0.5_413, 0.3_248], [0.3_034, 0.0_053, 0.3_108], [0.3_228, -0.2_499, 0.3_415]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) )
276
1
'''simple docstring''' import argparse import collections import torch from flax import traverse_util from tax import checkpoints from transformers import TaConfig, TaEncoderModel, TaForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[str] ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : Tuple="attention" ) -> Union[str, Any]: _a : Optional[Any] =params[F"{prefix}/layers_{i}/{layer_name}/key/kernel"] _a : str =params[F"{prefix}/layers_{i}/{layer_name}/out/kernel"] _a : Tuple =params[F"{prefix}/layers_{i}/{layer_name}/query/kernel"] _a : Dict =params[F"{prefix}/layers_{i}/{layer_name}/value/kernel"] return k, o, q, v def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Any ,_UpperCAmelCase : int ,_UpperCAmelCase : List[Any] ,_UpperCAmelCase : Dict=False ) -> Optional[int]: if split_mlp_wi: _a : Any =params[F"{prefix}/layers_{i}/mlp/wi_0/kernel"] _a : List[str] =params[F"{prefix}/layers_{i}/mlp/wi_1/kernel"] _a : List[Any] =(wi_a, wi_a) else: _a : Optional[Any] =params[F"{prefix}/layers_{i}/mlp/wi/kernel"] _a : str =params[F"{prefix}/layers_{i}/mlp/wo/kernel"] return wi, wo def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Any ,_UpperCAmelCase : int ,_UpperCAmelCase : str ,_UpperCAmelCase : Dict ) -> Tuple: return params[F"{prefix}/layers_{i}/{layer_name}/scale"] def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : dict ,*, _UpperCAmelCase : int ,_UpperCAmelCase : bool ) -> Optional[int]: _a : Union[str, Any] =traverse_util.flatten_dict(variables["""target"""] ) _a : Tuple ={"""/""".join(_UpperCAmelCase ): v for k, v in old.items()} # v1.1 models have a gated GeLU with wi_0 and wi_1 instead of wi _a : List[str] ="""encoder/layers_0/mlp/wi_0/kernel""" in old print("""Split MLP:""" ,_UpperCAmelCase ) _a : List[Any] =collections.OrderedDict() # Shared embeddings. _a : Union[str, Any] =old["""token_embedder/embedding"""] # Encoder. for i in range(_UpperCAmelCase ): # Block i, layer 0 (Self Attention). _a : Optional[Any] =tax_layer_norm_lookup(_UpperCAmelCase ,_UpperCAmelCase ,"""encoder""" ,"""pre_attention_layer_norm""" ) _a , _a , _a , _a : Dict =tax_attention_lookup(_UpperCAmelCase ,_UpperCAmelCase ,"""encoder""" ,"""attention""" ) _a : List[str] =layer_norm _a : str =k.T _a : str =o.T _a : int =q.T _a : str =v.T # Block i, layer 1 (MLP). _a : List[Any] =tax_layer_norm_lookup(_UpperCAmelCase ,_UpperCAmelCase ,"""encoder""" ,"""pre_mlp_layer_norm""" ) _a , _a : int =tax_mlp_lookup(_UpperCAmelCase ,_UpperCAmelCase ,"""encoder""" ,_UpperCAmelCase ) _a : Union[str, Any] =layer_norm if split_mlp_wi: _a : List[str] =wi[0].T _a : Dict =wi[1].T else: _a : Any =wi.T _a : str =wo.T _a : List[str] =old[ """encoder/relpos_bias/rel_embedding""" ].T _a : List[str] =old["""encoder/encoder_norm/scale"""] if not is_encoder_only: # Decoder. for i in range(_UpperCAmelCase ): # Block i, layer 0 (Self Attention). _a : int =tax_layer_norm_lookup(_UpperCAmelCase ,_UpperCAmelCase ,"""decoder""" ,"""pre_self_attention_layer_norm""" ) _a , _a , _a , _a : Dict =tax_attention_lookup(_UpperCAmelCase ,_UpperCAmelCase ,"""decoder""" ,"""self_attention""" ) _a : Dict =layer_norm _a : List[Any] =k.T _a : Optional[Any] =o.T _a : Dict =q.T _a : List[Any] =v.T # Block i, layer 1 (Cross Attention). _a : str =tax_layer_norm_lookup(_UpperCAmelCase ,_UpperCAmelCase ,"""decoder""" ,"""pre_cross_attention_layer_norm""" ) _a , _a , _a , _a : List[str] =tax_attention_lookup(_UpperCAmelCase ,_UpperCAmelCase ,"""decoder""" ,"""encoder_decoder_attention""" ) _a : int =layer_norm _a : int =k.T _a : Any =o.T _a : Tuple =q.T _a : Tuple =v.T # Block i, layer 2 (MLP). _a : Dict =tax_layer_norm_lookup(_UpperCAmelCase ,_UpperCAmelCase ,"""decoder""" ,"""pre_mlp_layer_norm""" ) _a , _a : int =tax_mlp_lookup(_UpperCAmelCase ,_UpperCAmelCase ,"""decoder""" ,_UpperCAmelCase ) _a : List[str] =layer_norm if split_mlp_wi: _a : List[Any] =wi[0].T _a : List[Any] =wi[1].T else: _a : List[str] =wi.T _a : Optional[Any] =wo.T _a : Optional[int] =old["""decoder/decoder_norm/scale"""] _a : Any =old[ """decoder/relpos_bias/rel_embedding""" ].T # LM Head (only in v1.1 checkpoints, in v1.0 embeddings are used instead) if "decoder/logits_dense/kernel" in old: _a : Dict =old["""decoder/logits_dense/kernel"""].T return new def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Any ,_UpperCAmelCase : bool ) -> Optional[Any]: _a : Tuple =collections.OrderedDict([(k, torch.from_numpy(v.copy() )) for (k, v) in converted_params.items()] ) # Add what is missing. if "encoder.embed_tokens.weight" not in state_dict: _a : Union[str, Any] =state_dict["""shared.weight"""] if not is_encoder_only: if "decoder.embed_tokens.weight" not in state_dict: _a : Union[str, Any] =state_dict["""shared.weight"""] if "lm_head.weight" not in state_dict: # For old 1.0 models. print("""Using shared word embeddings as lm_head.""" ) _a : List[str] =state_dict["""shared.weight"""] return state_dict def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Any ,_UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : Optional[Any] ) -> Dict: _a : Dict =checkpoints.load_tax_checkpoint(_UpperCAmelCase ) _a : Optional[Any] =convert_tax_to_pytorch(_UpperCAmelCase ,num_layers=config.num_layers ,is_encoder_only=_UpperCAmelCase ) _a : str =make_state_dict(_UpperCAmelCase ,_UpperCAmelCase ) model.load_state_dict(_UpperCAmelCase ,strict=_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : Any ,_UpperCAmelCase : Dict ,_UpperCAmelCase : bool = False ) -> List[str]: _a : Tuple =TaConfig.from_json_file(_UpperCAmelCase ) print(F"Building PyTorch model from configuration: {config}" ) # Non-v1.1 checkpoints could also use T5Model, but this works for all. # The v1.0 checkpoints will simply have an LM head that is the word embeddings. if is_encoder_only: _a : int =TaEncoderModel(_UpperCAmelCase ) else: _a : Optional[int] =TaForConditionalGeneration(_UpperCAmelCase ) # Load weights from tf checkpoint load_tax_weights_in_ta(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) # Save pytorch-model print(F"Save PyTorch model to {pytorch_dump_path}" ) model.save_pretrained(_UpperCAmelCase ) # Verify that we can load the checkpoint. model.from_pretrained(_UpperCAmelCase ) print("""Done""" ) if __name__ == "__main__": A__: Dict = argparse.ArgumentParser(description='''Converts a native T5X checkpoint into a PyTorch checkpoint.''') # Required parameters parser.add_argument( '''--t5x_checkpoint_path''', default=None, type=str, required=True, help='''Path to the T5X checkpoint.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help='''The config json file corresponding to the pre-trained T5 model.\nThis specifies the model architecture.''', ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) parser.add_argument( '''--is_encoder_only''', action='''store_true''', help='''Check if the model is encoder-decoder model''', default=False ) A__: Optional[Any] = parser.parse_args() convert_tax_checkpoint_to_pytorch( args.tax_checkpoint_path, args.config_file, args.pytorch_dump_path, args.is_encoder_only )
276
'''simple docstring''' from math import isqrt def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ) -> bool: return all(number % divisor != 0 for divisor in range(2 ,isqrt(_UpperCAmelCase ) + 1 ) ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int = 10**6 ) -> int: _a : List[Any] =0 _a : str =1 _a : Optional[Any] =7 while prime_candidate < max_prime: primes_count += is_prime(_UpperCAmelCase ) cube_index += 1 prime_candidate += 6 * cube_index return primes_count if __name__ == "__main__": print(F"{solution() = }")
276
1
'''simple docstring''' import argparse import json import math import os import time import traceback import zipfile from collections import Counter import requests def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[str] ,_UpperCAmelCase : List[Any]=None ) -> List[str]: _a : Optional[Any] =None if token is not None: _a : Tuple ={"""Accept""": """application/vnd.github+json""", """Authorization""": F"Bearer {token}"} _a : List[Any] =F"https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100" _a : List[Any] =requests.get(_UpperCAmelCase ,headers=_UpperCAmelCase ).json() _a : Optional[Any] ={} try: job_links.update({job["""name"""]: job["""html_url"""] for job in result["""jobs"""]} ) _a : List[str] =math.ceil((result["""total_count"""] - 100) / 100 ) for i in range(_UpperCAmelCase ): _a : Optional[int] =requests.get(url + F"&page={i + 2}" ,headers=_UpperCAmelCase ).json() job_links.update({job["""name"""]: job["""html_url"""] for job in result["""jobs"""]} ) return job_links except Exception: print(F"Unknown error, could not fetch links:\n{traceback.format_exc()}" ) return {} def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Any ,_UpperCAmelCase : Tuple=None ) -> List[Any]: _a : Dict =None if token is not None: _a : Any ={"""Accept""": """application/vnd.github+json""", """Authorization""": F"Bearer {token}"} _a : Optional[Any] =F"https://api.github.com/repos/huggingface/transformers/actions/runs/{worflow_run_id}/artifacts?per_page=100" _a : Tuple =requests.get(_UpperCAmelCase ,headers=_UpperCAmelCase ).json() _a : List[str] ={} try: artifacts.update({artifact["""name"""]: artifact["""archive_download_url"""] for artifact in result["""artifacts"""]} ) _a : Union[str, Any] =math.ceil((result["""total_count"""] - 100) / 100 ) for i in range(_UpperCAmelCase ): _a : Union[str, Any] =requests.get(url + F"&page={i + 2}" ,headers=_UpperCAmelCase ).json() artifacts.update({artifact["""name"""]: artifact["""archive_download_url"""] for artifact in result["""artifacts"""]} ) return artifacts except Exception: print(F"Unknown error, could not fetch links:\n{traceback.format_exc()}" ) return {} def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Any ,_UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : Union[str, Any] ) -> Any: _a : Tuple =None if token is not None: _a : List[Any] ={"""Accept""": """application/vnd.github+json""", """Authorization""": F"Bearer {token}"} _a : str =requests.get(_UpperCAmelCase ,headers=_UpperCAmelCase ,allow_redirects=_UpperCAmelCase ) _a : Dict =result.headers["""Location"""] _a : Optional[int] =requests.get(_UpperCAmelCase ,allow_redirects=_UpperCAmelCase ) _a : str =os.path.join(_UpperCAmelCase ,F"{artifact_name}.zip" ) with open(_UpperCAmelCase ,"""wb""" ) as fp: fp.write(response.content ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : int=None ) -> str: _a : Optional[Any] =[] _a : List[Any] =[] _a : int =None with zipfile.ZipFile(_UpperCAmelCase ) as z: for filename in z.namelist(): if not os.path.isdir(_UpperCAmelCase ): # read the file if filename in ["failures_line.txt", "summary_short.txt", "job_name.txt"]: with z.open(_UpperCAmelCase ) as f: for line in f: _a : Any =line.decode("""UTF-8""" ).strip() if filename == "failures_line.txt": try: # `error_line` is the place where `error` occurs _a : Union[str, Any] =line[: line.index(""": """ )] _a : str =line[line.index(""": """ ) + len(""": """ ) :] errors.append([error_line, error] ) except Exception: # skip un-related lines pass elif filename == "summary_short.txt" and line.startswith("""FAILED """ ): # `test` is the test method that failed _a : List[Any] =line[len("""FAILED """ ) :] failed_tests.append(_UpperCAmelCase ) elif filename == "job_name.txt": _a : List[Any] =line if len(_UpperCAmelCase ) != len(_UpperCAmelCase ): raise ValueError( F"`errors` and `failed_tests` should have the same number of elements. Got {len(_UpperCAmelCase )} for `errors` " F"and {len(_UpperCAmelCase )} for `failed_tests` instead. The test reports in {artifact_zip_path} have some" """ problem.""" ) _a : int =None if job_name and job_links: _a : int =job_links.get(_UpperCAmelCase ,_UpperCAmelCase ) # A list with elements of the form (line of error, error, failed test) _a : Dict =[x + [y] + [job_link] for x, y in zip(_UpperCAmelCase ,_UpperCAmelCase )] return result def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Dict ,_UpperCAmelCase : Optional[Any]=None ) -> Dict: _a : List[Any] =[] _a : Union[str, Any] =[os.path.join(_UpperCAmelCase ,_UpperCAmelCase ) for p in os.listdir(_UpperCAmelCase ) if p.endswith(""".zip""" )] for p in paths: errors.extend(get_errors_from_single_artifact(_UpperCAmelCase ,job_links=_UpperCAmelCase ) ) return errors def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : Optional[Any]=None ) -> Tuple: _a : Tuple =Counter() counter.update([x[1] for x in logs] ) _a : int =counter.most_common() _a : List[str] ={} for error, count in counts: if error_filter is None or error not in error_filter: _a : List[Any] ={"""count""": count, """failed_tests""": [(x[2], x[0]) for x in logs if x[1] == error]} _a : Optional[Any] =dict(sorted(r.items() ,key=lambda _UpperCAmelCase : item[1]["count"] ,reverse=_UpperCAmelCase ) ) return r def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Union[str, Any] ) -> int: _a : Any =test.split("""::""" )[0] if test.startswith("""tests/models/""" ): _a : Optional[int] =test.split("""/""" )[2] else: _a : Any =None return test def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ,_UpperCAmelCase : List[Any]=None ) -> List[Any]: _a : int =[(x[0], x[1], get_model(x[2] )) for x in logs] _a : List[Any] =[x for x in logs if x[2] is not None] _a : List[str] ={x[2] for x in logs} _a : Any ={} for test in tests: _a : Tuple =Counter() # count by errors in `test` counter.update([x[1] for x in logs if x[2] == test] ) _a : Tuple =counter.most_common() _a : Optional[Any] ={error: count for error, count in counts if (error_filter is None or error not in error_filter)} _a : Any =sum(error_counts.values() ) if n_errors > 0: _a : List[str] ={"""count""": n_errors, """errors""": error_counts} _a : str =dict(sorted(r.items() ,key=lambda _UpperCAmelCase : item[1]["count"] ,reverse=_UpperCAmelCase ) ) return r def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[int] ) -> List[str]: _a : Optional[int] ="""| no. | error | status |""" _a : Tuple ="""|-:|:-|:-|""" _a : Dict =[header, sep] for error in reduced_by_error: _a : Optional[int] =reduced_by_error[error]["""count"""] _a : str =F"| {count} | {error[:100]} | |" lines.append(_UpperCAmelCase ) return "\n".join(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[Any] ) -> Dict: _a : Dict ="""| model | no. of errors | major error | count |""" _a : int ="""|-:|-:|-:|-:|""" _a : Tuple =[header, sep] for model in reduced_by_model: _a : int =reduced_by_model[model]["""count"""] _a , _a : int =list(reduced_by_model[model]["""errors"""].items() )[0] _a : Any =F"| {model} | {count} | {error[:60]} | {_count} |" lines.append(_UpperCAmelCase ) return "\n".join(_UpperCAmelCase ) if __name__ == "__main__": A__: Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument('''--workflow_run_id''', type=str, required=True, help='''A GitHub Actions workflow run id.''') parser.add_argument( '''--output_dir''', type=str, required=True, help='''Where to store the downloaded artifacts and other result files.''', ) parser.add_argument('''--token''', default=None, type=str, help='''A token that has actions:read permission.''') A__: List[Any] = parser.parse_args() os.makedirs(args.output_dir, exist_ok=True) A__: Any = get_job_links(args.workflow_run_id, token=args.token) A__: List[str] = {} # To deal with `workflow_call` event, where a job name is the combination of the job names in the caller and callee. # For example, `PyTorch 1.11 / Model tests (models/albert, single-gpu)`. if _job_links: for k, v in _job_links.items(): # This is how GitHub actions combine job names. if " / " in k: A__: Optional[int] = k.find(''' / ''') A__: Tuple = k[index + len(''' / ''') :] A__: Union[str, Any] = v with open(os.path.join(args.output_dir, '''job_links.json'''), '''w''', encoding='''UTF-8''') as fp: json.dump(job_links, fp, ensure_ascii=False, indent=4) A__: Dict = get_artifacts_links(args.workflow_run_id, token=args.token) with open(os.path.join(args.output_dir, '''artifacts.json'''), '''w''', encoding='''UTF-8''') as fp: json.dump(artifacts, fp, ensure_ascii=False, indent=4) for idx, (name, url) in enumerate(artifacts.items()): download_artifact(name, url, args.output_dir, args.token) # Be gentle to GitHub time.sleep(1) A__: Optional[int] = get_all_errors(args.output_dir, job_links=job_links) # `e[1]` is the error A__: Optional[Any] = Counter() counter.update([e[1] for e in errors]) # print the top 30 most common test errors A__: Tuple = counter.most_common(30) for item in most_common: print(item) with open(os.path.join(args.output_dir, '''errors.json'''), '''w''', encoding='''UTF-8''') as fp: json.dump(errors, fp, ensure_ascii=False, indent=4) A__: List[str] = reduce_by_error(errors) A__: Tuple = reduce_by_model(errors) A__: Optional[Any] = make_github_table(reduced_by_error) A__: Tuple = make_github_table_per_model(reduced_by_model) with open(os.path.join(args.output_dir, '''reduced_by_error.txt'''), '''w''', encoding='''UTF-8''') as fp: fp.write(sa) with open(os.path.join(args.output_dir, '''reduced_by_model.txt'''), '''w''', encoding='''UTF-8''') as fp: fp.write(sa)
276
'''simple docstring''' # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from ...utils import deprecate from ..controlnet.multicontrolnet import MultiControlNetModel # noqa: F401 from ..controlnet.pipeline_controlnet import StableDiffusionControlNetPipeline # noqa: F401 deprecate( '''stable diffusion controlnet''', '''0.22.0''', '''Importing `StableDiffusionControlNetPipeline` or `MultiControlNetModel` from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import StableDiffusionControlNetPipeline` instead.''', standard_warn=False, stacklevel=3, )
276
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A__: int = logging.get_logger(__name__) A__: Optional[int] = { '''funnel-transformer/small''': '''https://huggingface.co/funnel-transformer/small/resolve/main/config.json''', '''funnel-transformer/small-base''': '''https://huggingface.co/funnel-transformer/small-base/resolve/main/config.json''', '''funnel-transformer/medium''': '''https://huggingface.co/funnel-transformer/medium/resolve/main/config.json''', '''funnel-transformer/medium-base''': '''https://huggingface.co/funnel-transformer/medium-base/resolve/main/config.json''', '''funnel-transformer/intermediate''': ( '''https://huggingface.co/funnel-transformer/intermediate/resolve/main/config.json''' ), '''funnel-transformer/intermediate-base''': ( '''https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/config.json''' ), '''funnel-transformer/large''': '''https://huggingface.co/funnel-transformer/large/resolve/main/config.json''', '''funnel-transformer/large-base''': '''https://huggingface.co/funnel-transformer/large-base/resolve/main/config.json''', '''funnel-transformer/xlarge''': '''https://huggingface.co/funnel-transformer/xlarge/resolve/main/config.json''', '''funnel-transformer/xlarge-base''': '''https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/config.json''', } class A__ ( UpperCAmelCase__ ): __UpperCamelCase : Tuple = "funnel" __UpperCamelCase : Tuple = { "hidden_size": "d_model", "num_attention_heads": "n_head", } def __init__( self :str , SCREAMING_SNAKE_CASE :List[str]=3_0_5_2_2 , SCREAMING_SNAKE_CASE :Optional[int]=[4, 4, 4] , SCREAMING_SNAKE_CASE :List[str]=None , SCREAMING_SNAKE_CASE :int=2 , SCREAMING_SNAKE_CASE :int=7_6_8 , SCREAMING_SNAKE_CASE :Optional[int]=1_2 , SCREAMING_SNAKE_CASE :Optional[Any]=6_4 , SCREAMING_SNAKE_CASE :Dict=3_0_7_2 , SCREAMING_SNAKE_CASE :Any="gelu_new" , SCREAMING_SNAKE_CASE :Any=0.1 , SCREAMING_SNAKE_CASE :str=0.1 , SCREAMING_SNAKE_CASE :List[Any]=0.0 , SCREAMING_SNAKE_CASE :Dict=0.1 , SCREAMING_SNAKE_CASE :Any=None , SCREAMING_SNAKE_CASE :List[Any]=1e-9 , SCREAMING_SNAKE_CASE :Union[str, Any]="mean" , SCREAMING_SNAKE_CASE :Optional[int]="relative_shift" , SCREAMING_SNAKE_CASE :Tuple=True , SCREAMING_SNAKE_CASE :Union[str, Any]=True , SCREAMING_SNAKE_CASE :int=True , **SCREAMING_SNAKE_CASE :List[str] , ) -> Tuple: '''simple docstring''' _a : str =vocab_size _a : List[Any] =block_sizes _a : Tuple =[1] * len(SCREAMING_SNAKE_CASE ) if block_repeats is None else block_repeats assert len(SCREAMING_SNAKE_CASE ) == len( self.block_repeats ), "`block_sizes` and `block_repeats` should have the same length." _a : List[str] =num_decoder_layers _a : List[Any] =d_model _a : Tuple =n_head _a : str =d_head _a : int =d_inner _a : Optional[Any] =hidden_act _a : Optional[Any] =hidden_dropout _a : List[Any] =attention_dropout _a : int =activation_dropout _a : Optional[int] =initializer_range _a : str =initializer_std _a : Tuple =layer_norm_eps assert pooling_type in [ "mean", "max", ], f"Got {pooling_type} for `pooling_type` but only 'mean' and 'max' are supported." _a : int =pooling_type assert attention_type in [ "relative_shift", "factorized", ], f"Got {attention_type} for `attention_type` but only 'relative_shift' and 'factorized' are supported." _a : Optional[Any] =attention_type _a : Any =separate_cls _a : Optional[int] =truncate_seq _a : Dict =pool_q_only super().__init__(**SCREAMING_SNAKE_CASE ) @property def __UpperCAmelCase ( self :int ) -> Dict: '''simple docstring''' return sum(self.block_sizes ) @num_hidden_layers.setter def __UpperCAmelCase ( self :List[str] , SCREAMING_SNAKE_CASE :Any ) -> Optional[Any]: '''simple docstring''' raise NotImplementedError( """This model does not support the setting of `num_hidden_layers`. Please set `block_sizes`.""" ) @property def __UpperCAmelCase ( self :Tuple ) -> Any: '''simple docstring''' return len(self.block_sizes ) @num_blocks.setter def __UpperCAmelCase ( self :List[Any] , SCREAMING_SNAKE_CASE :Tuple ) -> Dict: '''simple docstring''' raise NotImplementedError("""This model does not support the setting of `num_blocks`. Please set `block_sizes`.""" )
276
'''simple docstring''' import pytest from datasets.utils.sharding import _distribute_shards, _number_of_shards_in_gen_kwargs, _split_gen_kwargs @pytest.mark.parametrize( """kwargs, expected""" ,[ ({"""num_shards""": 0, """max_num_jobs""": 1}, []), ({"""num_shards""": 10, """max_num_jobs""": 1}, [range(10 )]), ({"""num_shards""": 10, """max_num_jobs""": 10}, [range(_UpperCAmelCase ,i + 1 ) for i in range(10 )]), ({"""num_shards""": 1, """max_num_jobs""": 10}, [range(1 )]), ({"""num_shards""": 10, """max_num_jobs""": 3}, [range(0 ,4 ), range(4 ,7 ), range(7 ,10 )]), ({"""num_shards""": 3, """max_num_jobs""": 10}, [range(0 ,1 ), range(1 ,2 ), range(2 ,3 )]), ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : Dict ) -> Optional[Any]: _a : Tuple =_distribute_shards(**_UpperCAmelCase ) assert out == expected @pytest.mark.parametrize( """gen_kwargs, max_num_jobs, expected""" ,[ ({"""foo""": 0}, 10, [{"""foo""": 0}]), ({"""shards""": [0, 1, 2, 3]}, 1, [{"""shards""": [0, 1, 2, 3]}]), ({"""shards""": [0, 1, 2, 3]}, 4, [{"""shards""": [0]}, {"""shards""": [1]}, {"""shards""": [2]}, {"""shards""": [3]}]), ({"""shards""": [0, 1]}, 4, [{"""shards""": [0]}, {"""shards""": [1]}]), ({"""shards""": [0, 1, 2, 3]}, 2, [{"""shards""": [0, 1]}, {"""shards""": [2, 3]}]), ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : List[Any] ,_UpperCAmelCase : Union[str, Any] ) -> List[str]: _a : List[str] =_split_gen_kwargs(_UpperCAmelCase ,_UpperCAmelCase ) assert out == expected @pytest.mark.parametrize( """gen_kwargs, expected""" ,[ ({"""foo""": 0}, 1), ({"""shards""": [0]}, 1), ({"""shards""": [0, 1, 2, 3]}, 4), ({"""shards""": [0, 1, 2, 3], """foo""": 0}, 4), ({"""shards""": [0, 1, 2, 3], """other""": (0, 1)}, 4), ({"""shards""": [0, 1, 2, 3], """shards2""": [0, 1]}, RuntimeError), ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : List[Any] ) -> Union[str, Any]: if expected is RuntimeError: with pytest.raises(_UpperCAmelCase ): _number_of_shards_in_gen_kwargs(_UpperCAmelCase ) else: _a : Dict =_number_of_shards_in_gen_kwargs(_UpperCAmelCase ) assert out == expected
276
1
'''simple docstring''' A__: Tuple = ''' # Installazione di Transformers ! pip install transformers datasets # Per installare dalla fonte invece dell\'ultima versione rilasciata, commenta il comando sopra e # rimuovi la modalità commento al comando seguente. # ! pip install git+https://github.com/huggingface/transformers.git ''' A__: Tuple = [{'''type''': '''code''', '''content''': INSTALL_CONTENT}] A__: Any = { '''{processor_class}''': '''FakeProcessorClass''', '''{model_class}''': '''FakeModelClass''', '''{object_class}''': '''FakeObjectClass''', }
276
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A__: Dict = logging.get_logger(__name__) A__: Tuple = { '''weiweishi/roc-bert-base-zh''': '''https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json''', } class A__ ( UpperCAmelCase__ ): __UpperCamelCase : Tuple = "roc_bert" def __init__( self :Optional[int] , SCREAMING_SNAKE_CASE :Tuple=3_0_5_2_2 , SCREAMING_SNAKE_CASE :List[str]=7_6_8 , SCREAMING_SNAKE_CASE :Dict=1_2 , SCREAMING_SNAKE_CASE :List[str]=1_2 , SCREAMING_SNAKE_CASE :Tuple=3_0_7_2 , SCREAMING_SNAKE_CASE :List[Any]="gelu" , SCREAMING_SNAKE_CASE :Union[str, Any]=0.1 , SCREAMING_SNAKE_CASE :List[Any]=0.1 , SCREAMING_SNAKE_CASE :int=5_1_2 , SCREAMING_SNAKE_CASE :Optional[Any]=2 , SCREAMING_SNAKE_CASE :Union[str, Any]=0.02 , SCREAMING_SNAKE_CASE :Optional[Any]=1e-12 , SCREAMING_SNAKE_CASE :Any=True , SCREAMING_SNAKE_CASE :List[Any]=0 , SCREAMING_SNAKE_CASE :Optional[int]="absolute" , SCREAMING_SNAKE_CASE :Union[str, Any]=None , SCREAMING_SNAKE_CASE :List[Any]=True , SCREAMING_SNAKE_CASE :int=True , SCREAMING_SNAKE_CASE :Optional[int]=7_6_8 , SCREAMING_SNAKE_CASE :Optional[Any]=9_1_0 , SCREAMING_SNAKE_CASE :Union[str, Any]=5_1_2 , SCREAMING_SNAKE_CASE :str=2_4_8_5_8 , SCREAMING_SNAKE_CASE :List[Any]=True , **SCREAMING_SNAKE_CASE :Tuple , ) -> Optional[int]: '''simple docstring''' _a : List[str] =vocab_size _a : List[str] =max_position_embeddings _a : Optional[Any] =hidden_size _a : List[Any] =num_hidden_layers _a : List[str] =num_attention_heads _a : int =intermediate_size _a : Any =hidden_act _a : Dict =hidden_dropout_prob _a : int =attention_probs_dropout_prob _a : str =initializer_range _a : Optional[int] =type_vocab_size _a : Any =layer_norm_eps _a : Any =use_cache _a : Optional[int] =enable_pronunciation _a : Optional[Any] =enable_shape _a : Optional[Any] =pronunciation_embed_dim _a : Tuple =pronunciation_vocab_size _a : Union[str, Any] =shape_embed_dim _a : Any =shape_vocab_size _a : Tuple =concat_input _a : List[str] =position_embedding_type _a : List[str] =classifier_dropout super().__init__(pad_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE )
276
1
'''simple docstring''' import logging import os import random import sys from dataclasses import dataclass, field from typing import Optional import datasets import evaluate import numpy as np from datasets import load_dataset import transformers from transformers import ( AutoConfig, AutoModelForSequenceClassification, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, default_data_collator, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('''4.31.0''') require_version('''datasets>=1.8.0''', '''To fix: pip install -r examples/pytorch/text-classification/requirements.txt''') A__: str = logging.getLogger(__name__) @dataclass class A__ : __UpperCamelCase : Optional[int] = field( default=128 , metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) __UpperCamelCase : bool = field( default=UpperCAmelCase__ , metadata={"help": "Overwrite the cached preprocessed datasets or not."} ) __UpperCamelCase : bool = field( default=UpperCAmelCase__ , metadata={ "help": ( "Whether to pad all samples to `max_seq_length`. " "If False, will pad the samples dynamically when batching to the maximum length in the batch." ) } , ) __UpperCamelCase : Optional[int] = field( default=UpperCAmelCase__ , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) } , ) __UpperCamelCase : Optional[int] = field( default=UpperCAmelCase__ , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) } , ) __UpperCamelCase : Optional[int] = field( default=UpperCAmelCase__ , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of prediction examples to this " "value if set." ) } , ) @dataclass class A__ : __UpperCamelCase : str = field( default=UpperCAmelCase__ , metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) __UpperCamelCase : str = field( default=UpperCAmelCase__ , metadata={"help": "Evaluation language. Also train language if `train_language` is set to None."} ) __UpperCamelCase : Optional[str] = field( default=UpperCAmelCase__ , metadata={"help": "Train language if it is different from the evaluation language."} ) __UpperCamelCase : Optional[str] = field( default=UpperCAmelCase__ , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) __UpperCamelCase : Optional[str] = field( default=UpperCAmelCase__ , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) __UpperCamelCase : Optional[str] = field( default=UpperCAmelCase__ , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) __UpperCamelCase : Optional[bool] = field( default=UpperCAmelCase__ , metadata={"help": "arg to indicate if tokenizer should do lower case in AutoTokenizer.from_pretrained()"} , ) __UpperCamelCase : bool = field( default=UpperCAmelCase__ , metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."} , ) __UpperCamelCase : str = field( default="main" , metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} , ) __UpperCamelCase : bool = field( default=UpperCAmelCase__ , metadata={ "help": ( "Will use the token generated when running `huggingface-cli login` (necessary to use this script " "with private models)." ) } , ) __UpperCamelCase : bool = field( default=UpperCAmelCase__ , metadata={"help": "Will enable to load a pretrained model whose head dimensions are different."} , ) def SCREAMING_SNAKE_CASE_ ( ) -> Union[str, Any]: # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. _a : Optional[int] =HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) _a , _a , _a : List[Any] =parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry("""run_xnli""" ,_UpperCAmelCase ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" ,datefmt="""%m/%d/%Y %H:%M:%S""" ,handlers=[logging.StreamHandler(sys.stdout )] ,) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() _a : str =training_args.get_process_log_level() logger.setLevel(_UpperCAmelCase ) datasets.utils.logging.set_verbosity(_UpperCAmelCase ) transformers.utils.logging.set_verbosity(_UpperCAmelCase ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}" + F"distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}" ) logger.info(F"Training/evaluation parameters {training_args}" ) # Detecting last checkpoint. _a : Optional[int] =None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: _a : Optional[Any] =get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F"Output directory ({training_args.output_dir}) already exists and is not empty. " """Use --overwrite_output_dir to overcome.""" ) elif last_checkpoint is not None: logger.info( F"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change " """the `--output_dir` or add `--overwrite_output_dir` to train from scratch.""" ) # Set seed before initializing model. set_seed(training_args.seed ) # In distributed training, the load_dataset function guarantees that only one local process can concurrently # download the dataset. # Downloading and loading xnli dataset from the hub. if training_args.do_train: if model_args.train_language is None: _a : int =load_dataset( """xnli""" ,model_args.language ,split="""train""" ,cache_dir=model_args.cache_dir ,use_auth_token=True if model_args.use_auth_token else None ,) else: _a : Union[str, Any] =load_dataset( """xnli""" ,model_args.train_language ,split="""train""" ,cache_dir=model_args.cache_dir ,use_auth_token=True if model_args.use_auth_token else None ,) _a : Optional[int] =train_dataset.features["""label"""].names if training_args.do_eval: _a : Tuple =load_dataset( """xnli""" ,model_args.language ,split="""validation""" ,cache_dir=model_args.cache_dir ,use_auth_token=True if model_args.use_auth_token else None ,) _a : Union[str, Any] =eval_dataset.features["""label"""].names if training_args.do_predict: _a : int =load_dataset( """xnli""" ,model_args.language ,split="""test""" ,cache_dir=model_args.cache_dir ,use_auth_token=True if model_args.use_auth_token else None ,) _a : int =predict_dataset.features["""label"""].names # Labels _a : List[str] =len(_UpperCAmelCase ) # Load pretrained model and tokenizer # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. _a : List[Any] =AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path ,num_labels=_UpperCAmelCase ,idalabel={str(_UpperCAmelCase ): label for i, label in enumerate(_UpperCAmelCase )} ,labelaid={label: i for i, label in enumerate(_UpperCAmelCase )} ,finetuning_task="""xnli""" ,cache_dir=model_args.cache_dir ,revision=model_args.model_revision ,use_auth_token=True if model_args.use_auth_token else None ,) _a : int =AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path ,do_lower_case=model_args.do_lower_case ,cache_dir=model_args.cache_dir ,use_fast=model_args.use_fast_tokenizer ,revision=model_args.model_revision ,use_auth_token=True if model_args.use_auth_token else None ,) _a : Union[str, Any] =AutoModelForSequenceClassification.from_pretrained( model_args.model_name_or_path ,from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) ,config=_UpperCAmelCase ,cache_dir=model_args.cache_dir ,revision=model_args.model_revision ,use_auth_token=True if model_args.use_auth_token else None ,ignore_mismatched_sizes=model_args.ignore_mismatched_sizes ,) # Preprocessing the datasets # Padding strategy if data_args.pad_to_max_length: _a : int ="""max_length""" else: # We will pad later, dynamically at batch creation, to the max sequence length in each batch _a : List[Any] =False def preprocess_function(_UpperCAmelCase : Tuple ): # Tokenize the texts return tokenizer( examples["""premise"""] ,examples["""hypothesis"""] ,padding=_UpperCAmelCase ,max_length=data_args.max_seq_length ,truncation=_UpperCAmelCase ,) if training_args.do_train: if data_args.max_train_samples is not None: _a : Optional[Any] =min(len(_UpperCAmelCase ) ,data_args.max_train_samples ) _a : Any =train_dataset.select(range(_UpperCAmelCase ) ) with training_args.main_process_first(desc="""train dataset map pre-processing""" ): _a : str =train_dataset.map( _UpperCAmelCase ,batched=_UpperCAmelCase ,load_from_cache_file=not data_args.overwrite_cache ,desc="""Running tokenizer on train dataset""" ,) # Log a few random samples from the training set: for index in random.sample(range(len(_UpperCAmelCase ) ) ,3 ): logger.info(F"Sample {index} of the training set: {train_dataset[index]}." ) if training_args.do_eval: if data_args.max_eval_samples is not None: _a : Any =min(len(_UpperCAmelCase ) ,data_args.max_eval_samples ) _a : List[Any] =eval_dataset.select(range(_UpperCAmelCase ) ) with training_args.main_process_first(desc="""validation dataset map pre-processing""" ): _a : List[Any] =eval_dataset.map( _UpperCAmelCase ,batched=_UpperCAmelCase ,load_from_cache_file=not data_args.overwrite_cache ,desc="""Running tokenizer on validation dataset""" ,) if training_args.do_predict: if data_args.max_predict_samples is not None: _a : str =min(len(_UpperCAmelCase ) ,data_args.max_predict_samples ) _a : Union[str, Any] =predict_dataset.select(range(_UpperCAmelCase ) ) with training_args.main_process_first(desc="""prediction dataset map pre-processing""" ): _a : int =predict_dataset.map( _UpperCAmelCase ,batched=_UpperCAmelCase ,load_from_cache_file=not data_args.overwrite_cache ,desc="""Running tokenizer on prediction dataset""" ,) # Get the metric function _a : Optional[Any] =evaluate.load("""xnli""" ) # You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a # predictions and label_ids field) and has to return a dictionary string to float. def compute_metrics(_UpperCAmelCase : EvalPrediction ): _a : Optional[int] =p.predictions[0] if isinstance(p.predictions ,_UpperCAmelCase ) else p.predictions _a : List[str] =np.argmax(_UpperCAmelCase ,axis=1 ) return metric.compute(predictions=_UpperCAmelCase ,references=p.label_ids ) # Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding. if data_args.pad_to_max_length: _a : Union[str, Any] =default_data_collator elif training_args.fpaa: _a : Optional[Any] =DataCollatorWithPadding(_UpperCAmelCase ,pad_to_multiple_of=8 ) else: _a : Dict =None # Initialize our Trainer _a : Optional[int] =Trainer( model=_UpperCAmelCase ,args=_UpperCAmelCase ,train_dataset=train_dataset if training_args.do_train else None ,eval_dataset=eval_dataset if training_args.do_eval else None ,compute_metrics=_UpperCAmelCase ,tokenizer=_UpperCAmelCase ,data_collator=_UpperCAmelCase ,) # Training if training_args.do_train: _a : Tuple =None if training_args.resume_from_checkpoint is not None: _a : Tuple =training_args.resume_from_checkpoint elif last_checkpoint is not None: _a : Any =last_checkpoint _a : Optional[int] =trainer.train(resume_from_checkpoint=_UpperCAmelCase ) _a : Optional[int] =train_result.metrics _a : Optional[Any] =( data_args.max_train_samples if data_args.max_train_samples is not None else len(_UpperCAmelCase ) ) _a : Tuple =min(_UpperCAmelCase ,len(_UpperCAmelCase ) ) trainer.save_model() # Saves the tokenizer too for easy upload trainer.log_metrics("""train""" ,_UpperCAmelCase ) trainer.save_metrics("""train""" ,_UpperCAmelCase ) trainer.save_state() # Evaluation if training_args.do_eval: logger.info("""*** Evaluate ***""" ) _a : Optional[Any] =trainer.evaluate(eval_dataset=_UpperCAmelCase ) _a : List[Any] =data_args.max_eval_samples if data_args.max_eval_samples is not None else len(_UpperCAmelCase ) _a : Any =min(_UpperCAmelCase ,len(_UpperCAmelCase ) ) trainer.log_metrics("""eval""" ,_UpperCAmelCase ) trainer.save_metrics("""eval""" ,_UpperCAmelCase ) # Prediction if training_args.do_predict: logger.info("""*** Predict ***""" ) _a , _a , _a : Optional[Any] =trainer.predict(_UpperCAmelCase ,metric_key_prefix="""predict""" ) _a : Optional[Any] =( data_args.max_predict_samples if data_args.max_predict_samples is not None else len(_UpperCAmelCase ) ) _a : str =min(_UpperCAmelCase ,len(_UpperCAmelCase ) ) trainer.log_metrics("""predict""" ,_UpperCAmelCase ) trainer.save_metrics("""predict""" ,_UpperCAmelCase ) _a : int =np.argmax(_UpperCAmelCase ,axis=1 ) _a : Union[str, Any] =os.path.join(training_args.output_dir ,"""predictions.txt""" ) if trainer.is_world_process_zero(): with open(_UpperCAmelCase ,"""w""" ) as writer: writer.write("""index\tprediction\n""" ) for index, item in enumerate(_UpperCAmelCase ): _a : int =label_list[item] writer.write(F"{index}\t{item}\n" ) if __name__ == "__main__": main()
276
'''simple docstring''' class A__ : def __init__( self :List[str] ) -> List[Any]: '''simple docstring''' _a : Tuple =0 _a : Any =0 _a : int ={} def __UpperCAmelCase ( self :Any , SCREAMING_SNAKE_CASE :List[str] ) -> Optional[int]: '''simple docstring''' if vertex not in self.adjacency: _a : Dict ={} self.num_vertices += 1 def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Any ) -> List[str]: '''simple docstring''' self.add_vertex(SCREAMING_SNAKE_CASE ) self.add_vertex(SCREAMING_SNAKE_CASE ) if head == tail: return _a : Any =weight _a : Tuple =weight def __UpperCAmelCase ( self :Dict ) -> Optional[int]: '''simple docstring''' _a : Union[str, Any] =self.get_edges() for edge in edges: _a , _a , _a : List[str] =edge edges.remove((tail, head, weight) ) for i in range(len(SCREAMING_SNAKE_CASE ) ): _a : str =list(edges[i] ) edges.sort(key=lambda SCREAMING_SNAKE_CASE : e[2] ) for i in range(len(SCREAMING_SNAKE_CASE ) - 1 ): if edges[i][2] >= edges[i + 1][2]: _a : Union[str, Any] =edges[i][2] + 1 for edge in edges: _a , _a , _a : Tuple =edge _a : Tuple =weight _a : List[Any] =weight def __str__( self :int ) -> str: '''simple docstring''' _a : int ="""""" for tail in self.adjacency: for head in self.adjacency[tail]: _a : str =self.adjacency[head][tail] string += f"{head} -> {tail} == {weight}\n" return string.rstrip("""\n""" ) def __UpperCAmelCase ( self :Optional[int] ) -> Optional[Any]: '''simple docstring''' _a : Union[str, Any] =[] for tail in self.adjacency: for head in self.adjacency[tail]: output.append((tail, head, self.adjacency[head][tail]) ) return output def __UpperCAmelCase ( self :List[Any] ) -> List[Any]: '''simple docstring''' return self.adjacency.keys() @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :Dict=None , SCREAMING_SNAKE_CASE :List[Any]=None ) -> Optional[int]: '''simple docstring''' _a : str =Graph() if vertices is None: _a : Union[str, Any] =[] if edges is None: _a : List[Any] =[] for vertex in vertices: g.add_vertex(SCREAMING_SNAKE_CASE ) for edge in edges: g.add_edge(*SCREAMING_SNAKE_CASE ) return g class A__ : def __init__( self :Optional[int] ) -> Union[str, Any]: '''simple docstring''' _a : Optional[int] ={} _a : List[str] ={} def __len__( self :List[Any] ) -> List[Any]: '''simple docstring''' return len(self.parent ) def __UpperCAmelCase ( self :Tuple , SCREAMING_SNAKE_CASE :Tuple ) -> Dict: '''simple docstring''' if item in self.parent: return self.find(SCREAMING_SNAKE_CASE ) _a : Optional[Any] =item _a : List[str] =0 return item def __UpperCAmelCase ( self :int , SCREAMING_SNAKE_CASE :Dict ) -> List[str]: '''simple docstring''' if item not in self.parent: return self.make_set(SCREAMING_SNAKE_CASE ) if item != self.parent[item]: _a : str =self.find(self.parent[item] ) return self.parent[item] def __UpperCAmelCase ( self :Optional[int] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :List[Any] ) -> Optional[Any]: '''simple docstring''' _a : Optional[int] =self.find(SCREAMING_SNAKE_CASE ) _a : Dict =self.find(SCREAMING_SNAKE_CASE ) if roota == roota: return roota if self.rank[roota] > self.rank[roota]: _a : Any =roota return roota if self.rank[roota] < self.rank[roota]: _a : List[str] =roota return roota if self.rank[roota] == self.rank[roota]: self.rank[roota] += 1 _a : List[Any] =roota return roota return None @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :Dict ) -> Union[str, Any]: '''simple docstring''' _a : Any =graph.num_vertices _a : Union[str, Any] =Graph.UnionFind() _a : Optional[int] =[] while num_components > 1: _a : str ={} for vertex in graph.get_vertices(): _a : List[str] =-1 _a : Any =graph.get_edges() for edge in edges: _a , _a , _a : Tuple =edge edges.remove((tail, head, weight) ) for edge in edges: _a , _a , _a : Any =edge _a : Any =union_find.find(SCREAMING_SNAKE_CASE ) _a : List[Any] =union_find.find(SCREAMING_SNAKE_CASE ) if seta != seta: if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight: _a : Optional[int] =[head, tail, weight] if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight: _a : List[Any] =[head, tail, weight] for vertex in cheap_edge: if cheap_edge[vertex] != -1: _a , _a , _a : Optional[Any] =cheap_edge[vertex] if union_find.find(SCREAMING_SNAKE_CASE ) != union_find.find(SCREAMING_SNAKE_CASE ): union_find.union(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) mst_edges.append(cheap_edge[vertex] ) _a : str =num_components - 1 _a : str =Graph.build(edges=SCREAMING_SNAKE_CASE ) return mst
276
1
'''simple docstring''' import unittest import numpy as np from transformers import MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING, TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING from transformers.pipelines import AudioClassificationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_torchaudio, slow, ) from .test_pipelines_common import ANY @is_pipeline_test class A__ ( unittest.TestCase ): __UpperCamelCase : Tuple = MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING __UpperCamelCase : Any = TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING def __UpperCAmelCase ( self :Dict , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :Dict ) -> Any: '''simple docstring''' _a : Optional[Any] =AudioClassificationPipeline(model=SCREAMING_SNAKE_CASE , feature_extractor=SCREAMING_SNAKE_CASE ) # test with a raw waveform _a : List[Any] =np.zeros((3_4_0_0_0,) ) _a : Any =np.zeros((1_4_0_0_0,) ) return audio_classifier, [audioa, audio] def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :Union[str, Any] ) -> Optional[Any]: '''simple docstring''' _a , _a : List[Any] =examples _a : Dict =audio_classifier(SCREAMING_SNAKE_CASE ) # by default a model is initialized with num_labels=2 self.assertEqual( SCREAMING_SNAKE_CASE , [ {"""score""": ANY(SCREAMING_SNAKE_CASE ), """label""": ANY(SCREAMING_SNAKE_CASE )}, {"""score""": ANY(SCREAMING_SNAKE_CASE ), """label""": ANY(SCREAMING_SNAKE_CASE )}, ] , ) _a : List[str] =audio_classifier(SCREAMING_SNAKE_CASE , top_k=1 ) self.assertEqual( SCREAMING_SNAKE_CASE , [ {"""score""": ANY(SCREAMING_SNAKE_CASE ), """label""": ANY(SCREAMING_SNAKE_CASE )}, ] , ) self.run_torchaudio(SCREAMING_SNAKE_CASE ) @require_torchaudio def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :Optional[int] ) -> Optional[Any]: '''simple docstring''' import datasets # test with a local file _a : int =datasets.load_dataset("""hf-internal-testing/librispeech_asr_dummy""" , """clean""" , split="""validation""" ) _a : List[str] =dataset[0]["""audio"""]["""array"""] _a : List[Any] =audio_classifier(SCREAMING_SNAKE_CASE ) self.assertEqual( SCREAMING_SNAKE_CASE , [ {"""score""": ANY(SCREAMING_SNAKE_CASE ), """label""": ANY(SCREAMING_SNAKE_CASE )}, {"""score""": ANY(SCREAMING_SNAKE_CASE ), """label""": ANY(SCREAMING_SNAKE_CASE )}, ] , ) @require_torch def __UpperCAmelCase ( self :Tuple ) -> List[Any]: '''simple docstring''' _a : Tuple ="""anton-l/wav2vec2-random-tiny-classifier""" _a : str =pipeline("""audio-classification""" , model=SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =np.ones((8_0_0_0,) ) _a : List[str] =audio_classifier(SCREAMING_SNAKE_CASE , top_k=4 ) _a : Optional[Any] =[ {"""score""": 0.0_842, """label""": """no"""}, {"""score""": 0.0_838, """label""": """up"""}, {"""score""": 0.0_837, """label""": """go"""}, {"""score""": 0.0_834, """label""": """right"""}, ] _a : str =[ {"""score""": 0.0_845, """label""": """stop"""}, {"""score""": 0.0_844, """label""": """on"""}, {"""score""": 0.0_841, """label""": """right"""}, {"""score""": 0.0_834, """label""": """left"""}, ] self.assertIn(nested_simplify(SCREAMING_SNAKE_CASE , decimals=4 ) , [EXPECTED_OUTPUT, EXPECTED_OUTPUT_PT_2] ) _a : str ={"""array""": np.ones((8_0_0_0,) ), """sampling_rate""": audio_classifier.feature_extractor.sampling_rate} _a : int =audio_classifier(SCREAMING_SNAKE_CASE , top_k=4 ) self.assertIn(nested_simplify(SCREAMING_SNAKE_CASE , decimals=4 ) , [EXPECTED_OUTPUT, EXPECTED_OUTPUT_PT_2] ) @require_torch @slow def __UpperCAmelCase ( self :Any ) -> List[str]: '''simple docstring''' import datasets _a : Union[str, Any] ="""superb/wav2vec2-base-superb-ks""" _a : int =pipeline("""audio-classification""" , model=SCREAMING_SNAKE_CASE ) _a : Optional[Any] =datasets.load_dataset("""anton-l/superb_dummy""" , """ks""" , split="""test""" ) _a : List[str] =np.array(dataset[3]["""speech"""] , dtype=np.floataa ) _a : Union[str, Any] =audio_classifier(SCREAMING_SNAKE_CASE , top_k=4 ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE , decimals=3 ) , [ {"""score""": 0.981, """label""": """go"""}, {"""score""": 0.007, """label""": """up"""}, {"""score""": 0.006, """label""": """_unknown_"""}, {"""score""": 0.001, """label""": """down"""}, ] , ) @require_tf @unittest.skip("""Audio classification is not implemented for TF""" ) def __UpperCAmelCase ( self :Any ) -> Dict: '''simple docstring''' pass
276
'''simple docstring''' from datetime import datetime import requests from bsa import BeautifulSoup if __name__ == "__main__": A__: Union[str, Any] = input('''Enter image url: ''').strip() print(F"Downloading image from {url} ...") A__: Tuple = BeautifulSoup(requests.get(url).content, '''html.parser''') # The image URL is in the content field of the first meta tag with property og:image A__: Union[str, Any] = soup.find('''meta''', {'''property''': '''og:image'''})['''content'''] A__: List[Any] = requests.get(image_url).content A__: List[str] = F"{datetime.now():%Y-%m-%d_%H:%M:%S}.jpg" with open(file_name, '''wb''') as fp: fp.write(image_data) print(F"Done. Image saved to disk as {file_name}.")
276
1
'''simple docstring''' from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ShapEPipeline else: from .camera import create_pan_cameras from .pipeline_shap_e import ShapEPipeline from .pipeline_shap_e_img2img import ShapEImgaImgPipeline from .renderer import ( BoundingBoxVolume, ImportanceRaySampler, MLPNeRFModelOutput, MLPNeRSTFModel, ShapEParamsProjModel, ShapERenderer, StratifiedRaySampler, VoidNeRFModel, )
276
'''simple docstring''' A__: Tuple = ''' # Installazione di Transformers ! pip install transformers datasets # Per installare dalla fonte invece dell\'ultima versione rilasciata, commenta il comando sopra e # rimuovi la modalità commento al comando seguente. # ! pip install git+https://github.com/huggingface/transformers.git ''' A__: Tuple = [{'''type''': '''code''', '''content''': INSTALL_CONTENT}] A__: Any = { '''{processor_class}''': '''FakeProcessorClass''', '''{model_class}''': '''FakeModelClass''', '''{object_class}''': '''FakeObjectClass''', }
276
1
'''simple docstring''' from typing import Dict, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import flip_channel_order, resize, to_channel_dimension_format, to_pil_image from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_pytesseract_available, is_vision_available, logging, requires_backends if is_vision_available(): import PIL # soft dependency if is_pytesseract_available(): import pytesseract A__: Union[str, Any] = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : List[str] ) -> int: return [ int(1000 * (box[0] / width) ), int(1000 * (box[1] / height) ), int(1000 * (box[2] / width) ), int(1000 * (box[3] / height) ), ] def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : np.ndarray ,_UpperCAmelCase : Optional[str] ,_UpperCAmelCase : Optional[str] = None ) -> Optional[int]: _a : Any =tesseract_config if tesseract_config is not None else """""" # apply OCR _a : Optional[Any] =to_pil_image(_UpperCAmelCase ) _a , _a : List[Any] =pil_image.size _a : List[str] =pytesseract.image_to_data(_UpperCAmelCase ,lang=_UpperCAmelCase ,output_type="""dict""" ,config=_UpperCAmelCase ) _a , _a , _a , _a , _a : str =data["""text"""], data["""left"""], data["""top"""], data["""width"""], data["""height"""] # filter empty words and corresponding coordinates _a : Tuple =[idx for idx, word in enumerate(_UpperCAmelCase ) if not word.strip()] _a : List[Any] =[word for idx, word in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] _a : Dict =[coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] _a : List[str] =[coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] _a : Union[str, Any] =[coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] _a : Union[str, Any] =[coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] # turn coordinates into (left, top, left+width, top+height) format _a : List[str] =[] for x, y, w, h in zip(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ): _a : int =[x, y, x + w, y + h] actual_boxes.append(_UpperCAmelCase ) # finally, normalize the bounding boxes _a : str =[] for box in actual_boxes: normalized_boxes.append(normalize_box(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) ) assert len(_UpperCAmelCase ) == len(_UpperCAmelCase ), "Not as many words as there are bounding boxes" return words, normalized_boxes class A__ ( UpperCAmelCase__ ): __UpperCamelCase : List[Any] = ["pixel_values"] def __init__( self :Tuple , SCREAMING_SNAKE_CASE :bool = True , SCREAMING_SNAKE_CASE :Dict[str, int] = None , SCREAMING_SNAKE_CASE :PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE :bool = True , SCREAMING_SNAKE_CASE :Optional[str] = None , SCREAMING_SNAKE_CASE :Optional[str] = "" , **SCREAMING_SNAKE_CASE :Tuple , ) -> None: '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE ) _a : List[Any] =size if size is not None else {"""height""": 2_2_4, """width""": 2_2_4} _a : Tuple =get_size_dict(SCREAMING_SNAKE_CASE ) _a : Dict =do_resize _a : Tuple =size _a : str =resample _a : Dict =apply_ocr _a : Union[str, Any] =ocr_lang _a : Dict =tesseract_config def __UpperCAmelCase ( self :List[str] , SCREAMING_SNAKE_CASE :np.ndarray , SCREAMING_SNAKE_CASE :Dict[str, int] , SCREAMING_SNAKE_CASE :PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE :Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE :Dict , ) -> np.ndarray: '''simple docstring''' _a : int =get_size_dict(SCREAMING_SNAKE_CASE ) if "height" not in size or "width" not in size: raise ValueError(f"The size dictionary must contain the keys 'height' and 'width'. Got {size.keys()}" ) _a : Any =(size["""height"""], size["""width"""]) return resize(SCREAMING_SNAKE_CASE , size=SCREAMING_SNAKE_CASE , resample=SCREAMING_SNAKE_CASE , data_format=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Dict , SCREAMING_SNAKE_CASE :ImageInput , SCREAMING_SNAKE_CASE :bool = None , SCREAMING_SNAKE_CASE :Dict[str, int] = None , SCREAMING_SNAKE_CASE :PILImageResampling = None , SCREAMING_SNAKE_CASE :bool = None , SCREAMING_SNAKE_CASE :Optional[str] = None , SCREAMING_SNAKE_CASE :Optional[str] = None , SCREAMING_SNAKE_CASE :Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE :ChannelDimension = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE :Optional[Any] , ) -> PIL.Image.Image: '''simple docstring''' _a : Optional[int] =do_resize if do_resize is not None else self.do_resize _a : Optional[int] =size if size is not None else self.size _a : str =get_size_dict(SCREAMING_SNAKE_CASE ) _a : List[str] =resample if resample is not None else self.resample _a : int =apply_ocr if apply_ocr is not None else self.apply_ocr _a : str =ocr_lang if ocr_lang is not None else self.ocr_lang _a : Union[str, Any] =tesseract_config if tesseract_config is not None else self.tesseract_config _a : List[str] =make_list_of_images(SCREAMING_SNAKE_CASE ) if not valid_images(SCREAMING_SNAKE_CASE ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None: raise ValueError("""Size must be specified if do_resize is True.""" ) # All transformations expect numpy arrays. _a : List[Any] =[to_numpy_array(SCREAMING_SNAKE_CASE ) for image in images] if apply_ocr: requires_backends(self , """pytesseract""" ) _a : Any =[] _a : Any =[] for image in images: _a , _a : int =apply_tesseract(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) words_batch.append(SCREAMING_SNAKE_CASE ) boxes_batch.append(SCREAMING_SNAKE_CASE ) if do_resize: _a : Union[str, Any] =[self.resize(image=SCREAMING_SNAKE_CASE , size=SCREAMING_SNAKE_CASE , resample=SCREAMING_SNAKE_CASE ) for image in images] # flip color channels from RGB to BGR (as Detectron2 requires this) _a : Dict =[flip_channel_order(SCREAMING_SNAKE_CASE ) for image in images] _a : str =[to_channel_dimension_format(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for image in images] _a : str =BatchFeature(data={"""pixel_values""": images} , tensor_type=SCREAMING_SNAKE_CASE ) if apply_ocr: _a : List[Any] =words_batch _a : Dict =boxes_batch return data
276
'''simple docstring''' A__: Optional[int] = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] A__: Any = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] A__: int = { 0: '''Sunday''', 1: '''Monday''', 2: '''Tuesday''', 3: '''Wednesday''', 4: '''Thursday''', 5: '''Friday''', 6: '''Saturday''', } def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ,_UpperCAmelCase : int ,_UpperCAmelCase : int ) -> str: assert len(str(_UpperCAmelCase ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 12, "month should be between 1 to 12" assert 1 <= day <= 31, "day should be between 1 to 31" # Doomsday algorithm: _a : List[str] =year // 100 _a : List[str] =(5 * (century % 4) + 2) % 7 _a : Optional[int] =year % 100 _a : Any =centurian % 12 _a : int =( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 _a : Optional[Any] =( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 400) == 0) else DOOMSDAY_LEAP[month - 1] ) _a : str =(dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
276
1
'''simple docstring''' def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ,_UpperCAmelCase : int ,_UpperCAmelCase : int ) -> int: if exponent == 1: return base if exponent % 2 == 0: _a : Optional[int] =_modexpt(_UpperCAmelCase ,exponent // 2 ,_UpperCAmelCase ) % modulo_value return (x * x) % modulo_value else: return (base * _modexpt(_UpperCAmelCase ,exponent - 1 ,_UpperCAmelCase )) % modulo_value def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int = 1777 ,_UpperCAmelCase : int = 1855 ,_UpperCAmelCase : int = 8 ) -> int: _a : Tuple =base for _ in range(1 ,_UpperCAmelCase ): _a : Tuple =_modexpt(_UpperCAmelCase ,_UpperCAmelCase ,10**digits ) return result if __name__ == "__main__": print(F"{solution() = }")
276
'''simple docstring''' from __future__ import annotations from typing import TypedDict class A__ ( UpperCAmelCase__ ): __UpperCamelCase : str __UpperCamelCase : int def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ) -> list[str]: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError("""The parameter s type must be str.""" ) return [s[i:] + s[:i] for i in range(len(_UpperCAmelCase ) )] def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ) -> BWTTransformDict: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError("""The parameter s type must be str.""" ) if not s: raise ValueError("""The parameter s must not be empty.""" ) _a : List[Any] =all_rotations(_UpperCAmelCase ) rotations.sort() # sort the list of rotations in alphabetically order # make a string composed of the last char of each rotation _a : BWTTransformDict ={ "bwt_string": "".join([word[-1] for word in rotations] ), "idx_original_string": rotations.index(_UpperCAmelCase ), } return response def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : int ) -> str: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError("""The parameter bwt_string type must be str.""" ) if not bwt_string: raise ValueError("""The parameter bwt_string must not be empty.""" ) try: _a : List[str] =int(_UpperCAmelCase ) except ValueError: raise TypeError( """The parameter idx_original_string type must be int or passive""" """ of cast to int.""" ) if idx_original_string < 0: raise ValueError("""The parameter idx_original_string must not be lower than 0.""" ) if idx_original_string >= len(_UpperCAmelCase ): raise ValueError( """The parameter idx_original_string must be lower than""" """ len(bwt_string).""" ) _a : Optional[int] =[""""""] * len(_UpperCAmelCase ) for _ in range(len(_UpperCAmelCase ) ): for i in range(len(_UpperCAmelCase ) ): _a : int =bwt_string[i] + ordered_rotations[i] ordered_rotations.sort() return ordered_rotations[idx_original_string] if __name__ == "__main__": A__: Any = '''Provide a string that I will generate its BWT transform: ''' A__: Union[str, Any] = input(entry_msg).strip() A__: Optional[int] = bwt_transform(s) print( F"Burrows Wheeler transform for string '{s}' results " F"in '{result['bwt_string']}'" ) A__: Union[str, Any] = reverse_bwt(result['''bwt_string'''], result['''idx_original_string''']) print( F"Reversing Burrows Wheeler transform for entry '{result['bwt_string']}' " F"we get original string '{original_string}'" )
276
1
'''simple docstring''' import unittest from transformers import is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision, slow, torch_device if is_torch_available(): import torch from transformers import AutoModelForImageClassification if is_vision_available(): from transformers import AutoImageProcessor @require_torch @require_vision class A__ ( unittest.TestCase ): @slow def __UpperCAmelCase ( self :str ) -> Tuple: '''simple docstring''' _a : List[Any] =AutoImageProcessor.from_pretrained("""microsoft/dit-base-finetuned-rvlcdip""" ) _a : Any =AutoModelForImageClassification.from_pretrained("""microsoft/dit-base-finetuned-rvlcdip""" ) model.to(SCREAMING_SNAKE_CASE ) from datasets import load_dataset _a : int =load_dataset("""nielsr/rvlcdip-demo""" ) _a : Optional[Any] =dataset["""train"""][0]["""image"""].convert("""RGB""" ) _a : List[str] =image_processor(SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).to(SCREAMING_SNAKE_CASE ) # forward pass with torch.no_grad(): _a : Dict =model(**SCREAMING_SNAKE_CASE ) _a : Optional[int] =outputs.logits _a : List[Any] =torch.Size((1, 1_6) ) self.assertEqual(logits.shape , SCREAMING_SNAKE_CASE ) _a : int =torch.tensor( [-0.4_158, -0.4_092, -0.4_347] , device=SCREAMING_SNAKE_CASE , dtype=torch.float , ) self.assertTrue(torch.allclose(logits[0, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) )
276
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available A__: List[str] = { '''configuration_chinese_clip''': [ '''CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ChineseCLIPConfig''', '''ChineseCLIPOnnxConfig''', '''ChineseCLIPTextConfig''', '''ChineseCLIPVisionConfig''', ], '''processing_chinese_clip''': ['''ChineseCLIPProcessor'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Optional[int] = ['''ChineseCLIPFeatureExtractor'''] A__: Any = ['''ChineseCLIPImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Dict = [ '''CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ChineseCLIPModel''', '''ChineseCLIPPreTrainedModel''', '''ChineseCLIPTextModel''', '''ChineseCLIPVisionModel''', ] if TYPE_CHECKING: from .configuration_chinese_clip import ( CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, ChineseCLIPConfig, ChineseCLIPOnnxConfig, ChineseCLIPTextConfig, ChineseCLIPVisionConfig, ) from .processing_chinese_clip import ChineseCLIPProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_chinese_clip import ChineseCLIPFeatureExtractor, ChineseCLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_chinese_clip import ( CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, ChineseCLIPModel, ChineseCLIPPreTrainedModel, ChineseCLIPTextModel, ChineseCLIPVisionModel, ) else: import sys A__: str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
276
1
'''simple docstring''' from __future__ import annotations import requests def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ) -> dict: _a : Any =F"https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty" return requests.get(_UpperCAmelCase ).json() def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int = 10 ) -> list[dict]: _a : Union[str, Any] ="""https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty""" _a : int =requests.get(_UpperCAmelCase ).json()[:max_stories] return [get_hackernews_story(_UpperCAmelCase ) for story_id in story_ids] def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int = 10 ) -> str: _a : Union[str, Any] =hackernews_top_stories(_UpperCAmelCase ) return "\n".join("""* [{title}]({url})""".format(**_UpperCAmelCase ) for story in stories ) if __name__ == "__main__": print(hackernews_top_stories_as_markdown())
276
'''simple docstring''' class A__ : def __init__( self :List[Any] ) -> None: '''simple docstring''' _a : dict[str, TrieNode] ={} # Mapping from char to TrieNode _a : List[str] =False def __UpperCAmelCase ( self :Tuple , SCREAMING_SNAKE_CASE :list[str] ) -> None: '''simple docstring''' for word in words: self.insert(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :str ) -> None: '''simple docstring''' _a : str =self for char in word: if char not in curr.nodes: _a : Dict =TrieNode() _a : List[Any] =curr.nodes[char] _a : int =True def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :str ) -> bool: '''simple docstring''' _a : int =self for char in word: if char not in curr.nodes: return False _a : List[Any] =curr.nodes[char] return curr.is_leaf def __UpperCAmelCase ( self :Dict , SCREAMING_SNAKE_CASE :str ) -> None: '''simple docstring''' def _delete(SCREAMING_SNAKE_CASE :TrieNode , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :int ) -> bool: if index == len(SCREAMING_SNAKE_CASE ): # If word does not exist if not curr.is_leaf: return False _a : Any =False return len(curr.nodes ) == 0 _a : int =word[index] _a : int =curr.nodes.get(SCREAMING_SNAKE_CASE ) # If char not in current trie node if not char_node: return False # Flag to check if node can be deleted _a : List[Any] =_delete(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , index + 1 ) if delete_curr: del curr.nodes[char] return len(curr.nodes ) == 0 return delete_curr _delete(self , SCREAMING_SNAKE_CASE , 0 ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : TrieNode ,_UpperCAmelCase : str ) -> None: if node.is_leaf: print(_UpperCAmelCase ,end=""" """ ) for key, value in node.nodes.items(): print_words(_UpperCAmelCase ,word + key ) def SCREAMING_SNAKE_CASE_ ( ) -> bool: _a : List[str] ="""banana bananas bandana band apple all beast""".split() _a : List[Any] =TrieNode() root.insert_many(_UpperCAmelCase ) # print_words(root, "") assert all(root.find(_UpperCAmelCase ) for word in words ) assert root.find("""banana""" ) assert not root.find("""bandanas""" ) assert not root.find("""apps""" ) assert root.find("""apple""" ) assert root.find("""all""" ) root.delete("""all""" ) assert not root.find("""all""" ) root.delete("""banana""" ) assert not root.find("""banana""" ) assert root.find("""bananas""" ) return True def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : bool ) -> None: print(str(_UpperCAmelCase ) ,"""works!""" if passes else """doesn't work :(""" ) def SCREAMING_SNAKE_CASE_ ( ) -> None: assert test_trie() def SCREAMING_SNAKE_CASE_ ( ) -> None: print_results("""Testing trie functionality""" ,test_trie() ) if __name__ == "__main__": main()
276
1
'''simple docstring''' from __future__ import annotations def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : float ,_UpperCAmelCase : float ,_UpperCAmelCase : float ,) -> tuple: if (electron_conc, hole_conc, intrinsic_conc).count(0 ) != 1: raise ValueError("""You cannot supply more or less than 2 values""" ) elif electron_conc < 0: raise ValueError("""Electron concentration cannot be negative in a semiconductor""" ) elif hole_conc < 0: raise ValueError("""Hole concentration cannot be negative in a semiconductor""" ) elif intrinsic_conc < 0: raise ValueError( """Intrinsic concentration cannot be negative in a semiconductor""" ) elif electron_conc == 0: return ( "electron_conc", intrinsic_conc**2 / hole_conc, ) elif hole_conc == 0: return ( "hole_conc", intrinsic_conc**2 / electron_conc, ) elif intrinsic_conc == 0: return ( "intrinsic_conc", (electron_conc * hole_conc) ** 0.5, ) else: return (-1, -1) if __name__ == "__main__": import doctest doctest.testmod()
276
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available A__: str = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Tuple = ['''GPTSw3Tokenizer'''] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_swa import GPTSwaTokenizer else: import sys A__: str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
276
1
'''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 A__: str = 1.054571817E-34 # unit of ℏ : J * s A__: int = 3E8 # unit of c : m * s^-1 def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : float ,_UpperCAmelCase : float ,_UpperCAmelCase : float ) -> dict[str, float]: 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: _a : Optional[int] =(REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 * area) / ( 240 * (distance) ** 4 ) return {"force": force} elif area == 0: _a : Optional[Any] =(240 * force * (distance) ** 4) / ( REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 ) return {"area": area} elif distance == 0: _a : Union[str, Any] =( (REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 * area) / (240 * 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()
276
'''simple docstring''' import importlib.metadata import warnings from copy import deepcopy from packaging import version from ..utils import logging from .import_utils import is_accelerate_available, is_bitsandbytes_available if is_bitsandbytes_available(): import bitsandbytes as bnb import torch import torch.nn as nn from ..pytorch_utils import ConvaD if is_accelerate_available(): from accelerate import init_empty_weights from accelerate.utils import find_tied_parameters A__: str = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[Any] ,_UpperCAmelCase : List[str] ,_UpperCAmelCase : int ,_UpperCAmelCase : int=None ,_UpperCAmelCase : Optional[Any]=None ) -> Optional[Any]: # Recurse if needed if "." in tensor_name: _a : Union[str, Any] =tensor_name.split(""".""" ) for split in splits[:-1]: _a : Optional[Any] =getattr(_UpperCAmelCase ,_UpperCAmelCase ) if new_module is None: raise ValueError(F"{module} has no attribute {split}." ) _a : Optional[int] =new_module _a : Optional[int] =splits[-1] if tensor_name not in module._parameters and tensor_name not in module._buffers: raise ValueError(F"{module} does not have a parameter or a buffer named {tensor_name}." ) _a : Optional[Any] =tensor_name in module._buffers _a : str =getattr(_UpperCAmelCase ,_UpperCAmelCase ) if old_value.device == torch.device("""meta""" ) and device not in ["meta", torch.device("""meta""" )] and value is None: raise ValueError(F"{tensor_name} is on the meta device, we need a `value` to put in on {device}." ) _a : int =False _a : Tuple =False if is_buffer or not is_bitsandbytes_available(): _a : str =False _a : Optional[Any] =False else: _a : int =hasattr(bnb.nn ,"""Params4bit""" ) and isinstance(module._parameters[tensor_name] ,bnb.nn.Paramsabit ) _a : int =isinstance(module._parameters[tensor_name] ,bnb.nn.IntaParams ) if is_abit or is_abit: _a : Any =module._parameters[tensor_name] if param.device.type != "cuda": if value is None: _a : int =old_value.to(_UpperCAmelCase ) elif isinstance(_UpperCAmelCase ,torch.Tensor ): _a : str =value.to("""cpu""" ) if value.dtype == torch.inta: _a : int =version.parse(importlib.metadata.version("""bitsandbytes""" ) ) > version.parse( """0.37.2""" ) if not is_abit_serializable: raise ValueError( """Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. """ """Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`.""" ) else: _a : Dict =torch.tensor(_UpperCAmelCase ,device="""cpu""" ) # Support models using `Conv1D` in place of `nn.Linear` (e.g. gpt2) by transposing the weight matrix prior to quantization. # Since weights are saved in the correct "orientation", we skip transposing when loading. if issubclass(module.source_cls ,_UpperCAmelCase ) and fpaa_statistics is None: _a : int =new_value.T _a : Any =old_value.__dict__ if is_abit: _a : Any =bnb.nn.IntaParams(_UpperCAmelCase ,requires_grad=_UpperCAmelCase ,**_UpperCAmelCase ).to(_UpperCAmelCase ) elif is_abit: _a : Union[str, Any] =bnb.nn.Paramsabit(_UpperCAmelCase ,requires_grad=_UpperCAmelCase ,**_UpperCAmelCase ).to(_UpperCAmelCase ) _a : List[Any] =new_value if fpaa_statistics is not None: setattr(module.weight ,"""SCB""" ,fpaa_statistics.to(_UpperCAmelCase ) ) else: if value is None: _a : str =old_value.to(_UpperCAmelCase ) elif isinstance(_UpperCAmelCase ,torch.Tensor ): _a : Any =value.to(_UpperCAmelCase ) else: _a : str =torch.tensor(_UpperCAmelCase ,device=_UpperCAmelCase ) if is_buffer: _a : Optional[int] =new_value else: _a : Optional[Any] =nn.Parameter(_UpperCAmelCase ,requires_grad=old_value.requires_grad ) _a : Tuple =new_value def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : Union[str, Any]=None ,_UpperCAmelCase : List[Any]=None ,_UpperCAmelCase : str=None ,_UpperCAmelCase : Union[str, Any]=False ) -> Dict: for name, module in model.named_children(): if current_key_name is None: _a : Optional[int] =[] current_key_name.append(_UpperCAmelCase ) if (isinstance(_UpperCAmelCase ,nn.Linear ) or isinstance(_UpperCAmelCase ,_UpperCAmelCase )) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` if not any(key in """.""".join(_UpperCAmelCase ) for key in modules_to_not_convert ): with init_empty_weights(): if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): _a , _a : int =module.weight.shape else: _a : List[str] =module.in_features _a : Tuple =module.out_features if quantization_config.quantization_method() == "llm_int8": _a : Optional[Any] =bnb.nn.LinearabitLt( _UpperCAmelCase ,_UpperCAmelCase ,module.bias is not None ,has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight ,threshold=quantization_config.llm_inta_threshold ,) _a : Optional[Any] =True else: if ( quantization_config.llm_inta_skip_modules is not None and name in quantization_config.llm_inta_skip_modules ): pass else: _a : Dict =bnb.nn.Linearabit( _UpperCAmelCase ,_UpperCAmelCase ,module.bias is not None ,quantization_config.bnb_abit_compute_dtype ,compress_statistics=quantization_config.bnb_abit_use_double_quant ,quant_type=quantization_config.bnb_abit_quant_type ,) _a : List[Any] =True # Store the module class in case we need to transpose the weight later _a : int =type(_UpperCAmelCase ) # Force requires grad to False to avoid unexpected errors model._modules[name].requires_grad_(_UpperCAmelCase ) if len(list(module.children() ) ) > 0: _a , _a : List[Any] =_replace_with_bnb_linear( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,has_been_replaced=_UpperCAmelCase ,) # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : int=None ,_UpperCAmelCase : Union[str, Any]=None ,_UpperCAmelCase : Any=None ) -> Tuple: _a : Dict =["""lm_head"""] if modules_to_not_convert is None else modules_to_not_convert _a , _a : List[Any] =_replace_with_bnb_linear( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) if not has_been_replaced: logger.warning( """You are loading your model in 8bit or 4bit but no linear modules were found in your model.""" """ Please double check your model architecture, or submit an issue on github if you think this is""" """ a bug.""" ) return model def SCREAMING_SNAKE_CASE_ ( *_UpperCAmelCase : Any ,**_UpperCAmelCase : Any ) -> str: warnings.warn( """`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead""" ,_UpperCAmelCase ,) return replace_with_bnb_linear(*_UpperCAmelCase ,**_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( *_UpperCAmelCase : str ,**_UpperCAmelCase : Optional[int] ) -> Optional[int]: warnings.warn( """`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead""" ,_UpperCAmelCase ,) return set_module_quantized_tensor_to_device(*_UpperCAmelCase ,**_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ) -> Union[str, Any]: _a : Any =deepcopy(_UpperCAmelCase ) # this has 0 cost since it is done inside `init_empty_weights` context manager` tied_model.tie_weights() _a : List[Any] =find_tied_parameters(_UpperCAmelCase ) # For compatibility with Accelerate < 0.18 if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): _a : str =sum(list(tied_params.values() ) ,[] ) + list(tied_params.keys() ) else: _a : Optional[int] =sum(_UpperCAmelCase ,[] ) _a : List[Any] =len(_UpperCAmelCase ) > 0 # Check if it is a base model _a : Tuple =not hasattr(_UpperCAmelCase ,model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head _a : List[Any] =list(model.named_children() ) _a : Dict =[list_modules[-1][0]] # add last module together with tied weights _a : List[str] =set(_UpperCAmelCase ) - set(_UpperCAmelCase ) _a : str =list(set(_UpperCAmelCase ) ) + list(_UpperCAmelCase ) # remove ".weight" from the keys _a : List[Any] =[""".weight""", """.bias"""] _a : Any =[] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: _a : Any =name.replace(_UpperCAmelCase ,"""""" ) filtered_module_names.append(_UpperCAmelCase ) return filtered_module_names
276
1
'''simple docstring''' import importlib.metadata import warnings from copy import deepcopy from packaging import version from ..utils import logging from .import_utils import is_accelerate_available, is_bitsandbytes_available if is_bitsandbytes_available(): import bitsandbytes as bnb import torch import torch.nn as nn from ..pytorch_utils import ConvaD if is_accelerate_available(): from accelerate import init_empty_weights from accelerate.utils import find_tied_parameters A__: str = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[Any] ,_UpperCAmelCase : List[str] ,_UpperCAmelCase : int ,_UpperCAmelCase : int=None ,_UpperCAmelCase : Optional[Any]=None ) -> Optional[Any]: # Recurse if needed if "." in tensor_name: _a : Union[str, Any] =tensor_name.split(""".""" ) for split in splits[:-1]: _a : Optional[Any] =getattr(_UpperCAmelCase ,_UpperCAmelCase ) if new_module is None: raise ValueError(F"{module} has no attribute {split}." ) _a : Optional[int] =new_module _a : Optional[int] =splits[-1] if tensor_name not in module._parameters and tensor_name not in module._buffers: raise ValueError(F"{module} does not have a parameter or a buffer named {tensor_name}." ) _a : Optional[Any] =tensor_name in module._buffers _a : str =getattr(_UpperCAmelCase ,_UpperCAmelCase ) if old_value.device == torch.device("""meta""" ) and device not in ["meta", torch.device("""meta""" )] and value is None: raise ValueError(F"{tensor_name} is on the meta device, we need a `value` to put in on {device}." ) _a : int =False _a : Tuple =False if is_buffer or not is_bitsandbytes_available(): _a : str =False _a : Optional[Any] =False else: _a : int =hasattr(bnb.nn ,"""Params4bit""" ) and isinstance(module._parameters[tensor_name] ,bnb.nn.Paramsabit ) _a : int =isinstance(module._parameters[tensor_name] ,bnb.nn.IntaParams ) if is_abit or is_abit: _a : Any =module._parameters[tensor_name] if param.device.type != "cuda": if value is None: _a : int =old_value.to(_UpperCAmelCase ) elif isinstance(_UpperCAmelCase ,torch.Tensor ): _a : str =value.to("""cpu""" ) if value.dtype == torch.inta: _a : int =version.parse(importlib.metadata.version("""bitsandbytes""" ) ) > version.parse( """0.37.2""" ) if not is_abit_serializable: raise ValueError( """Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. """ """Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`.""" ) else: _a : Dict =torch.tensor(_UpperCAmelCase ,device="""cpu""" ) # Support models using `Conv1D` in place of `nn.Linear` (e.g. gpt2) by transposing the weight matrix prior to quantization. # Since weights are saved in the correct "orientation", we skip transposing when loading. if issubclass(module.source_cls ,_UpperCAmelCase ) and fpaa_statistics is None: _a : int =new_value.T _a : Any =old_value.__dict__ if is_abit: _a : Any =bnb.nn.IntaParams(_UpperCAmelCase ,requires_grad=_UpperCAmelCase ,**_UpperCAmelCase ).to(_UpperCAmelCase ) elif is_abit: _a : Union[str, Any] =bnb.nn.Paramsabit(_UpperCAmelCase ,requires_grad=_UpperCAmelCase ,**_UpperCAmelCase ).to(_UpperCAmelCase ) _a : List[Any] =new_value if fpaa_statistics is not None: setattr(module.weight ,"""SCB""" ,fpaa_statistics.to(_UpperCAmelCase ) ) else: if value is None: _a : str =old_value.to(_UpperCAmelCase ) elif isinstance(_UpperCAmelCase ,torch.Tensor ): _a : Any =value.to(_UpperCAmelCase ) else: _a : str =torch.tensor(_UpperCAmelCase ,device=_UpperCAmelCase ) if is_buffer: _a : Optional[int] =new_value else: _a : Optional[Any] =nn.Parameter(_UpperCAmelCase ,requires_grad=old_value.requires_grad ) _a : Tuple =new_value def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : Union[str, Any]=None ,_UpperCAmelCase : List[Any]=None ,_UpperCAmelCase : str=None ,_UpperCAmelCase : Union[str, Any]=False ) -> Dict: for name, module in model.named_children(): if current_key_name is None: _a : Optional[int] =[] current_key_name.append(_UpperCAmelCase ) if (isinstance(_UpperCAmelCase ,nn.Linear ) or isinstance(_UpperCAmelCase ,_UpperCAmelCase )) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` if not any(key in """.""".join(_UpperCAmelCase ) for key in modules_to_not_convert ): with init_empty_weights(): if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): _a , _a : int =module.weight.shape else: _a : List[str] =module.in_features _a : Tuple =module.out_features if quantization_config.quantization_method() == "llm_int8": _a : Optional[Any] =bnb.nn.LinearabitLt( _UpperCAmelCase ,_UpperCAmelCase ,module.bias is not None ,has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight ,threshold=quantization_config.llm_inta_threshold ,) _a : Optional[Any] =True else: if ( quantization_config.llm_inta_skip_modules is not None and name in quantization_config.llm_inta_skip_modules ): pass else: _a : Dict =bnb.nn.Linearabit( _UpperCAmelCase ,_UpperCAmelCase ,module.bias is not None ,quantization_config.bnb_abit_compute_dtype ,compress_statistics=quantization_config.bnb_abit_use_double_quant ,quant_type=quantization_config.bnb_abit_quant_type ,) _a : List[Any] =True # Store the module class in case we need to transpose the weight later _a : int =type(_UpperCAmelCase ) # Force requires grad to False to avoid unexpected errors model._modules[name].requires_grad_(_UpperCAmelCase ) if len(list(module.children() ) ) > 0: _a , _a : List[Any] =_replace_with_bnb_linear( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,has_been_replaced=_UpperCAmelCase ,) # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : int=None ,_UpperCAmelCase : Union[str, Any]=None ,_UpperCAmelCase : Any=None ) -> Tuple: _a : Dict =["""lm_head"""] if modules_to_not_convert is None else modules_to_not_convert _a , _a : List[Any] =_replace_with_bnb_linear( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) if not has_been_replaced: logger.warning( """You are loading your model in 8bit or 4bit but no linear modules were found in your model.""" """ Please double check your model architecture, or submit an issue on github if you think this is""" """ a bug.""" ) return model def SCREAMING_SNAKE_CASE_ ( *_UpperCAmelCase : Any ,**_UpperCAmelCase : Any ) -> str: warnings.warn( """`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead""" ,_UpperCAmelCase ,) return replace_with_bnb_linear(*_UpperCAmelCase ,**_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( *_UpperCAmelCase : str ,**_UpperCAmelCase : Optional[int] ) -> Optional[int]: warnings.warn( """`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead""" ,_UpperCAmelCase ,) return set_module_quantized_tensor_to_device(*_UpperCAmelCase ,**_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ) -> Union[str, Any]: _a : Any =deepcopy(_UpperCAmelCase ) # this has 0 cost since it is done inside `init_empty_weights` context manager` tied_model.tie_weights() _a : List[Any] =find_tied_parameters(_UpperCAmelCase ) # For compatibility with Accelerate < 0.18 if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): _a : str =sum(list(tied_params.values() ) ,[] ) + list(tied_params.keys() ) else: _a : Optional[int] =sum(_UpperCAmelCase ,[] ) _a : List[Any] =len(_UpperCAmelCase ) > 0 # Check if it is a base model _a : Tuple =not hasattr(_UpperCAmelCase ,model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head _a : List[Any] =list(model.named_children() ) _a : Dict =[list_modules[-1][0]] # add last module together with tied weights _a : List[str] =set(_UpperCAmelCase ) - set(_UpperCAmelCase ) _a : str =list(set(_UpperCAmelCase ) ) + list(_UpperCAmelCase ) # remove ".weight" from the keys _a : List[Any] =[""".weight""", """.bias"""] _a : Any =[] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: _a : Any =name.replace(_UpperCAmelCase ,"""""" ) filtered_module_names.append(_UpperCAmelCase ) return filtered_module_names
276
'''simple docstring''' import logging import os from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union from filelock import FileLock from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available A__: int = logging.getLogger(__name__) @dataclass class A__ : __UpperCamelCase : str __UpperCamelCase : List[str] __UpperCamelCase : Optional[List[str]] @dataclass class A__ : __UpperCamelCase : List[int] __UpperCamelCase : List[int] __UpperCamelCase : Optional[List[int]] = None __UpperCamelCase : Optional[List[int]] = None class A__ ( UpperCAmelCase__ ): __UpperCamelCase : str = "train" __UpperCamelCase : Tuple = "dev" __UpperCamelCase : str = "test" class A__ : @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :Union[Split, str] ) -> List[InputExample]: '''simple docstring''' raise NotImplementedError @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :str ) -> List[str]: '''simple docstring''' raise NotImplementedError @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :List[InputExample] , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :PreTrainedTokenizer , SCREAMING_SNAKE_CASE :str=False , SCREAMING_SNAKE_CASE :Optional[Any]="[CLS]" , SCREAMING_SNAKE_CASE :Optional[int]=1 , SCREAMING_SNAKE_CASE :Any="[SEP]" , SCREAMING_SNAKE_CASE :List[Any]=False , SCREAMING_SNAKE_CASE :Union[str, Any]=False , SCREAMING_SNAKE_CASE :List[str]=0 , SCREAMING_SNAKE_CASE :str=0 , SCREAMING_SNAKE_CASE :Dict=-1_0_0 , SCREAMING_SNAKE_CASE :Optional[int]=0 , SCREAMING_SNAKE_CASE :Tuple=True , ) -> List[InputFeatures]: '''simple docstring''' _a : str ={label: i for i, label in enumerate(SCREAMING_SNAKE_CASE )} _a : Tuple =[] for ex_index, example in enumerate(SCREAMING_SNAKE_CASE ): if ex_index % 1_0_0_0_0 == 0: logger.info("""Writing example %d of %d""" , SCREAMING_SNAKE_CASE , len(SCREAMING_SNAKE_CASE ) ) _a : Optional[Any] =[] _a : List[Any] =[] for word, label in zip(example.words , example.labels ): _a : Optional[int] =tokenizer.tokenize(SCREAMING_SNAKE_CASE ) # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space. if len(SCREAMING_SNAKE_CASE ) > 0: tokens.extend(SCREAMING_SNAKE_CASE ) # Use the real label id for the first token of the word, and padding ids for the remaining tokens label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(SCREAMING_SNAKE_CASE ) - 1) ) # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa. _a : Optional[int] =tokenizer.num_special_tokens_to_add() if len(SCREAMING_SNAKE_CASE ) > max_seq_length - special_tokens_count: _a : List[Any] =tokens[: (max_seq_length - special_tokens_count)] _a : Tuple =label_ids[: (max_seq_length - special_tokens_count)] # The convention in BERT is: # (a) For sequence pairs: # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP] # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1 # (b) For single sequences: # tokens: [CLS] the dog is hairy . [SEP] # type_ids: 0 0 0 0 0 0 0 # # Where "type_ids" are used to indicate whether this is the first # sequence or the second sequence. The embedding vectors for `type=0` and # `type=1` were learned during pre-training and are added to the wordpiece # embedding vector (and position vector). This is not *strictly* necessary # since the [SEP] token unambiguously separates the sequences, but it makes # it easier for the model to learn the concept of sequences. # # For classification tasks, the first vector (corresponding to [CLS]) is # used as the "sentence vector". Note that this only makes sense because # the entire model is fine-tuned. tokens += [sep_token] label_ids += [pad_token_label_id] if sep_token_extra: # roberta uses an extra separator b/w pairs of sentences tokens += [sep_token] label_ids += [pad_token_label_id] _a : Dict =[sequence_a_segment_id] * len(SCREAMING_SNAKE_CASE ) if cls_token_at_end: tokens += [cls_token] label_ids += [pad_token_label_id] segment_ids += [cls_token_segment_id] else: _a : Any =[cls_token] + tokens _a : Dict =[pad_token_label_id] + label_ids _a : Union[str, Any] =[cls_token_segment_id] + segment_ids _a : List[str] =tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE ) # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. _a : Optional[int] =[1 if mask_padding_with_zero else 0] * len(SCREAMING_SNAKE_CASE ) # Zero-pad up to the sequence length. _a : Union[str, Any] =max_seq_length - len(SCREAMING_SNAKE_CASE ) if pad_on_left: _a : Optional[Any] =([pad_token] * padding_length) + input_ids _a : Optional[int] =([0 if mask_padding_with_zero else 1] * padding_length) + input_mask _a : Union[str, Any] =([pad_token_segment_id] * padding_length) + segment_ids _a : Dict =([pad_token_label_id] * padding_length) + label_ids else: input_ids += [pad_token] * padding_length input_mask += [0 if mask_padding_with_zero else 1] * padding_length segment_ids += [pad_token_segment_id] * padding_length label_ids += [pad_token_label_id] * padding_length assert len(SCREAMING_SNAKE_CASE ) == max_seq_length assert len(SCREAMING_SNAKE_CASE ) == max_seq_length assert len(SCREAMING_SNAKE_CASE ) == max_seq_length assert len(SCREAMING_SNAKE_CASE ) == max_seq_length if ex_index < 5: logger.info("""*** Example ***""" ) logger.info("""guid: %s""" , example.guid ) logger.info("""tokens: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in tokens] ) ) logger.info("""input_ids: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in input_ids] ) ) logger.info("""input_mask: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in input_mask] ) ) logger.info("""segment_ids: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in segment_ids] ) ) logger.info("""label_ids: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in label_ids] ) ) if "token_type_ids" not in tokenizer.model_input_names: _a : Tuple =None features.append( InputFeatures( input_ids=SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , token_type_ids=SCREAMING_SNAKE_CASE , label_ids=SCREAMING_SNAKE_CASE ) ) return features if is_torch_available(): import torch from torch import nn from torch.utils.data import Dataset class A__ ( UpperCAmelCase__ ): __UpperCamelCase : List[InputFeatures] __UpperCamelCase : int = nn.CrossEntropyLoss().ignore_index def __init__( self :Dict , SCREAMING_SNAKE_CASE :TokenClassificationTask , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :PreTrainedTokenizer , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Optional[int] = None , SCREAMING_SNAKE_CASE :int=False , SCREAMING_SNAKE_CASE :Split = Split.train , ) -> List[str]: '''simple docstring''' # Load data features from cache or dataset file _a : Optional[Any] =os.path.join( SCREAMING_SNAKE_CASE , """cached_{}_{}_{}""".format(mode.value , tokenizer.__class__.__name__ , str(SCREAMING_SNAKE_CASE ) ) , ) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. _a : List[str] =cached_features_file + """.lock""" with FileLock(SCREAMING_SNAKE_CASE ): if os.path.exists(SCREAMING_SNAKE_CASE ) and not overwrite_cache: logger.info(f"Loading features from cached file {cached_features_file}" ) _a : Any =torch.load(SCREAMING_SNAKE_CASE ) else: logger.info(f"Creating features from dataset file at {data_dir}" ) _a : Any =token_classification_task.read_examples_from_file(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # TODO clean up all this to leverage built-in features of tokenizers _a : List[str] =token_classification_task.convert_examples_to_features( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cls_token_at_end=bool(model_type in ["""xlnet"""] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ["""xlnet"""] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=SCREAMING_SNAKE_CASE , pad_on_left=bool(tokenizer.padding_side == """left""" ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info(f"Saving features into cached file {cached_features_file}" ) torch.save(self.features , SCREAMING_SNAKE_CASE ) def __len__( self :Optional[int] ) -> Union[str, Any]: '''simple docstring''' return len(self.features ) def __getitem__( self :Dict , SCREAMING_SNAKE_CASE :int ) -> InputFeatures: '''simple docstring''' return self.features[i] if is_tf_available(): import tensorflow as tf class A__ : __UpperCamelCase : List[InputFeatures] __UpperCamelCase : int = -100 def __init__( self :str , SCREAMING_SNAKE_CASE :TokenClassificationTask , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :PreTrainedTokenizer , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Optional[int] = None , SCREAMING_SNAKE_CASE :str=False , SCREAMING_SNAKE_CASE :Split = Split.train , ) -> Any: '''simple docstring''' _a : Tuple =token_classification_task.read_examples_from_file(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # TODO clean up all this to leverage built-in features of tokenizers _a : List[Any] =token_classification_task.convert_examples_to_features( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cls_token_at_end=bool(model_type in ["""xlnet"""] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ["""xlnet"""] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=SCREAMING_SNAKE_CASE , pad_on_left=bool(tokenizer.padding_side == """left""" ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) def gen(): for ex in self.features: if ex.token_type_ids is None: yield ( {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label_ids, ) else: yield ( { "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label_ids, ) if "token_type_ids" not in tokenizer.model_input_names: _a : Union[str, Any] =tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE , ({"""input_ids""": tf.intaa, """attention_mask""": tf.intaa}, tf.intaa) , ( {"""input_ids""": tf.TensorShape([None] ), """attention_mask""": tf.TensorShape([None] )}, tf.TensorShape([None] ), ) , ) else: _a : Union[str, Any] =tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE , ({"""input_ids""": tf.intaa, """attention_mask""": tf.intaa, """token_type_ids""": tf.intaa}, tf.intaa) , ( { """input_ids""": tf.TensorShape([None] ), """attention_mask""": tf.TensorShape([None] ), """token_type_ids""": tf.TensorShape([None] ), }, tf.TensorShape([None] ), ) , ) def __UpperCAmelCase ( self :Tuple ) -> Any: '''simple docstring''' _a : List[Any] =self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features ) ) ) return self.dataset def __len__( self :str ) -> Optional[int]: '''simple docstring''' return len(self.features ) def __getitem__( self :int , SCREAMING_SNAKE_CASE :str ) -> InputFeatures: '''simple docstring''' return self.features[i]
276
1
'''simple docstring''' def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ) -> int: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): _a : int =F"Input value of [number={number}] must be an integer" raise TypeError(_UpperCAmelCase ) if number < 1: _a : Optional[int] =F"Input value of [number={number}] must be > 0" raise ValueError(_UpperCAmelCase ) _a : Tuple =1 for i in range(1 ,_UpperCAmelCase ): current_number *= 4 * i - 2 current_number //= i + 1 return current_number if __name__ == "__main__": import doctest doctest.testmod()
276
'''simple docstring''' from __future__ import annotations class A__ : def __init__( self :Union[str, Any] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :str ) -> Optional[int]: '''simple docstring''' _a , _a : List[str] =text, pattern _a , _a : Union[str, Any] =len(SCREAMING_SNAKE_CASE ), len(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Optional[int] , SCREAMING_SNAKE_CASE :str ) -> int: '''simple docstring''' for i in range(self.patLen - 1 , -1 , -1 ): if char == self.pattern[i]: return i return -1 def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :int ) -> int: '''simple docstring''' for i in range(self.patLen - 1 , -1 , -1 ): if self.pattern[i] != self.text[current_pos + i]: return current_pos + i return -1 def __UpperCAmelCase ( self :Union[str, Any] ) -> list[int]: '''simple docstring''' # searches pattern in text and returns index positions _a : Union[str, Any] =[] for i in range(self.textLen - self.patLen + 1 ): _a : Any =self.mismatch_in_text(SCREAMING_SNAKE_CASE ) if mismatch_index == -1: positions.append(SCREAMING_SNAKE_CASE ) else: _a : int =self.match_in_pattern(self.text[mismatch_index] ) _a : List[str] =( mismatch_index - match_index ) # shifting index lgtm [py/multiple-definition] return positions A__: Any = '''ABAABA''' A__: int = '''AB''' A__: Optional[int] = BoyerMooreSearch(text, pattern) A__: Optional[Any] = bms.bad_character_heuristic() if len(positions) == 0: print('''No match found''') else: print('''Pattern found in following positions: ''') print(positions)
276
1
'''simple docstring''' # This code is adapted from OpenAI's release # https://github.com/openai/human-eval/blob/master/human_eval/execution.py import contextlib import faulthandler import io import multiprocessing import os import platform import signal import tempfile def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : int ,_UpperCAmelCase : Union[str, Any] ) -> Tuple: _a : int =multiprocessing.Manager() _a : Optional[Any] =manager.list() _a : Optional[int] =multiprocessing.Process(target=_UpperCAmelCase ,args=(check_program, result, timeout) ) p.start() p.join(timeout=timeout + 1 ) if p.is_alive(): p.kill() if not result: result.append("""timed out""" ) return { "task_id": task_id, "passed": result[0] == "passed", "result": result[0], "completion_id": completion_id, } def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : List[Any] ,_UpperCAmelCase : Optional[Any] ) -> Optional[Any]: with create_tempdir(): # These system calls are needed when cleaning up tempdir. import os import shutil _a : str =shutil.rmtree _a : str =os.rmdir _a : List[Any] =os.chdir # Disable functionalities that can make destructive changes to the test. reliability_guard() # Run program. try: _a : int ={} with swallow_io(): with time_limit(_UpperCAmelCase ): exec(_UpperCAmelCase ,_UpperCAmelCase ) result.append("""passed""" ) except TimeoutException: result.append("""timed out""" ) except BaseException as e: result.append(F"failed: {e}" ) # Needed for cleaning up. _a : Union[str, Any] =rmtree _a : Any =rmdir _a : Union[str, Any] =chdir @contextlib.contextmanager def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Dict ) -> Any: def signal_handler(_UpperCAmelCase : Tuple ,_UpperCAmelCase : Union[str, Any] ): raise TimeoutException("""Timed out!""" ) signal.setitimer(signal.ITIMER_REAL ,_UpperCAmelCase ) signal.signal(signal.SIGALRM ,_UpperCAmelCase ) try: yield finally: signal.setitimer(signal.ITIMER_REAL ,0 ) @contextlib.contextmanager def SCREAMING_SNAKE_CASE_ ( ) -> Dict: _a : Any =WriteOnlyStringIO() with contextlib.redirect_stdout(_UpperCAmelCase ): with contextlib.redirect_stderr(_UpperCAmelCase ): with redirect_stdin(_UpperCAmelCase ): yield @contextlib.contextmanager def SCREAMING_SNAKE_CASE_ ( ) -> str: with tempfile.TemporaryDirectory() as dirname: with chdir(_UpperCAmelCase ): yield dirname class A__ ( UpperCAmelCase__ ): pass class A__ ( io.StringIO ): def __UpperCAmelCase ( self :List[Any] , *SCREAMING_SNAKE_CASE :int , **SCREAMING_SNAKE_CASE :Union[str, Any] ) -> Dict: '''simple docstring''' raise OSError def __UpperCAmelCase ( self :Dict , *SCREAMING_SNAKE_CASE :List[str] , **SCREAMING_SNAKE_CASE :List[Any] ) -> Optional[Any]: '''simple docstring''' raise OSError def __UpperCAmelCase ( self :Optional[Any] , *SCREAMING_SNAKE_CASE :Optional[Any] , **SCREAMING_SNAKE_CASE :int ) -> Dict: '''simple docstring''' raise OSError def __UpperCAmelCase ( self :Any , *SCREAMING_SNAKE_CASE :int , **SCREAMING_SNAKE_CASE :str ) -> Union[str, Any]: '''simple docstring''' return False class A__ ( contextlib._RedirectStream ): # type: ignore __UpperCamelCase : List[Any] = "stdin" @contextlib.contextmanager def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[str] ) -> Any: if root == ".": yield return _a : int =os.getcwd() os.chdir(_UpperCAmelCase ) try: yield except BaseException as exc: raise exc finally: os.chdir(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[str]=None ) -> List[str]: if maximum_memory_bytes is not None: import resource resource.setrlimit(resource.RLIMIT_AS ,(maximum_memory_bytes, maximum_memory_bytes) ) resource.setrlimit(resource.RLIMIT_DATA ,(maximum_memory_bytes, maximum_memory_bytes) ) if not platform.uname().system == "Darwin": resource.setrlimit(resource.RLIMIT_STACK ,(maximum_memory_bytes, maximum_memory_bytes) ) faulthandler.disable() import builtins _a : Union[str, Any] =None _a : Optional[int] =None import os _a : List[Any] ="""1""" _a : Any =None _a : str =None _a : List[str] =None _a : List[str] =None _a : Any =None _a : List[str] =None _a : Optional[Any] =None _a : Optional[int] =None _a : Optional[int] =None _a : Dict =None _a : Tuple =None _a : List[Any] =None _a : Optional[int] =None _a : List[str] =None _a : str =None _a : str =None _a : Optional[int] =None _a : List[Any] =None _a : Optional[Any] =None _a : int =None _a : Dict =None _a : str =None _a : List[str] =None _a : Dict =None _a : Optional[Any] =None _a : Any =None _a : List[str] =None import shutil _a : Optional[int] =None _a : Optional[int] =None _a : Tuple =None import subprocess _a : List[str] =None # type: ignore _a : List[str] =None import sys _a : Optional[int] =None _a : List[str] =None _a : List[Any] =None _a : str =None _a : str =None
276
'''simple docstring''' 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''' ) A__: Dict = None A__: Tuple = { '''7B''': 1_1008, '''13B''': 1_3824, '''30B''': 1_7920, '''65B''': 2_2016, '''70B''': 2_8672, } A__: Any = { '''7B''': 1, '''7Bf''': 1, '''13B''': 2, '''13Bf''': 2, '''30B''': 4, '''65B''': 8, '''70B''': 8, '''70Bf''': 8, } def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Optional[int]=1 ,_UpperCAmelCase : List[str]=256 ) -> Dict: return multiple_of * ((int(ffn_dim_multiplier * int(8 * n / 3 ) ) + multiple_of - 1) // multiple_of) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[Any] ) -> List[str]: with open(_UpperCAmelCase ,"""r""" ) as f: return json.load(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : Optional[Any] ) -> Tuple: with open(_UpperCAmelCase ,"""w""" ) as f: json.dump(_UpperCAmelCase ,_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : int ,_UpperCAmelCase : List[Any]=True ) -> Union[str, Any]: os.makedirs(_UpperCAmelCase ,exist_ok=_UpperCAmelCase ) _a : Union[str, Any] =os.path.join(_UpperCAmelCase ,"""tmp""" ) os.makedirs(_UpperCAmelCase ,exist_ok=_UpperCAmelCase ) _a : int =read_json(os.path.join(_UpperCAmelCase ,"""params.json""" ) ) _a : int =NUM_SHARDS[model_size] _a : Dict =params["""n_layers"""] _a : Union[str, Any] =params["""n_heads"""] _a : List[str] =n_heads // num_shards _a : int =params["""dim"""] _a : Union[str, Any] =dim // n_heads _a : int =1_0_0_0_0.0 _a : str =1.0 / (base ** (torch.arange(0 ,_UpperCAmelCase ,2 ).float() / dims_per_head)) if "n_kv_heads" in params: _a : str =params["""n_kv_heads"""] # for GQA / MQA _a : Optional[Any] =n_heads_per_shard // num_key_value_heads _a : Optional[int] =dim // num_key_value_heads else: # compatibility with other checkpoints _a : str =n_heads _a : Any =n_heads_per_shard _a : str =dim # permute for sliced rotary def permute(_UpperCAmelCase : Tuple ,_UpperCAmelCase : Optional[int]=n_heads ,_UpperCAmelCase : Optional[int]=dim ,_UpperCAmelCase : List[str]=dim ): return w.view(_UpperCAmelCase ,dima // n_heads // 2 ,2 ,_UpperCAmelCase ).transpose(1 ,2 ).reshape(_UpperCAmelCase ,_UpperCAmelCase ) 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.) _a : Any =torch.load(os.path.join(_UpperCAmelCase ,"""consolidated.00.pth""" ) ,map_location="""cpu""" ) else: # Sharded _a : List[Any] =[ torch.load(os.path.join(_UpperCAmelCase ,F"consolidated.{i:02d}.pth" ) ,map_location="""cpu""" ) for i in range(_UpperCAmelCase ) ] _a : Any =0 _a : Optional[int] ={"""weight_map""": {}} for layer_i in range(_UpperCAmelCase ): _a : List[str] =F"pytorch_model-{layer_i + 1}-of-{n_layers + 1}.bin" if model_size == "7B": # Unsharded _a : List[str] ={ 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. _a : Tuple ={ 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(), } _a : str =permute( torch.cat( [ loaded[i][F"layers.{layer_i}.attention.wq.weight"].view(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) for i in range(_UpperCAmelCase ) ] ,dim=0 ,).reshape(_UpperCAmelCase ,_UpperCAmelCase ) ) _a : Tuple =permute( torch.cat( [ loaded[i][F"layers.{layer_i}.attention.wk.weight"].view( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) for i in range(_UpperCAmelCase ) ] ,dim=0 ,).reshape(_UpperCAmelCase ,_UpperCAmelCase ) ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,) _a : Any =torch.cat( [ loaded[i][F"layers.{layer_i}.attention.wv.weight"].view( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) for i in range(_UpperCAmelCase ) ] ,dim=0 ,).reshape(_UpperCAmelCase ,_UpperCAmelCase ) _a : List[str] =torch.cat( [loaded[i][F"layers.{layer_i}.attention.wo.weight"] for i in range(_UpperCAmelCase )] ,dim=1 ) _a : Union[str, Any] =torch.cat( [loaded[i][F"layers.{layer_i}.feed_forward.w1.weight"] for i in range(_UpperCAmelCase )] ,dim=0 ) _a : Tuple =torch.cat( [loaded[i][F"layers.{layer_i}.feed_forward.w2.weight"] for i in range(_UpperCAmelCase )] ,dim=1 ) _a : Union[str, Any] =torch.cat( [loaded[i][F"layers.{layer_i}.feed_forward.w3.weight"] for i in range(_UpperCAmelCase )] ,dim=0 ) _a : str =inv_freq for k, v in state_dict.items(): _a : Any =filename param_count += v.numel() torch.save(_UpperCAmelCase ,os.path.join(_UpperCAmelCase ,_UpperCAmelCase ) ) _a : Union[str, Any] =F"pytorch_model-{n_layers + 1}-of-{n_layers + 1}.bin" if model_size == "7B": # Unsharded _a : List[str] ={ """model.embed_tokens.weight""": loaded["""tok_embeddings.weight"""], """model.norm.weight""": loaded["""norm.weight"""], """lm_head.weight""": loaded["""output.weight"""], } else: _a : int ={ """model.norm.weight""": loaded[0]["""norm.weight"""], """model.embed_tokens.weight""": torch.cat( [loaded[i]["""tok_embeddings.weight"""] for i in range(_UpperCAmelCase )] ,dim=1 ), """lm_head.weight""": torch.cat([loaded[i]["""output.weight"""] for i in range(_UpperCAmelCase )] ,dim=0 ), } for k, v in state_dict.items(): _a : Dict =filename param_count += v.numel() torch.save(_UpperCAmelCase ,os.path.join(_UpperCAmelCase ,_UpperCAmelCase ) ) # Write configs _a : Tuple ={"""total_size""": param_count * 2} write_json(_UpperCAmelCase ,os.path.join(_UpperCAmelCase ,"""pytorch_model.bin.index.json""" ) ) _a : Optional[Any] =params["""ffn_dim_multiplier"""] if """ffn_dim_multiplier""" in params else 1 _a : int =params["""multiple_of"""] if """multiple_of""" in params else 256 _a : List[Any] =LlamaConfig( hidden_size=_UpperCAmelCase ,intermediate_size=compute_intermediate_size(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) ,num_attention_heads=params["""n_heads"""] ,num_hidden_layers=params["""n_layers"""] ,rms_norm_eps=params["""norm_eps"""] ,num_key_value_heads=_UpperCAmelCase ,) config.save_pretrained(_UpperCAmelCase ) # 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.""" ) _a : Any =LlamaForCausalLM.from_pretrained(_UpperCAmelCase ,torch_dtype=torch.floataa ,low_cpu_mem_usage=_UpperCAmelCase ) # Avoid saving this as part of the config. del model.config._name_or_path print("""Saving in the Transformers format.""" ) model.save_pretrained(_UpperCAmelCase ,safe_serialization=_UpperCAmelCase ) shutil.rmtree(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ,_UpperCAmelCase : int ) -> Optional[Any]: # Initialize the tokenizer based on the `spm` model _a : List[str] =LlamaTokenizer if LlamaTokenizerFast is None else LlamaTokenizerFast print(F"Saving a {tokenizer_class.__name__} to {tokenizer_path}." ) _a : List[Any] =tokenizer_class(_UpperCAmelCase ) tokenizer.save_pretrained(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( ) -> Union[str, Any]: _a : List[str] =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=_UpperCAmelCase ,help="""Whether or not to save using `safetensors`.""" ) _a : Optional[Any] =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 ,) _a : List[Any] =os.path.join(args.input_dir ,"""tokenizer.model""" ) write_tokenizer(args.output_dir ,_UpperCAmelCase ) if __name__ == "__main__": main()
276
1
'''simple docstring''' from string import ascii_uppercase A__: Tuple = {str(ord(c) - 55): c for c in ascii_uppercase} def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ,_UpperCAmelCase : int ) -> str: if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError("""int() can't convert non-string with explicit base""" ) if num < 0: raise ValueError("""parameter must be positive int""" ) if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError("""'str' object cannot be interpreted as an integer""" ) if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError("""'float' object cannot be interpreted as an integer""" ) if base in (0, 1): raise ValueError("""base must be >= 2""" ) if base > 36: raise ValueError("""base must be <= 36""" ) _a : Tuple ="""""" _a : List[Any] =0 _a : Optional[Any] =0 while div != 1: _a , _a : str =divmod(_UpperCAmelCase ,_UpperCAmelCase ) if base >= 11 and 9 < mod < 36: _a : Dict =ALPHABET_VALUES[str(_UpperCAmelCase )] else: _a : Dict =str(_UpperCAmelCase ) new_value += actual_value _a : Any =num // base _a : Optional[int] =div if div == 0: return str(new_value[::-1] ) elif div == 1: new_value += str(_UpperCAmelCase ) return str(new_value[::-1] ) return new_value[::-1] if __name__ == "__main__": import doctest doctest.testmod() for base in range(2, 37): for num in range(1000): assert int(decimal_to_any(num, base), base) == num, ( num, base, decimal_to_any(num, base), int(decimal_to_any(num, base), base), )
276
'''simple docstring''' import contextlib import os import sqlitea import pytest from datasets import Dataset, Features, Value from datasets.io.sql import SqlDatasetReader, SqlDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases, require_sqlalchemy def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Any ,_UpperCAmelCase : str ) -> Dict: assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ) 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 @require_sqlalchemy @pytest.mark.parametrize("""keep_in_memory""" ,[False, True] ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Optional[int] ,_UpperCAmelCase : str ) -> Optional[Any]: _a : Any =tmp_path / """cache""" _a : int ={"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): _a : Tuple =SqlDatasetReader( """dataset""" ,"""sqlite:///""" + sqlite_path ,cache_dir=_UpperCAmelCase ,keep_in_memory=_UpperCAmelCase ).read() _check_sql_dataset(_UpperCAmelCase ,_UpperCAmelCase ) @require_sqlalchemy @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 SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[Any] ,_UpperCAmelCase : Dict ,_UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : int ) -> List[Any]: _a : Union[str, Any] =tmp_path / """cache""" _a : str ={"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} _a : Optional[int] =features.copy() if features else default_expected_features _a : Union[str, Any] =( Features({feature: Value(_UpperCAmelCase ) for feature, dtype in features.items()} ) if features is not None else None ) _a : Optional[Any] =SqlDatasetReader("""dataset""" ,"""sqlite:///""" + sqlite_path ,features=_UpperCAmelCase ,cache_dir=_UpperCAmelCase ).read() _check_sql_dataset(_UpperCAmelCase ,_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[Any] ) -> List[str]: with contextlib.closing(sqlitea.connect(_UpperCAmelCase ) ) as con: _a : Any =con.cursor() cur.execute("""SELECT * FROM dataset""" ) for row in cur: yield row @require_sqlalchemy def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Dict ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : List[str] ) -> Union[str, Any]: _a : Union[str, Any] =tmp_path / """cache""" _a : Union[str, Any] =os.path.join(_UpperCAmelCase ,"""tmp.sql""" ) _a : Tuple =SqlDatasetReader("""dataset""" ,"""sqlite:///""" + sqlite_path ,cache_dir=_UpperCAmelCase ).read() SqlDatasetWriter(_UpperCAmelCase ,"""dataset""" ,"""sqlite:///""" + output_sqlite_path ,num_proc=1 ).write() _a : Tuple =iter_sql_file(_UpperCAmelCase ) _a : List[Any] =iter_sql_file(_UpperCAmelCase ) for rowa, rowa in zip(_UpperCAmelCase ,_UpperCAmelCase ): assert rowa == rowa @require_sqlalchemy def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Any ,_UpperCAmelCase : List[Any] ) -> Optional[int]: _a : int =tmp_path / """cache""" _a : Any =os.path.join(_UpperCAmelCase ,"""tmp.sql""" ) _a : Union[str, Any] =SqlDatasetReader("""dataset""" ,"""sqlite:///""" + sqlite_path ,cache_dir=_UpperCAmelCase ).read() SqlDatasetWriter(_UpperCAmelCase ,"""dataset""" ,"""sqlite:///""" + output_sqlite_path ,num_proc=2 ).write() _a : List[Any] =iter_sql_file(_UpperCAmelCase ) _a : str =iter_sql_file(_UpperCAmelCase ) for rowa, rowa in zip(_UpperCAmelCase ,_UpperCAmelCase ): assert rowa == rowa @require_sqlalchemy def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : str ,_UpperCAmelCase : List[Any] ) -> List[str]: _a : List[str] =tmp_path / """cache""" _a : Dict =os.path.join(_UpperCAmelCase ,"""tmp.sql""" ) _a : Optional[Any] =SqlDatasetReader("""dataset""" ,"""sqlite:///""" + sqlite_path ,cache_dir=_UpperCAmelCase ).read() with pytest.raises(_UpperCAmelCase ): SqlDatasetWriter(_UpperCAmelCase ,"""dataset""" ,"""sqlite:///""" + output_sqlite_path ,num_proc=0 ).write()
276
1
'''simple docstring''' import argparse import re import requests import torch # git clone https://github.com/salesforce/BLIP.git from models.blip import blip_decoder from models.blip_itm import blip_itm from models.blip_vqa import blip_vqa from PIL import Image from torchvision import transforms from torchvision.transforms.functional import InterpolationMode from transformers import ( BertTokenizer, BlipConfig, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[int] ,_UpperCAmelCase : List[Any] ) -> Dict: _a : Optional[int] ="""https://storage.googleapis.com/sfr-vision-language-research/BLIP/demo.jpg""" _a : List[str] =Image.open(requests.get(_UpperCAmelCase ,stream=_UpperCAmelCase ).raw ).convert("""RGB""" ) _a : Dict =transforms.Compose( [ transforms.Resize((image_size, image_size) ,interpolation=InterpolationMode.BICUBIC ), transforms.ToTensor(), transforms.Normalize((0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3) ,(0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1) ), ] ) _a : Optional[int] =transform(_UpperCAmelCase ).unsqueeze(0 ).to(_UpperCAmelCase ) return image def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[Any] ) -> Optional[int]: if "visual_encoder" in key: _a : Optional[int] =re.sub("""visual_encoder*""" ,"""vision_model.encoder""" ,_UpperCAmelCase ) if "blocks" in key: _a : int =re.sub(R"""blocks""" ,"""layers""" ,_UpperCAmelCase ) if "attn" in key: _a : Any =re.sub(R"""attn""" ,"""self_attn""" ,_UpperCAmelCase ) if "norm1" in key: _a : Optional[int] =re.sub(R"""norm1""" ,"""layer_norm1""" ,_UpperCAmelCase ) if "norm2" in key: _a : Optional[Any] =re.sub(R"""norm2""" ,"""layer_norm2""" ,_UpperCAmelCase ) if "encoder.norm" in key: _a : str =re.sub(R"""encoder.norm""" ,"""post_layernorm""" ,_UpperCAmelCase ) if "encoder.patch_embed.proj" in key: _a : List[Any] =re.sub(R"""encoder.patch_embed.proj""" ,"""embeddings.patch_embedding""" ,_UpperCAmelCase ) if "encoder.pos_embed" in key: _a : Optional[int] =re.sub(R"""encoder.pos_embed""" ,"""embeddings.position_embedding""" ,_UpperCAmelCase ) if "encoder.cls_token" in key: _a : Dict =re.sub(R"""encoder.cls_token""" ,"""embeddings.class_embedding""" ,_UpperCAmelCase ) if "self_attn" in key: _a : Optional[Any] =re.sub(R"""self_attn.proj""" ,"""self_attn.projection""" ,_UpperCAmelCase ) return key @torch.no_grad() def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[int] ,_UpperCAmelCase : int=None ) -> Any: if config_path is not None: _a : List[Any] =BlipConfig.from_pretrained(_UpperCAmelCase ) else: _a : Optional[int] =BlipConfig(projection_dim=512 ,text_config={} ,vision_config={} ) _a : Optional[int] =BlipForConditionalGeneration(_UpperCAmelCase ).eval() _a : List[str] ="""https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_capfilt_large.pth""" _a : Any =blip_decoder(pretrained=_UpperCAmelCase ,image_size=384 ,vit="""base""" ) _a : int =pt_model.eval() _a : Union[str, Any] =pt_model.state_dict() for key in modified_state_dict.copy(): _a : Union[str, Any] =modified_state_dict.pop(_UpperCAmelCase ) _a : Dict =rename_key(_UpperCAmelCase ) _a : Optional[int] =value hf_model.load_state_dict(_UpperCAmelCase ) _a : Union[str, Any] =384 _a : Optional[Any] =load_demo_image(image_size=_UpperCAmelCase ,device="""cpu""" ) _a : Optional[Any] =BertTokenizer.from_pretrained("""bert-base-uncased""" ) _a : List[str] =tokenizer(["""a picture of"""] ).input_ids _a : Any =hf_model.generate(_UpperCAmelCase ,_UpperCAmelCase ) assert out[0].tolist() == [30522, 1037, 3861, 1997, 1037, 2450, 3564, 2006, 1996, 3509, 2007, 2014, 3899, 102] _a : Dict =hf_model.generate(_UpperCAmelCase ) assert out[0].tolist() == [30522, 1037, 2450, 3564, 2006, 1996, 3509, 2007, 2014, 3899, 102] if pytorch_dump_folder_path is not None: hf_model.save_pretrained(_UpperCAmelCase ) # model_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_vqa.pth' _a : Any =( """https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_vqa_capfilt_large.pth""" ) _a : List[str] =blip_vqa(pretrained=_UpperCAmelCase ,image_size=_UpperCAmelCase ,vit="""base""" ) vqa_model.eval() _a : Optional[Any] =vqa_model.state_dict() for key in modified_state_dict.copy(): _a : Any =modified_state_dict.pop(_UpperCAmelCase ) _a : Tuple =rename_key(_UpperCAmelCase ) _a : Union[str, Any] =value _a : int =BlipForQuestionAnswering(_UpperCAmelCase ) hf_vqa_model.load_state_dict(_UpperCAmelCase ) _a : Tuple =["""How many dogs are in this image?"""] _a : Optional[int] =tokenizer(_UpperCAmelCase ,return_tensors="""pt""" ).input_ids _a : Union[str, Any] =hf_vqa_model.generate(_UpperCAmelCase ,_UpperCAmelCase ) print(tokenizer.decode(answer[0] ) ) assert tokenizer.decode(answer[0] ) == "[UNK] 1 [SEP]" if pytorch_dump_folder_path is not None: hf_vqa_model.save_pretrained(pytorch_dump_folder_path + """_vqa""" ) _a : Optional[Any] ="""https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_retrieval_coco.pth""" _a : Optional[int] =blip_itm(pretrained=_UpperCAmelCase ,image_size=_UpperCAmelCase ,vit="""base""" ) itm_model.eval() _a : Any =itm_model.state_dict() for key in modified_state_dict.copy(): _a : str =modified_state_dict.pop(_UpperCAmelCase ) _a : Optional[Any] =rename_key(_UpperCAmelCase ) _a : Union[str, Any] =value _a : Optional[Any] =BlipForImageTextRetrieval(_UpperCAmelCase ) _a : Any =["""A picture of a woman with a dog sitting in a beach"""] _a : List[str] =tokenizer( _UpperCAmelCase ,return_tensors="""pt""" ,padding="""max_length""" ,truncation=_UpperCAmelCase ,max_length=35 ,).input_ids hf_itm_model.load_state_dict(_UpperCAmelCase ) hf_itm_model.eval() _a : int =hf_itm_model(_UpperCAmelCase ,_UpperCAmelCase ,use_itm_head=_UpperCAmelCase ) _a : Optional[int] =hf_itm_model(_UpperCAmelCase ,_UpperCAmelCase ,use_itm_head=_UpperCAmelCase ) assert out[0].item() == 0.2_1_1_0_6_8_7_4_9_4_2_7_7_9_5_4 assert torch.nn.functional.softmax(out_itm[0] ,dim=1 )[:, 1].item() == 0.4_5_6_9_8_8_4_5_3_8_6_5_0_5_1_2_7 if pytorch_dump_folder_path is not None: hf_itm_model.save_pretrained(pytorch_dump_folder_path + """_itm""" ) if __name__ == "__main__": A__: List[Any] = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') A__: Dict = parser.parse_args() convert_blip_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
276
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A__: List[str] = logging.get_logger(__name__) A__: Union[str, Any] = { '''facebook/data2vec-text-base''': '''https://huggingface.co/data2vec/resolve/main/config.json''', } class A__ ( UpperCAmelCase__ ): __UpperCamelCase : int = "data2vec-text" def __init__( self :str , SCREAMING_SNAKE_CASE :Optional[Any]=3_0_5_2_2 , SCREAMING_SNAKE_CASE :Any=7_6_8 , SCREAMING_SNAKE_CASE :List[Any]=1_2 , SCREAMING_SNAKE_CASE :List[str]=1_2 , SCREAMING_SNAKE_CASE :Dict=3_0_7_2 , SCREAMING_SNAKE_CASE :List[str]="gelu" , SCREAMING_SNAKE_CASE :Any=0.1 , SCREAMING_SNAKE_CASE :List[str]=0.1 , SCREAMING_SNAKE_CASE :int=5_1_2 , SCREAMING_SNAKE_CASE :int=2 , SCREAMING_SNAKE_CASE :Union[str, Any]=0.02 , SCREAMING_SNAKE_CASE :Dict=1e-12 , SCREAMING_SNAKE_CASE :int=1 , SCREAMING_SNAKE_CASE :Dict=0 , SCREAMING_SNAKE_CASE :List[Any]=2 , SCREAMING_SNAKE_CASE :str="absolute" , SCREAMING_SNAKE_CASE :Tuple=True , SCREAMING_SNAKE_CASE :Union[str, Any]=None , **SCREAMING_SNAKE_CASE :Union[str, Any] , ) -> List[str]: '''simple docstring''' super().__init__(pad_token_id=SCREAMING_SNAKE_CASE , bos_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) _a : Optional[Any] =vocab_size _a : Optional[Any] =hidden_size _a : Any =num_hidden_layers _a : List[str] =num_attention_heads _a : Union[str, Any] =hidden_act _a : Any =intermediate_size _a : str =hidden_dropout_prob _a : Optional[Any] =attention_probs_dropout_prob _a : Optional[Any] =max_position_embeddings _a : Union[str, Any] =type_vocab_size _a : Tuple =initializer_range _a : Optional[int] =layer_norm_eps _a : Tuple =position_embedding_type _a : int =use_cache _a : List[str] =classifier_dropout class A__ ( UpperCAmelCase__ ): @property def __UpperCAmelCase ( self :int ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' 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), ] )
276
1
'''simple docstring''' from typing import List, Optional, Tuple, Union import torch from ...utils import logging, randn_tensor from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline A__: int = logging.get_logger(__name__) # pylint: disable=invalid-name class A__ ( UpperCAmelCase__ ): def __init__( self :List[str] , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :List[str] ) -> Optional[int]: '''simple docstring''' super().__init__() self.register_modules(unet=SCREAMING_SNAKE_CASE , scheduler=SCREAMING_SNAKE_CASE ) @torch.no_grad() def __call__( self :Tuple , SCREAMING_SNAKE_CASE :int = 1 , SCREAMING_SNAKE_CASE :int = 1_0_0 , SCREAMING_SNAKE_CASE :Optional[Union[torch.Generator, List[torch.Generator]]] = None , SCREAMING_SNAKE_CASE :Optional[float] = None , SCREAMING_SNAKE_CASE :bool = True , ) -> Union[AudioPipelineOutput, Tuple]: '''simple docstring''' if audio_length_in_s is None: _a : Tuple =self.unet.config.sample_size / self.unet.config.sample_rate _a : Optional[int] =audio_length_in_s * self.unet.config.sample_rate _a : int =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}." ) _a : str =int(SCREAMING_SNAKE_CASE ) if sample_size % down_scale_factor != 0: _a : Tuple =( (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.""" ) _a : Optional[int] =int(SCREAMING_SNAKE_CASE ) _a : Optional[Any] =next(iter(self.unet.parameters() ) ).dtype _a : Union[str, Any] =(batch_size, self.unet.config.in_channels, sample_size) if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) and len(SCREAMING_SNAKE_CASE ) != batch_size: raise ValueError( f"You have passed a list of generators of length {len(SCREAMING_SNAKE_CASE )}, but requested an effective batch" f" size of {batch_size}. Make sure the batch size matches the length of the generators." ) _a : Tuple =randn_tensor(SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE , device=self.device , dtype=SCREAMING_SNAKE_CASE ) # set step values self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE , device=audio.device ) _a : Optional[int] =self.scheduler.timesteps.to(SCREAMING_SNAKE_CASE ) for t in self.progress_bar(self.scheduler.timesteps ): # 1. predict noise model_output _a : Tuple =self.unet(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ).sample # 2. compute previous image: x_t -> t_t-1 _a : List[str] =self.scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ).prev_sample _a : int =audio.clamp(-1 , 1 ).float().cpu().numpy() _a : str =audio[:, :, :original_sample_size] if not return_dict: return (audio,) return AudioPipelineOutput(audios=SCREAMING_SNAKE_CASE )
276
'''simple docstring''' from typing import Dict, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import flip_channel_order, resize, to_channel_dimension_format, to_pil_image from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_pytesseract_available, is_vision_available, logging, requires_backends if is_vision_available(): import PIL # soft dependency if is_pytesseract_available(): import pytesseract A__: Union[str, Any] = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : List[str] ) -> int: return [ int(1000 * (box[0] / width) ), int(1000 * (box[1] / height) ), int(1000 * (box[2] / width) ), int(1000 * (box[3] / height) ), ] def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : np.ndarray ,_UpperCAmelCase : Optional[str] ,_UpperCAmelCase : Optional[str] = None ) -> Optional[int]: _a : Any =tesseract_config if tesseract_config is not None else """""" # apply OCR _a : Optional[Any] =to_pil_image(_UpperCAmelCase ) _a , _a : List[Any] =pil_image.size _a : List[str] =pytesseract.image_to_data(_UpperCAmelCase ,lang=_UpperCAmelCase ,output_type="""dict""" ,config=_UpperCAmelCase ) _a , _a , _a , _a , _a : str =data["""text"""], data["""left"""], data["""top"""], data["""width"""], data["""height"""] # filter empty words and corresponding coordinates _a : Tuple =[idx for idx, word in enumerate(_UpperCAmelCase ) if not word.strip()] _a : List[Any] =[word for idx, word in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] _a : Dict =[coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] _a : List[str] =[coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] _a : Union[str, Any] =[coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] _a : Union[str, Any] =[coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] # turn coordinates into (left, top, left+width, top+height) format _a : List[str] =[] for x, y, w, h in zip(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ): _a : int =[x, y, x + w, y + h] actual_boxes.append(_UpperCAmelCase ) # finally, normalize the bounding boxes _a : str =[] for box in actual_boxes: normalized_boxes.append(normalize_box(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) ) assert len(_UpperCAmelCase ) == len(_UpperCAmelCase ), "Not as many words as there are bounding boxes" return words, normalized_boxes class A__ ( UpperCAmelCase__ ): __UpperCamelCase : List[Any] = ["pixel_values"] def __init__( self :Tuple , SCREAMING_SNAKE_CASE :bool = True , SCREAMING_SNAKE_CASE :Dict[str, int] = None , SCREAMING_SNAKE_CASE :PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE :bool = True , SCREAMING_SNAKE_CASE :Optional[str] = None , SCREAMING_SNAKE_CASE :Optional[str] = "" , **SCREAMING_SNAKE_CASE :Tuple , ) -> None: '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE ) _a : List[Any] =size if size is not None else {"""height""": 2_2_4, """width""": 2_2_4} _a : Tuple =get_size_dict(SCREAMING_SNAKE_CASE ) _a : Dict =do_resize _a : Tuple =size _a : str =resample _a : Dict =apply_ocr _a : Union[str, Any] =ocr_lang _a : Dict =tesseract_config def __UpperCAmelCase ( self :List[str] , SCREAMING_SNAKE_CASE :np.ndarray , SCREAMING_SNAKE_CASE :Dict[str, int] , SCREAMING_SNAKE_CASE :PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE :Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE :Dict , ) -> np.ndarray: '''simple docstring''' _a : int =get_size_dict(SCREAMING_SNAKE_CASE ) if "height" not in size or "width" not in size: raise ValueError(f"The size dictionary must contain the keys 'height' and 'width'. Got {size.keys()}" ) _a : Any =(size["""height"""], size["""width"""]) return resize(SCREAMING_SNAKE_CASE , size=SCREAMING_SNAKE_CASE , resample=SCREAMING_SNAKE_CASE , data_format=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Dict , SCREAMING_SNAKE_CASE :ImageInput , SCREAMING_SNAKE_CASE :bool = None , SCREAMING_SNAKE_CASE :Dict[str, int] = None , SCREAMING_SNAKE_CASE :PILImageResampling = None , SCREAMING_SNAKE_CASE :bool = None , SCREAMING_SNAKE_CASE :Optional[str] = None , SCREAMING_SNAKE_CASE :Optional[str] = None , SCREAMING_SNAKE_CASE :Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE :ChannelDimension = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE :Optional[Any] , ) -> PIL.Image.Image: '''simple docstring''' _a : Optional[int] =do_resize if do_resize is not None else self.do_resize _a : Optional[int] =size if size is not None else self.size _a : str =get_size_dict(SCREAMING_SNAKE_CASE ) _a : List[str] =resample if resample is not None else self.resample _a : int =apply_ocr if apply_ocr is not None else self.apply_ocr _a : str =ocr_lang if ocr_lang is not None else self.ocr_lang _a : Union[str, Any] =tesseract_config if tesseract_config is not None else self.tesseract_config _a : List[str] =make_list_of_images(SCREAMING_SNAKE_CASE ) if not valid_images(SCREAMING_SNAKE_CASE ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None: raise ValueError("""Size must be specified if do_resize is True.""" ) # All transformations expect numpy arrays. _a : List[Any] =[to_numpy_array(SCREAMING_SNAKE_CASE ) for image in images] if apply_ocr: requires_backends(self , """pytesseract""" ) _a : Any =[] _a : Any =[] for image in images: _a , _a : int =apply_tesseract(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) words_batch.append(SCREAMING_SNAKE_CASE ) boxes_batch.append(SCREAMING_SNAKE_CASE ) if do_resize: _a : Union[str, Any] =[self.resize(image=SCREAMING_SNAKE_CASE , size=SCREAMING_SNAKE_CASE , resample=SCREAMING_SNAKE_CASE ) for image in images] # flip color channels from RGB to BGR (as Detectron2 requires this) _a : Dict =[flip_channel_order(SCREAMING_SNAKE_CASE ) for image in images] _a : str =[to_channel_dimension_format(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for image in images] _a : str =BatchFeature(data={"""pixel_values""": images} , tensor_type=SCREAMING_SNAKE_CASE ) if apply_ocr: _a : List[Any] =words_batch _a : Dict =boxes_batch return data
276
1
'''simple docstring''' from maths.is_square_free import is_square_free from maths.prime_factors import prime_factors def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ) -> int: _a : str =prime_factors(_UpperCAmelCase ) if is_square_free(_UpperCAmelCase ): return -1 if len(_UpperCAmelCase ) % 2 else 1 return 0 if __name__ == "__main__": import doctest doctest.testmod()
276
'''simple docstring''' from __future__ import annotations import requests def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ) -> dict: _a : Any =F"https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty" return requests.get(_UpperCAmelCase ).json() def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int = 10 ) -> list[dict]: _a : Union[str, Any] ="""https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty""" _a : int =requests.get(_UpperCAmelCase ).json()[:max_stories] return [get_hackernews_story(_UpperCAmelCase ) for story_id in story_ids] def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int = 10 ) -> str: _a : Union[str, Any] =hackernews_top_stories(_UpperCAmelCase ) return "\n".join("""* [{title}]({url})""".format(**_UpperCAmelCase ) for story in stories ) if __name__ == "__main__": print(hackernews_top_stories_as_markdown())
276
1
'''simple docstring''' from typing import Dict from .base import GenericTensor, Pipeline class A__ ( UpperCAmelCase__ ): def __UpperCAmelCase ( self :Dict , SCREAMING_SNAKE_CASE :List[str]=None , SCREAMING_SNAKE_CASE :str=None , SCREAMING_SNAKE_CASE :Any=None , **SCREAMING_SNAKE_CASE :int ) -> Optional[Any]: '''simple docstring''' if tokenize_kwargs is None: _a : Tuple ={} if truncation is not None: if "truncation" in tokenize_kwargs: raise ValueError( """truncation parameter defined twice (given as keyword argument as well as in tokenize_kwargs)""" ) _a : Union[str, Any] =truncation _a : List[str] =tokenize_kwargs _a : Any ={} if return_tensors is not None: _a : List[str] =return_tensors return preprocess_params, {}, postprocess_params def __UpperCAmelCase ( self :Tuple , SCREAMING_SNAKE_CASE :Union[str, Any] , **SCREAMING_SNAKE_CASE :str ) -> Dict[str, GenericTensor]: '''simple docstring''' _a : Optional[int] =self.framework _a : int =self.tokenizer(SCREAMING_SNAKE_CASE , return_tensors=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) return model_inputs def __UpperCAmelCase ( self :List[Any] , SCREAMING_SNAKE_CASE :Any ) -> str: '''simple docstring''' _a : List[str] =self.model(**SCREAMING_SNAKE_CASE ) return model_outputs def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :Any=False ) -> Optional[Any]: '''simple docstring''' # [0] is the first available tensor, logits or last_hidden_state. if return_tensors: return model_outputs[0] if self.framework == "pt": return model_outputs[0].tolist() elif self.framework == "tf": return model_outputs[0].numpy().tolist() def __call__( self :List[str] , *SCREAMING_SNAKE_CASE :Optional[Any] , **SCREAMING_SNAKE_CASE :List[Any] ) -> str: '''simple docstring''' return super().__call__(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE )
276
'''simple docstring''' from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .modeling_utils import ModelMixin from .vae import Decoder, DecoderOutput, Encoder, VectorQuantizer @dataclass class A__ ( UpperCAmelCase__ ): __UpperCamelCase : torch.FloatTensor class A__ ( UpperCAmelCase__ , UpperCAmelCase__ ): @register_to_config def __init__( self :Optional[Any] , SCREAMING_SNAKE_CASE :int = 3 , SCREAMING_SNAKE_CASE :int = 3 , SCREAMING_SNAKE_CASE :Tuple[str] = ("DownEncoderBlock2D",) , SCREAMING_SNAKE_CASE :Tuple[str] = ("UpDecoderBlock2D",) , SCREAMING_SNAKE_CASE :Tuple[int] = (6_4,) , SCREAMING_SNAKE_CASE :int = 1 , SCREAMING_SNAKE_CASE :str = "silu" , SCREAMING_SNAKE_CASE :int = 3 , SCREAMING_SNAKE_CASE :int = 3_2 , SCREAMING_SNAKE_CASE :int = 2_5_6 , SCREAMING_SNAKE_CASE :int = 3_2 , SCREAMING_SNAKE_CASE :Optional[int] = None , SCREAMING_SNAKE_CASE :float = 0.18_215 , SCREAMING_SNAKE_CASE :str = "group" , ) -> Optional[int]: '''simple docstring''' super().__init__() # pass init params to Encoder _a : Union[str, Any] =Encoder( in_channels=SCREAMING_SNAKE_CASE , out_channels=SCREAMING_SNAKE_CASE , down_block_types=SCREAMING_SNAKE_CASE , block_out_channels=SCREAMING_SNAKE_CASE , layers_per_block=SCREAMING_SNAKE_CASE , act_fn=SCREAMING_SNAKE_CASE , norm_num_groups=SCREAMING_SNAKE_CASE , double_z=SCREAMING_SNAKE_CASE , ) _a : Optional[int] =vq_embed_dim if vq_embed_dim is not None else latent_channels _a : Optional[int] =nn.Convad(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , 1 ) _a : str =VectorQuantizer(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , beta=0.25 , remap=SCREAMING_SNAKE_CASE , sane_index_shape=SCREAMING_SNAKE_CASE ) _a : List[str] =nn.Convad(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , 1 ) # pass init params to Decoder _a : List[str] =Decoder( in_channels=SCREAMING_SNAKE_CASE , out_channels=SCREAMING_SNAKE_CASE , up_block_types=SCREAMING_SNAKE_CASE , block_out_channels=SCREAMING_SNAKE_CASE , layers_per_block=SCREAMING_SNAKE_CASE , act_fn=SCREAMING_SNAKE_CASE , norm_num_groups=SCREAMING_SNAKE_CASE , norm_type=SCREAMING_SNAKE_CASE , ) @apply_forward_hook def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :torch.FloatTensor , SCREAMING_SNAKE_CASE :bool = True ) -> VQEncoderOutput: '''simple docstring''' _a : Optional[int] =self.encoder(SCREAMING_SNAKE_CASE ) _a : int =self.quant_conv(SCREAMING_SNAKE_CASE ) if not return_dict: return (h,) return VQEncoderOutput(latents=SCREAMING_SNAKE_CASE ) @apply_forward_hook def __UpperCAmelCase ( self :List[Any] , SCREAMING_SNAKE_CASE :torch.FloatTensor , SCREAMING_SNAKE_CASE :bool = False , SCREAMING_SNAKE_CASE :bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: '''simple docstring''' # also go through quantization layer if not force_not_quantize: _a , _a , _a : Tuple =self.quantize(SCREAMING_SNAKE_CASE ) else: _a : str =h _a : Dict =self.post_quant_conv(SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =self.decoder(SCREAMING_SNAKE_CASE , quant if self.config.norm_type == """spatial""" else None ) if not return_dict: return (dec,) return DecoderOutput(sample=SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :torch.FloatTensor , SCREAMING_SNAKE_CASE :bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: '''simple docstring''' _a : Tuple =sample _a : int =self.encode(SCREAMING_SNAKE_CASE ).latents _a : List[Any] =self.decode(SCREAMING_SNAKE_CASE ).sample if not return_dict: return (dec,) return DecoderOutput(sample=SCREAMING_SNAKE_CASE )
276
1
'''simple docstring''' from __future__ import annotations class A__ : def __init__( self :Union[str, Any] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :str ) -> Optional[int]: '''simple docstring''' _a , _a : List[str] =text, pattern _a , _a : Union[str, Any] =len(SCREAMING_SNAKE_CASE ), len(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Optional[int] , SCREAMING_SNAKE_CASE :str ) -> int: '''simple docstring''' for i in range(self.patLen - 1 , -1 , -1 ): if char == self.pattern[i]: return i return -1 def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :int ) -> int: '''simple docstring''' for i in range(self.patLen - 1 , -1 , -1 ): if self.pattern[i] != self.text[current_pos + i]: return current_pos + i return -1 def __UpperCAmelCase ( self :Union[str, Any] ) -> list[int]: '''simple docstring''' # searches pattern in text and returns index positions _a : Union[str, Any] =[] for i in range(self.textLen - self.patLen + 1 ): _a : Any =self.mismatch_in_text(SCREAMING_SNAKE_CASE ) if mismatch_index == -1: positions.append(SCREAMING_SNAKE_CASE ) else: _a : int =self.match_in_pattern(self.text[mismatch_index] ) _a : List[str] =( mismatch_index - match_index ) # shifting index lgtm [py/multiple-definition] return positions A__: Any = '''ABAABA''' A__: int = '''AB''' A__: Optional[int] = BoyerMooreSearch(text, pattern) A__: Optional[Any] = bms.bad_character_heuristic() if len(positions) == 0: print('''No match found''') else: print('''Pattern found in following positions: ''') print(positions)
276
'''simple docstring''' import unittest from transformers import EsmConfig, is_torch_available from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import EsmForMaskedLM, EsmForSequenceClassification, EsmForTokenClassification, EsmModel from transformers.models.esm.modeling_esm import ( ESM_PRETRAINED_MODEL_ARCHIVE_LIST, EsmEmbeddings, create_position_ids_from_input_ids, ) class A__ : def __init__( self :Tuple , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :Optional[int]=1_3 , SCREAMING_SNAKE_CASE :Optional[int]=7 , SCREAMING_SNAKE_CASE :Tuple=False , SCREAMING_SNAKE_CASE :Dict=True , SCREAMING_SNAKE_CASE :Optional[int]=False , SCREAMING_SNAKE_CASE :Optional[Any]=True , SCREAMING_SNAKE_CASE :List[str]=3_3 , SCREAMING_SNAKE_CASE :Tuple=3_2 , SCREAMING_SNAKE_CASE :Tuple=5 , SCREAMING_SNAKE_CASE :int=4 , SCREAMING_SNAKE_CASE :Union[str, Any]=3_7 , SCREAMING_SNAKE_CASE :List[str]="gelu" , SCREAMING_SNAKE_CASE :Optional[Any]=0.1 , SCREAMING_SNAKE_CASE :Tuple=0.1 , SCREAMING_SNAKE_CASE :str=5_1_2 , SCREAMING_SNAKE_CASE :Dict=1_6 , SCREAMING_SNAKE_CASE :Dict=2 , SCREAMING_SNAKE_CASE :Union[str, Any]=0.02 , SCREAMING_SNAKE_CASE :str=3 , SCREAMING_SNAKE_CASE :List[str]=4 , SCREAMING_SNAKE_CASE :List[str]=None , ) -> Union[str, Any]: '''simple docstring''' _a : Union[str, Any] =parent _a : List[Any] =batch_size _a : Optional[int] =seq_length _a : Union[str, Any] =is_training _a : List[Any] =use_input_mask _a : Optional[int] =use_token_type_ids _a : int =use_labels _a : List[str] =vocab_size _a : List[Any] =hidden_size _a : int =num_hidden_layers _a : Tuple =num_attention_heads _a : Any =intermediate_size _a : str =hidden_act _a : Union[str, Any] =hidden_dropout_prob _a : Union[str, Any] =attention_probs_dropout_prob _a : str =max_position_embeddings _a : Dict =type_vocab_size _a : Tuple =type_sequence_label_size _a : Dict =initializer_range _a : List[str] =num_labels _a : Tuple =num_choices _a : int =scope def __UpperCAmelCase ( self :Union[str, Any] ) -> str: '''simple docstring''' _a : Optional[int] =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _a : List[Any] =None if self.use_input_mask: _a : Any =random_attention_mask([self.batch_size, self.seq_length] ) _a : Optional[int] =None _a : str =None _a : Dict =None if self.use_labels: _a : Dict =ids_tensor([self.batch_size] , self.type_sequence_label_size ) _a : str =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _a : List[str] =ids_tensor([self.batch_size] , self.num_choices ) _a : List[Any] =self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCAmelCase ( self :str ) -> Optional[int]: '''simple docstring''' return EsmConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , pad_token_id=1 , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) def __UpperCAmelCase ( self :List[str] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :int ) -> Tuple: '''simple docstring''' _a : Any =EsmModel(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() _a : Optional[Any] =model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =model(SCREAMING_SNAKE_CASE ) _a : str =model(SCREAMING_SNAKE_CASE ) 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 __UpperCAmelCase ( self :str , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :Optional[Any] ) -> Dict: '''simple docstring''' _a : str =EsmForMaskedLM(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() _a : Union[str, Any] =model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :List[Any] , SCREAMING_SNAKE_CASE :Union[str, Any] ) -> Optional[Any]: '''simple docstring''' _a : int =self.num_labels _a : Tuple =EsmForTokenClassification(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() _a : Tuple =model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCAmelCase ( self :Dict ) -> List[str]: '''simple docstring''' _a : Optional[Any] =self.prepare_config_and_inputs() ( ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ) : Any =config_and_inputs _a : List[Any] ={"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class A__ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): __UpperCamelCase : Any = False __UpperCamelCase : Any = ( ( EsmForMaskedLM, EsmModel, EsmForSequenceClassification, EsmForTokenClassification, ) if is_torch_available() else () ) __UpperCamelCase : str = () __UpperCamelCase : List[str] = ( { "feature-extraction": EsmModel, "fill-mask": EsmForMaskedLM, "text-classification": EsmForSequenceClassification, "token-classification": EsmForTokenClassification, "zero-shot": EsmForSequenceClassification, } if is_torch_available() else {} ) __UpperCamelCase : Union[str, Any] = True def __UpperCAmelCase ( self :Optional[int] ) -> int: '''simple docstring''' _a : Dict =EsmModelTester(self ) _a : Optional[Any] =ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , hidden_size=3_7 ) def __UpperCAmelCase ( self :Tuple ) -> List[Any]: '''simple docstring''' self.config_tester.run_common_tests() def __UpperCAmelCase ( self :Optional[int] ) -> str: '''simple docstring''' _a : List[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :List[Any] ) -> Dict: '''simple docstring''' _a : List[str] =self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: _a : Dict =type self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Dict ) -> List[str]: '''simple docstring''' _a : Tuple =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :List[Any] ) -> List[str]: '''simple docstring''' _a : str =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE ) @slow def __UpperCAmelCase ( self :str ) -> Dict: '''simple docstring''' for model_name in ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _a : Union[str, Any] =EsmModel.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Tuple ) -> int: '''simple docstring''' _a : Optional[Any] =self.model_tester.prepare_config_and_inputs()[0] _a : Dict =EsmEmbeddings(config=SCREAMING_SNAKE_CASE ) _a : Tuple =torch.as_tensor([[1_2, 3_1, 1_3, model.padding_idx]] ) _a : Optional[Any] =torch.as_tensor( [ [ 0 + model.padding_idx + 1, 1 + model.padding_idx + 1, 2 + model.padding_idx + 1, model.padding_idx, ] ] ) _a : Any =create_position_ids_from_input_ids(SCREAMING_SNAKE_CASE , model.padding_idx ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) ) def __UpperCAmelCase ( self :Optional[Any] ) -> Tuple: '''simple docstring''' _a : List[Any] =self.model_tester.prepare_config_and_inputs()[0] _a : Optional[int] =EsmEmbeddings(config=SCREAMING_SNAKE_CASE ) _a : Tuple =torch.empty(2 , 4 , 3_0 ) _a : str =[ 0 + embeddings.padding_idx + 1, 1 + embeddings.padding_idx + 1, 2 + embeddings.padding_idx + 1, 3 + embeddings.padding_idx + 1, ] _a : int =torch.as_tensor([expected_single_positions, expected_single_positions] ) _a : Any =embeddings.create_position_ids_from_inputs_embeds(SCREAMING_SNAKE_CASE ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) ) @unittest.skip("""Esm does not support embedding resizing""" ) def __UpperCAmelCase ( self :Tuple ) -> List[str]: '''simple docstring''' pass @unittest.skip("""Esm does not support embedding resizing""" ) def __UpperCAmelCase ( self :str ) -> Any: '''simple docstring''' pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def __UpperCAmelCase ( self :Dict ) -> Any: '''simple docstring''' pass @require_torch class A__ ( UpperCAmelCase__ ): @slow def __UpperCAmelCase ( self :List[Any] ) -> str: '''simple docstring''' with torch.no_grad(): _a : Optional[int] =EsmForMaskedLM.from_pretrained("""facebook/esm2_t6_8M_UR50D""" ) model.eval() _a : Any =torch.tensor([[0, 1, 2, 3, 4, 5]] ) _a : Tuple =model(SCREAMING_SNAKE_CASE )[0] _a : int =3_3 _a : Tuple =torch.Size((1, 6, vocab_size) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =torch.tensor( [[[8.9_215, -10.5_898, -6.4_671], [-6.3_967, -13.9_114, -1.1_212], [-7.7_812, -13.9_516, -3.7_406]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) ) @slow def __UpperCAmelCase ( self :Union[str, Any] ) -> Tuple: '''simple docstring''' with torch.no_grad(): _a : Any =EsmModel.from_pretrained("""facebook/esm2_t6_8M_UR50D""" ) model.eval() _a : Any =torch.tensor([[0, 6, 4, 1_3, 5, 4, 1_6, 1_2, 1_1, 7, 2]] ) _a : int =model(SCREAMING_SNAKE_CASE )[0] # compare the actual values for a slice. _a : str =torch.tensor( [[[0.1_444, 0.5_413, 0.3_248], [0.3_034, 0.0_053, 0.3_108], [0.3_228, -0.2_499, 0.3_415]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) )
276
1
'''simple docstring''' import unittest from transformers.utils.backbone_utils import ( BackboneMixin, get_aligned_output_features_output_indices, verify_out_features_out_indices, ) class A__ ( unittest.TestCase ): def __UpperCAmelCase ( self :List[str] ) -> Dict: '''simple docstring''' _a : Optional[int] =["""a""", """b""", """c"""] # Defaults to last layer if both are None _a , _a : str =get_aligned_output_features_output_indices(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) self.assertEqual(SCREAMING_SNAKE_CASE , ["""c"""] ) self.assertEqual(SCREAMING_SNAKE_CASE , [2] ) # Out indices set to match out features _a , _a : List[Any] =get_aligned_output_features_output_indices(["""a""", """c"""] , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) self.assertEqual(SCREAMING_SNAKE_CASE , ["""a""", """c"""] ) self.assertEqual(SCREAMING_SNAKE_CASE , [0, 2] ) # Out features set to match out indices _a , _a : Dict =get_aligned_output_features_output_indices(SCREAMING_SNAKE_CASE , [0, 2] , SCREAMING_SNAKE_CASE ) self.assertEqual(SCREAMING_SNAKE_CASE , ["""a""", """c"""] ) self.assertEqual(SCREAMING_SNAKE_CASE , [0, 2] ) # Out features selected from negative indices _a , _a : Any =get_aligned_output_features_output_indices(SCREAMING_SNAKE_CASE , [-3, -1] , SCREAMING_SNAKE_CASE ) self.assertEqual(SCREAMING_SNAKE_CASE , ["""a""", """c"""] ) self.assertEqual(SCREAMING_SNAKE_CASE , [-3, -1] ) def __UpperCAmelCase ( self :Any ) -> Optional[int]: '''simple docstring''' # Stage names must be set with self.assertRaises(SCREAMING_SNAKE_CASE ): verify_out_features_out_indices(["""a""", """b"""] , (0, 1) , SCREAMING_SNAKE_CASE ) # Out features must be a list with self.assertRaises(SCREAMING_SNAKE_CASE ): verify_out_features_out_indices(("""a""", """b""") , (0, 1) , ["""a""", """b"""] ) # Out features must be a subset of stage names with self.assertRaises(SCREAMING_SNAKE_CASE ): verify_out_features_out_indices(["""a""", """b"""] , (0, 1) , ["""a"""] ) # Out indices must be a list or tuple with self.assertRaises(SCREAMING_SNAKE_CASE ): verify_out_features_out_indices(SCREAMING_SNAKE_CASE , 0 , ["""a""", """b"""] ) # Out indices must be a subset of stage names with self.assertRaises(SCREAMING_SNAKE_CASE ): verify_out_features_out_indices(SCREAMING_SNAKE_CASE , (0, 1) , ["""a"""] ) # Out features and out indices must be the same length with self.assertRaises(SCREAMING_SNAKE_CASE ): verify_out_features_out_indices(["""a""", """b"""] , (0,) , ["""a""", """b""", """c"""] ) # Out features should match out indices with self.assertRaises(SCREAMING_SNAKE_CASE ): verify_out_features_out_indices(["""a""", """b"""] , (0, 2) , ["""a""", """b""", """c"""] ) # Out features and out indices should be in order with self.assertRaises(SCREAMING_SNAKE_CASE ): verify_out_features_out_indices(["""b""", """a"""] , (0, 1) , ["""a""", """b"""] ) # Check passes with valid inputs verify_out_features_out_indices(["""a""", """b""", """d"""] , (0, 1, -1) , ["""a""", """b""", """c""", """d"""] ) def __UpperCAmelCase ( self :Any ) -> Dict: '''simple docstring''' _a : str =BackboneMixin() _a : Dict =["""a""", """b""", """c"""] _a : List[Any] =["""a""", """c"""] _a : Tuple =[0, 2] # Check that the output features and indices are set correctly self.assertEqual(backbone.out_features , ["""a""", """c"""] ) self.assertEqual(backbone.out_indices , [0, 2] ) # Check out features and indices are updated correctly _a : Optional[int] =["""a""", """b"""] self.assertEqual(backbone.out_features , ["""a""", """b"""] ) self.assertEqual(backbone.out_indices , [0, 1] ) _a : Optional[int] =[-3, -1] self.assertEqual(backbone.out_features , ["""a""", """c"""] ) self.assertEqual(backbone.out_indices , [-3, -1] )
276
'''simple docstring''' from math import isqrt def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ) -> bool: return all(number % divisor != 0 for divisor in range(2 ,isqrt(_UpperCAmelCase ) + 1 ) ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int = 10**6 ) -> int: _a : List[Any] =0 _a : str =1 _a : Optional[Any] =7 while prime_candidate < max_prime: primes_count += is_prime(_UpperCAmelCase ) cube_index += 1 prime_candidate += 6 * cube_index return primes_count if __name__ == "__main__": print(F"{solution() = }")
276
1
'''simple docstring''' from __future__ import annotations import unittest from transformers import RoFormerConfig, 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 import ( TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerModel, ) from transformers.models.roformer.modeling_tf_roformer import ( TFRoFormerSelfAttention, TFRoFormerSinusoidalPositionalEmbedding, ) class A__ : def __init__( self :List[Any] , SCREAMING_SNAKE_CASE :Optional[int] , SCREAMING_SNAKE_CASE :Union[str, Any]=1_3 , SCREAMING_SNAKE_CASE :List[str]=7 , SCREAMING_SNAKE_CASE :Tuple=True , SCREAMING_SNAKE_CASE :str=True , SCREAMING_SNAKE_CASE :int=True , SCREAMING_SNAKE_CASE :Tuple=True , SCREAMING_SNAKE_CASE :int=9_9 , SCREAMING_SNAKE_CASE :List[str]=3_2 , SCREAMING_SNAKE_CASE :int=2 , SCREAMING_SNAKE_CASE :Optional[int]=4 , SCREAMING_SNAKE_CASE :List[Any]=3_7 , SCREAMING_SNAKE_CASE :Dict="gelu" , SCREAMING_SNAKE_CASE :Optional[int]=0.1 , SCREAMING_SNAKE_CASE :List[Any]=0.1 , SCREAMING_SNAKE_CASE :Optional[int]=5_1_2 , SCREAMING_SNAKE_CASE :Tuple=1_6 , SCREAMING_SNAKE_CASE :int=2 , SCREAMING_SNAKE_CASE :int=0.02 , SCREAMING_SNAKE_CASE :str=3 , SCREAMING_SNAKE_CASE :Dict=4 , SCREAMING_SNAKE_CASE :Tuple=None , ) -> str: '''simple docstring''' _a : List[str] =parent _a : int =1_3 _a : Optional[int] =7 _a : int =True _a : List[str] =True _a : str =True _a : int =True _a : int =9_9 _a : str =3_2 _a : Tuple =2 _a : int =4 _a : str =3_7 _a : List[str] ="""gelu""" _a : Tuple =0.1 _a : Tuple =0.1 _a : Optional[Any] =5_1_2 _a : Union[str, Any] =1_6 _a : Optional[Any] =2 _a : Union[str, Any] =0.02 _a : Union[str, Any] =3 _a : Tuple =4 _a : List[Any] =None def __UpperCAmelCase ( self :Tuple ) -> Tuple: '''simple docstring''' _a : Union[str, Any] =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _a : List[Any] =None if self.use_input_mask: _a : int =random_attention_mask([self.batch_size, self.seq_length] ) _a : Any =None if self.use_token_type_ids: _a : Optional[Any] =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _a : Dict =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[Any] =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _a : int =ids_tensor([self.batch_size] , self.num_choices ) _a : Optional[Any] =RoFormerConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , return_dict=SCREAMING_SNAKE_CASE , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCAmelCase ( self :str , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :List[Any] , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :Optional[int] ) -> Optional[int]: '''simple docstring''' _a : int =TFRoFormerModel(config=SCREAMING_SNAKE_CASE ) _a : int ={"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} _a : int =[input_ids, input_mask] _a : Tuple =model(SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self :int , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :Optional[int] , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :List[Any] ) -> Optional[Any]: '''simple docstring''' _a : Optional[Any] =True _a : Any =TFRoFormerForCausalLM(config=SCREAMING_SNAKE_CASE ) _a : Union[str, Any] ={ """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } _a : Dict =model(SCREAMING_SNAKE_CASE )["""logits"""] self.parent.assertListEqual( list(prediction_scores.numpy().shape ) , [self.batch_size, self.seq_length, self.vocab_size] ) def __UpperCAmelCase ( self :int , SCREAMING_SNAKE_CASE :List[Any] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :Tuple ) -> Optional[Any]: '''simple docstring''' _a : Union[str, Any] =TFRoFormerForMaskedLM(config=SCREAMING_SNAKE_CASE ) _a : Optional[int] ={ """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } _a : Optional[int] =model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self :Tuple , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Optional[int] , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :Dict ) -> str: '''simple docstring''' _a : List[str] =self.num_labels _a : Optional[int] =TFRoFormerForSequenceClassification(config=SCREAMING_SNAKE_CASE ) _a : Optional[int] ={ """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } _a : Tuple =model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCAmelCase ( self :Tuple , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :List[Any] , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :Optional[Any] ) -> Tuple: '''simple docstring''' _a : List[Any] =self.num_choices _a : List[Any] =TFRoFormerForMultipleChoice(config=SCREAMING_SNAKE_CASE ) _a : Optional[int] =tf.tile(tf.expand_dims(SCREAMING_SNAKE_CASE , 1 ) , (1, self.num_choices, 1) ) _a : Any =tf.tile(tf.expand_dims(SCREAMING_SNAKE_CASE , 1 ) , (1, self.num_choices, 1) ) _a : int =tf.tile(tf.expand_dims(SCREAMING_SNAKE_CASE , 1 ) , (1, self.num_choices, 1) ) _a : List[str] ={ """input_ids""": multiple_choice_inputs_ids, """attention_mask""": multiple_choice_input_mask, """token_type_ids""": multiple_choice_token_type_ids, } _a : List[str] =model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __UpperCAmelCase ( self :Optional[int] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :Optional[Any] ) -> Optional[int]: '''simple docstring''' _a : Any =self.num_labels _a : Tuple =TFRoFormerForTokenClassification(config=SCREAMING_SNAKE_CASE ) _a : Tuple ={ """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } _a : Union[str, Any] =model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :Optional[int] , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :List[Any] ) -> str: '''simple docstring''' _a : int =TFRoFormerForQuestionAnswering(config=SCREAMING_SNAKE_CASE ) _a : Dict ={ """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } _a : Optional[int] =model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __UpperCAmelCase ( self :Union[str, Any] ) -> Optional[Any]: '''simple docstring''' _a : Dict =self.prepare_config_and_inputs() ( ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ) : Any =config_and_inputs _a : List[Any] ={"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_tf class A__ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): __UpperCamelCase : Optional[Any] = ( ( TFRoFormerModel, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerForMultipleChoice, ) if is_tf_available() else () ) __UpperCamelCase : List[str] = ( { "feature-extraction": TFRoFormerModel, "fill-mask": TFRoFormerForMaskedLM, "question-answering": TFRoFormerForQuestionAnswering, "text-classification": TFRoFormerForSequenceClassification, "text-generation": TFRoFormerForCausalLM, "token-classification": TFRoFormerForTokenClassification, "zero-shot": TFRoFormerForSequenceClassification, } if is_tf_available() else {} ) __UpperCamelCase : Optional[int] = False __UpperCamelCase : str = False def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :Optional[int] , SCREAMING_SNAKE_CASE :List[Any] ) -> Dict: '''simple docstring''' if pipeline_test_casse_name == "TextGenerationPipelineTests": return True return False def __UpperCAmelCase ( self :List[str] ) -> List[str]: '''simple docstring''' _a : Dict =TFRoFormerModelTester(self ) _a : Any =ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , hidden_size=3_7 ) def __UpperCAmelCase ( self :List[Any] ) -> List[str]: '''simple docstring''' self.config_tester.run_common_tests() def __UpperCAmelCase ( self :Union[str, Any] ) -> Tuple: '''simple docstring''' _a : Optional[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Any ) -> Dict: '''simple docstring''' _a : Dict =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :List[str] ) -> str: '''simple docstring''' _a : Dict =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Optional[Any] ) -> int: '''simple docstring''' _a : Optional[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :List[Any] ) -> Dict: '''simple docstring''' _a : Optional[int] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :str ) -> Dict: '''simple docstring''' _a : str =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :List[Any] ) -> Tuple: '''simple docstring''' _a : List[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE ) @slow def __UpperCAmelCase ( self :List[str] ) -> Dict: '''simple docstring''' _a : str =TFRoFormerModel.from_pretrained("""junnyu/roformer_chinese_base""" ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) @require_tf class A__ ( unittest.TestCase ): @slow def __UpperCAmelCase ( self :int ) -> Optional[int]: '''simple docstring''' _a : Any =TFRoFormerForMaskedLM.from_pretrained("""junnyu/roformer_chinese_base""" ) _a : Union[str, Any] =tf.constant([[0, 1, 2, 3, 4, 5]] ) _a : Optional[Any] =model(SCREAMING_SNAKE_CASE )[0] # TODO Replace vocab size _a : Tuple =5_0_0_0_0 _a : Optional[int] =[1, 6, vocab_size] self.assertEqual(output.shape , SCREAMING_SNAKE_CASE ) print(output[:, :3, :3] ) # TODO Replace values below with what was printed above. _a : Dict =tf.constant( [ [ [-0.12_053_341, -1.0_264_901, 0.29_221_946], [-1.5_133_783, 0.197_433, 0.15_190_607], [-5.0_135_403, -3.900_256, -0.84_038_764], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) @require_tf class A__ ( unittest.TestCase ): __UpperCamelCase : Optional[int] = 1e-4 def __UpperCAmelCase ( self :Optional[Any] ) -> str: '''simple docstring''' _a : Optional[int] =tf.constant([[4, 1_0]] ) _a : int =TFRoFormerSinusoidalPositionalEmbedding(num_positions=6 , embedding_dim=6 ) _a : Optional[Any] =emba(input_ids.shape ) _a : Union[str, Any] =tf.constant( [[0.0_000, 0.0_000, 0.0_000, 1.0_000, 1.0_000, 1.0_000], [0.8_415, 0.0_464, 0.0_022, 0.5_403, 0.9_989, 1.0_000]] ) tf.debugging.assert_near(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=self.tolerance ) def __UpperCAmelCase ( self :Union[str, Any] ) -> Union[str, Any]: '''simple docstring''' _a : Optional[int] =tf.constant( [ [0.0_000, 0.0_000, 0.0_000, 0.0_000, 0.0_000], [0.8_415, 0.8_219, 0.8_020, 0.7_819, 0.7_617], [0.9_093, 0.9_364, 0.9_581, 0.9_749, 0.9_870], ] ) _a : Tuple =TFRoFormerSinusoidalPositionalEmbedding(num_positions=5_1_2 , embedding_dim=5_1_2 ) emba([2, 1_6, 5_1_2] ) _a : Union[str, Any] =emba.weight[:3, :5] tf.debugging.assert_near(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=self.tolerance ) @require_tf class A__ ( unittest.TestCase ): __UpperCamelCase : Tuple = 1e-4 def __UpperCAmelCase ( self :str ) -> Union[str, Any]: '''simple docstring''' # 2,12,16,64 _a : Optional[int] =tf.reshape(tf.range(2 * 1_2 * 1_6 * 6_4 , dtype=tf.floataa ) , shape=(2, 1_2, 1_6, 6_4) ) / 1_0_0 _a : int =-tf.reshape(tf.range(2 * 1_2 * 1_6 * 6_4 , dtype=tf.floataa ) , shape=(2, 1_2, 1_6, 6_4) ) / 1_0_0 _a : List[str] =TFRoFormerSinusoidalPositionalEmbedding(num_positions=3_2 , embedding_dim=6_4 ) _a : List[Any] =embed_positions([2, 1_6, 7_6_8] )[None, None, :, :] _a , _a : Dict =TFRoFormerSelfAttention.apply_rotary_position_embeddings( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) _a : Any =tf.constant( [ [0.0_000, 0.0_100, 0.0_200, 0.0_300, 0.0_400, 0.0_500, 0.0_600, 0.0_700], [-0.2_012, 0.8_897, 0.0_263, 0.9_401, 0.2_074, 0.9_463, 0.3_481, 0.9_343], [-1.7_057, 0.6_271, -1.2_145, 1.3_897, -0.6_303, 1.7_647, -0.1_173, 1.8_985], [-2.1_731, -1.6_397, -2.7_358, 0.2_854, -2.1_840, 1.7_183, -1.3_018, 2.4_871], [0.2_717, -3.6_173, -2.9_206, -2.1_988, -3.6_638, 0.3_858, -2.9_155, 2.2_980], [3.9_859, -2.1_580, -0.7_984, -4.4_904, -4.1_181, -2.0_252, -4.4_782, 1.1_253], ] ) _a : Dict =tf.constant( [ [0.0_000, -0.0_100, -0.0_200, -0.0_300, -0.0_400, -0.0_500, -0.0_600, -0.0_700], [0.2_012, -0.8_897, -0.0_263, -0.9_401, -0.2_074, -0.9_463, -0.3_481, -0.9_343], [1.7_057, -0.6_271, 1.2_145, -1.3_897, 0.6_303, -1.7_647, 0.1_173, -1.8_985], [2.1_731, 1.6_397, 2.7_358, -0.2_854, 2.1_840, -1.7_183, 1.3_018, -2.4_871], [-0.2_717, 3.6_173, 2.9_206, 2.1_988, 3.6_638, -0.3_858, 2.9_155, -2.2_980], [-3.9_859, 2.1_580, 0.7_984, 4.4_904, 4.1_181, 2.0_252, 4.4_782, -1.1_253], ] ) tf.debugging.assert_near(query_layer[0, 0, :6, :8] , SCREAMING_SNAKE_CASE , atol=self.tolerance ) tf.debugging.assert_near(key_layer[0, 0, :6, :8] , SCREAMING_SNAKE_CASE , atol=self.tolerance )
276
'''simple docstring''' # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from ...utils import deprecate from ..controlnet.multicontrolnet import MultiControlNetModel # noqa: F401 from ..controlnet.pipeline_controlnet import StableDiffusionControlNetPipeline # noqa: F401 deprecate( '''stable diffusion controlnet''', '''0.22.0''', '''Importing `StableDiffusionControlNetPipeline` or `MultiControlNetModel` from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import StableDiffusionControlNetPipeline` instead.''', standard_warn=False, stacklevel=3, )
276
1
'''simple docstring''' def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : float ,_UpperCAmelCase : list[float] ) -> float: if discount_rate < 0: raise ValueError("""Discount rate cannot be negative""" ) if not cash_flows: raise ValueError("""Cash flows list cannot be empty""" ) _a : Optional[int] =sum( cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(_UpperCAmelCase ) ) return round(_UpperCAmelCase ,ndigits=2 ) if __name__ == "__main__": import doctest doctest.testmod()
276
'''simple docstring''' import pytest from datasets.utils.sharding import _distribute_shards, _number_of_shards_in_gen_kwargs, _split_gen_kwargs @pytest.mark.parametrize( """kwargs, expected""" ,[ ({"""num_shards""": 0, """max_num_jobs""": 1}, []), ({"""num_shards""": 10, """max_num_jobs""": 1}, [range(10 )]), ({"""num_shards""": 10, """max_num_jobs""": 10}, [range(_UpperCAmelCase ,i + 1 ) for i in range(10 )]), ({"""num_shards""": 1, """max_num_jobs""": 10}, [range(1 )]), ({"""num_shards""": 10, """max_num_jobs""": 3}, [range(0 ,4 ), range(4 ,7 ), range(7 ,10 )]), ({"""num_shards""": 3, """max_num_jobs""": 10}, [range(0 ,1 ), range(1 ,2 ), range(2 ,3 )]), ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : Dict ) -> Optional[Any]: _a : Tuple =_distribute_shards(**_UpperCAmelCase ) assert out == expected @pytest.mark.parametrize( """gen_kwargs, max_num_jobs, expected""" ,[ ({"""foo""": 0}, 10, [{"""foo""": 0}]), ({"""shards""": [0, 1, 2, 3]}, 1, [{"""shards""": [0, 1, 2, 3]}]), ({"""shards""": [0, 1, 2, 3]}, 4, [{"""shards""": [0]}, {"""shards""": [1]}, {"""shards""": [2]}, {"""shards""": [3]}]), ({"""shards""": [0, 1]}, 4, [{"""shards""": [0]}, {"""shards""": [1]}]), ({"""shards""": [0, 1, 2, 3]}, 2, [{"""shards""": [0, 1]}, {"""shards""": [2, 3]}]), ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : List[Any] ,_UpperCAmelCase : Union[str, Any] ) -> List[str]: _a : List[str] =_split_gen_kwargs(_UpperCAmelCase ,_UpperCAmelCase ) assert out == expected @pytest.mark.parametrize( """gen_kwargs, expected""" ,[ ({"""foo""": 0}, 1), ({"""shards""": [0]}, 1), ({"""shards""": [0, 1, 2, 3]}, 4), ({"""shards""": [0, 1, 2, 3], """foo""": 0}, 4), ({"""shards""": [0, 1, 2, 3], """other""": (0, 1)}, 4), ({"""shards""": [0, 1, 2, 3], """shards2""": [0, 1]}, RuntimeError), ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : List[Any] ) -> Union[str, Any]: if expected is RuntimeError: with pytest.raises(_UpperCAmelCase ): _number_of_shards_in_gen_kwargs(_UpperCAmelCase ) else: _a : Dict =_number_of_shards_in_gen_kwargs(_UpperCAmelCase ) assert out == expected
276
1
'''simple docstring''' import collections import os import re from pathlib import Path A__: str = '''src/transformers''' # Matches is_xxx_available() A__: List[str] = re.compile(R'''is\_([a-z_]*)_available()''') # Catches a one-line _import_struct = {xxx} A__: Optional[int] = re.compile(R'''^_import_structure\s+=\s+\{([^\}]+)\}''') # Catches a line with a key-values pattern: "bla": ["foo", "bar"] A__: int = re.compile(R'''\s+"\S*":\s+\[([^\]]*)\]''') # Catches a line if not is_foo_available A__: List[Any] = re.compile(R'''^\s*if\s+not\s+is\_[a-z_]*\_available\(\)''') # Catches a line _import_struct["bla"].append("foo") A__: Dict = re.compile(R'''^\s*_import_structure\["\S*"\]\.append\("(\S*)"\)''') # Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"] A__: Optional[int] = re.compile(R'''^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]''') # Catches a line with an object between quotes and a comma: "MyModel", A__: Any = re.compile(R'''^\s+"([^"]+)",''') # Catches a line with objects between brackets only: ["foo", "bar"], A__: Optional[int] = re.compile(R'''^\s+\[([^\]]+)\]''') # Catches a line with from foo import bar, bla, boo A__: Any = re.compile(R'''\s+from\s+\S*\s+import\s+([^\(\s].*)\n''') # Catches a line with try: A__: Tuple = re.compile(R'''^\s*try:''') # Catches a line with else: A__: str = re.compile(R'''^\s*else:''') def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[str] ) -> List[Any]: if _re_test_backend.search(_UpperCAmelCase ) is None: return None _a : int =[b[0] for b in _re_backend.findall(_UpperCAmelCase )] backends.sort() return "_and_".join(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Dict ) -> Dict: with open(_UpperCAmelCase ,"""r""" ,encoding="""utf-8""" ,newline="""\n""" ) as f: _a : Union[str, Any] =f.readlines() _a : Union[str, Any] =0 while line_index < len(_UpperCAmelCase ) and not lines[line_index].startswith("""_import_structure = {""" ): line_index += 1 # If this is a traditional init, just return. if line_index >= len(_UpperCAmelCase ): return None # First grab the objects without a specific backend in _import_structure _a : str =[] while not lines[line_index].startswith("""if TYPE_CHECKING""" ) and find_backend(lines[line_index] ) is None: _a : List[Any] =lines[line_index] # If we have everything on a single line, let's deal with it. if _re_one_line_import_struct.search(_UpperCAmelCase ): _a : Optional[Any] =_re_one_line_import_struct.search(_UpperCAmelCase ).groups()[0] _a : Union[str, Any] =re.findall(R"""\[([^\]]+)\]""" ,_UpperCAmelCase ) for imp in imports: objects.extend([obj[1:-1] for obj in imp.split(""", """ )] ) line_index += 1 continue _a : Optional[Any] =_re_import_struct_key_value.search(_UpperCAmelCase ) if single_line_import_search is not None: _a : Any =[obj[1:-1] for obj in single_line_import_search.groups()[0].split(""", """ ) if len(_UpperCAmelCase ) > 0] objects.extend(_UpperCAmelCase ) elif line.startswith(""" """ * 8 + """\"""" ): objects.append(line[9:-3] ) line_index += 1 _a : List[str] ={"""none""": objects} # Let's continue with backend-specific objects in _import_structure while not lines[line_index].startswith("""if TYPE_CHECKING""" ): # If the line is an if not is_backend_available, we grab all objects associated. _a : int =find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: _a : Dict =None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 _a : Optional[Any] =[] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(""" """ * 4 ): _a : int =lines[line_index] if _re_import_struct_add_one.search(_UpperCAmelCase ) is not None: objects.append(_re_import_struct_add_one.search(_UpperCAmelCase ).groups()[0] ) elif _re_import_struct_add_many.search(_UpperCAmelCase ) is not None: _a : Any =_re_import_struct_add_many.search(_UpperCAmelCase ).groups()[0].split(""", """ ) _a : Tuple =[obj[1:-1] for obj in imports if len(_UpperCAmelCase ) > 0] objects.extend(_UpperCAmelCase ) elif _re_between_brackets.search(_UpperCAmelCase ) is not None: _a : Dict =_re_between_brackets.search(_UpperCAmelCase ).groups()[0].split(""", """ ) _a : Dict =[obj[1:-1] for obj in imports if len(_UpperCAmelCase ) > 0] objects.extend(_UpperCAmelCase ) elif _re_quote_object.search(_UpperCAmelCase ) is not None: objects.append(_re_quote_object.search(_UpperCAmelCase ).groups()[0] ) elif line.startswith(""" """ * 8 + """\"""" ): objects.append(line[9:-3] ) elif line.startswith(""" """ * 12 + """\"""" ): objects.append(line[13:-3] ) line_index += 1 _a : Any =objects else: line_index += 1 # At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend _a : Optional[Any] =[] while ( line_index < len(_UpperCAmelCase ) and find_backend(lines[line_index] ) is None and not lines[line_index].startswith("""else""" ) ): _a : Tuple =lines[line_index] _a : Dict =_re_import.search(_UpperCAmelCase ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(""", """ ) ) elif line.startswith(""" """ * 8 ): objects.append(line[8:-2] ) line_index += 1 _a : Tuple ={"""none""": objects} # Let's continue with backend-specific objects while line_index < len(_UpperCAmelCase ): # If the line is an if is_backend_available, we grab all objects associated. _a : Optional[Any] =find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: _a : Dict =None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 _a : int =[] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(""" """ * 8 ): _a : int =lines[line_index] _a : List[str] =_re_import.search(_UpperCAmelCase ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(""", """ ) ) elif line.startswith(""" """ * 12 ): objects.append(line[12:-2] ) line_index += 1 _a : List[Any] =objects else: line_index += 1 return import_dict_objects, type_hint_objects def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Dict ,_UpperCAmelCase : Any ) -> int: def find_duplicates(_UpperCAmelCase : Union[str, Any] ): return [k for k, v in collections.Counter(_UpperCAmelCase ).items() if v > 1] if list(import_dict_objects.keys() ) != list(type_hint_objects.keys() ): return ["Both sides of the init do not have the same backends!"] _a : List[str] =[] for key in import_dict_objects.keys(): _a : Optional[int] =find_duplicates(import_dict_objects[key] ) if duplicate_imports: errors.append(F"Duplicate _import_structure definitions for: {duplicate_imports}" ) _a : List[Any] =find_duplicates(type_hint_objects[key] ) if duplicate_type_hints: errors.append(F"Duplicate TYPE_CHECKING objects for: {duplicate_type_hints}" ) if sorted(set(import_dict_objects[key] ) ) != sorted(set(type_hint_objects[key] ) ): _a : Any ="""base imports""" if key == """none""" else F"{key} backend" errors.append(F"Differences for {name}:" ) for a in type_hint_objects[key]: if a not in import_dict_objects[key]: errors.append(F" {a} in TYPE_HINT but not in _import_structure." ) for a in import_dict_objects[key]: if a not in type_hint_objects[key]: errors.append(F" {a} in _import_structure but not in TYPE_HINT." ) return errors def SCREAMING_SNAKE_CASE_ ( ) -> Any: _a : Any =[] for root, _, files in os.walk(_UpperCAmelCase ): if "__init__.py" in files: _a : Tuple =os.path.join(_UpperCAmelCase ,"""__init__.py""" ) _a : Any =parse_init(_UpperCAmelCase ) if objects is not None: _a : Any =analyze_results(*_UpperCAmelCase ) if len(_UpperCAmelCase ) > 0: _a : str =F"Problem in {fname}, both halves do not define the same objects.\n{errors[0]}" failures.append("""\n""".join(_UpperCAmelCase ) ) if len(_UpperCAmelCase ) > 0: raise ValueError("""\n\n""".join(_UpperCAmelCase ) ) def SCREAMING_SNAKE_CASE_ ( ) -> List[Any]: _a : Dict =[] for path, directories, files in os.walk(_UpperCAmelCase ): for folder in directories: # Ignore private modules if folder.startswith("""_""" ): directories.remove(_UpperCAmelCase ) continue # Ignore leftovers from branches (empty folders apart from pycache) if len(list((Path(_UpperCAmelCase ) / folder).glob("""*.py""" ) ) ) == 0: continue _a : Optional[Any] =str((Path(_UpperCAmelCase ) / folder).relative_to(_UpperCAmelCase ) ) _a : Any =short_path.replace(os.path.sep ,""".""" ) submodules.append(_UpperCAmelCase ) for fname in files: if fname == "__init__.py": continue _a : Any =str((Path(_UpperCAmelCase ) / fname).relative_to(_UpperCAmelCase ) ) _a : List[str] =short_path.replace(""".py""" ,"""""" ).replace(os.path.sep ,""".""" ) if len(submodule.split(""".""" ) ) == 1: submodules.append(_UpperCAmelCase ) return submodules A__: int = [ '''convert_pytorch_checkpoint_to_tf2''', '''modeling_flax_pytorch_utils''', '''models.esm.openfold_utils''', ] def SCREAMING_SNAKE_CASE_ ( ) -> Optional[Any]: # This is to make sure the transformers module imported is the one in the repo. from transformers.utils import direct_transformers_import _a : int =direct_transformers_import(_UpperCAmelCase ) _a : Any =set(transformers._import_structure.keys() ) # This contains all the base keys of the _import_structure object defined in the init, but if the user is missing # some optional dependencies, they may not have all of them. Thus we read the init to read all additions and # (potentiall re-) add them. with open(os.path.join(_UpperCAmelCase ,"""__init__.py""" ) ,"""r""" ) as f: _a : Tuple =f.read() import_structure_keys.update(set(re.findall(R"""import_structure\[\"([^\"]*)\"\]""" ,_UpperCAmelCase ) ) ) _a : List[str] =[ module for module in get_transformers_submodules() if module not in IGNORE_SUBMODULES and module not in import_structure_keys ] if len(_UpperCAmelCase ) > 0: _a : Optional[int] ="""\n""".join(F"- {module}" for module in module_not_registered ) raise ValueError( """The following submodules are not properly registed in the main init of Transformers:\n""" F"{list_of_modules}\n" """Make sure they appear somewhere in the keys of `_import_structure` with an empty list as value.""" ) if __name__ == "__main__": check_all_inits() check_submodules()
276
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A__: Dict = logging.get_logger(__name__) A__: Tuple = { '''weiweishi/roc-bert-base-zh''': '''https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json''', } class A__ ( UpperCAmelCase__ ): __UpperCamelCase : Tuple = "roc_bert" def __init__( self :Optional[int] , SCREAMING_SNAKE_CASE :Tuple=3_0_5_2_2 , SCREAMING_SNAKE_CASE :List[str]=7_6_8 , SCREAMING_SNAKE_CASE :Dict=1_2 , SCREAMING_SNAKE_CASE :List[str]=1_2 , SCREAMING_SNAKE_CASE :Tuple=3_0_7_2 , SCREAMING_SNAKE_CASE :List[Any]="gelu" , SCREAMING_SNAKE_CASE :Union[str, Any]=0.1 , SCREAMING_SNAKE_CASE :List[Any]=0.1 , SCREAMING_SNAKE_CASE :int=5_1_2 , SCREAMING_SNAKE_CASE :Optional[Any]=2 , SCREAMING_SNAKE_CASE :Union[str, Any]=0.02 , SCREAMING_SNAKE_CASE :Optional[Any]=1e-12 , SCREAMING_SNAKE_CASE :Any=True , SCREAMING_SNAKE_CASE :List[Any]=0 , SCREAMING_SNAKE_CASE :Optional[int]="absolute" , SCREAMING_SNAKE_CASE :Union[str, Any]=None , SCREAMING_SNAKE_CASE :List[Any]=True , SCREAMING_SNAKE_CASE :int=True , SCREAMING_SNAKE_CASE :Optional[int]=7_6_8 , SCREAMING_SNAKE_CASE :Optional[Any]=9_1_0 , SCREAMING_SNAKE_CASE :Union[str, Any]=5_1_2 , SCREAMING_SNAKE_CASE :str=2_4_8_5_8 , SCREAMING_SNAKE_CASE :List[Any]=True , **SCREAMING_SNAKE_CASE :Tuple , ) -> Optional[int]: '''simple docstring''' _a : List[str] =vocab_size _a : List[str] =max_position_embeddings _a : Optional[Any] =hidden_size _a : List[Any] =num_hidden_layers _a : List[str] =num_attention_heads _a : int =intermediate_size _a : Any =hidden_act _a : Dict =hidden_dropout_prob _a : int =attention_probs_dropout_prob _a : str =initializer_range _a : Optional[int] =type_vocab_size _a : Any =layer_norm_eps _a : Any =use_cache _a : Optional[int] =enable_pronunciation _a : Optional[Any] =enable_shape _a : Optional[Any] =pronunciation_embed_dim _a : Tuple =pronunciation_vocab_size _a : Union[str, Any] =shape_embed_dim _a : Any =shape_vocab_size _a : Tuple =concat_input _a : List[str] =position_embedding_type _a : List[str] =classifier_dropout super().__init__(pad_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE )
276
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A__: Union[str, Any] = logging.get_logger(__name__) A__: Dict = { '''google/realm-cc-news-pretrained-embedder''': ( '''https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/config.json''' ), '''google/realm-cc-news-pretrained-encoder''': ( '''https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/config.json''' ), '''google/realm-cc-news-pretrained-scorer''': ( '''https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/config.json''' ), '''google/realm-cc-news-pretrained-openqa''': ( '''https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/config.json''' ), '''google/realm-orqa-nq-openqa''': '''https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/config.json''', '''google/realm-orqa-nq-reader''': '''https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/config.json''', '''google/realm-orqa-wq-openqa''': '''https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/config.json''', '''google/realm-orqa-wq-reader''': '''https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/config.json''', # See all REALM models at https://huggingface.co/models?filter=realm } class A__ ( UpperCAmelCase__ ): __UpperCamelCase : Tuple = "realm" def __init__( self :Any , SCREAMING_SNAKE_CASE :List[Any]=3_0_5_2_2 , SCREAMING_SNAKE_CASE :Optional[Any]=7_6_8 , SCREAMING_SNAKE_CASE :List[str]=1_2_8 , SCREAMING_SNAKE_CASE :Any=1_2 , SCREAMING_SNAKE_CASE :Any=1_2 , SCREAMING_SNAKE_CASE :Optional[Any]=8 , SCREAMING_SNAKE_CASE :Tuple=3_0_7_2 , SCREAMING_SNAKE_CASE :Tuple="gelu_new" , SCREAMING_SNAKE_CASE :Optional[int]=0.1 , SCREAMING_SNAKE_CASE :int=0.1 , SCREAMING_SNAKE_CASE :List[str]=5_1_2 , SCREAMING_SNAKE_CASE :List[Any]=2 , SCREAMING_SNAKE_CASE :Optional[Any]=0.02 , SCREAMING_SNAKE_CASE :Union[str, Any]=1e-12 , SCREAMING_SNAKE_CASE :Optional[int]=2_5_6 , SCREAMING_SNAKE_CASE :Optional[int]=1_0 , SCREAMING_SNAKE_CASE :List[Any]=1e-3 , SCREAMING_SNAKE_CASE :int=5 , SCREAMING_SNAKE_CASE :Optional[Any]=3_2_0 , SCREAMING_SNAKE_CASE :Tuple=1_3_3_5_3_7_1_8 , SCREAMING_SNAKE_CASE :int=5_0_0_0 , SCREAMING_SNAKE_CASE :Dict=1 , SCREAMING_SNAKE_CASE :Union[str, Any]=0 , SCREAMING_SNAKE_CASE :str=2 , **SCREAMING_SNAKE_CASE :Union[str, Any] , ) -> Optional[int]: '''simple docstring''' super().__init__(pad_token_id=SCREAMING_SNAKE_CASE , bos_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) # Common config _a : Tuple =vocab_size _a : List[Any] =max_position_embeddings _a : List[Any] =hidden_size _a : Any =retriever_proj_size _a : List[Any] =num_hidden_layers _a : int =num_attention_heads _a : Optional[Any] =num_candidates _a : Optional[Any] =intermediate_size _a : Tuple =hidden_act _a : Optional[Any] =hidden_dropout_prob _a : Any =attention_probs_dropout_prob _a : Optional[Any] =initializer_range _a : List[str] =type_vocab_size _a : str =layer_norm_eps # Reader config _a : Tuple =span_hidden_size _a : List[Any] =max_span_width _a : Optional[Any] =reader_layer_norm_eps _a : int =reader_beam_size _a : Tuple =reader_seq_len # Retrieval config _a : Optional[Any] =num_block_records _a : Any =searcher_beam_size
276
'''simple docstring''' class A__ : def __init__( self :List[str] ) -> List[Any]: '''simple docstring''' _a : Tuple =0 _a : Any =0 _a : int ={} def __UpperCAmelCase ( self :Any , SCREAMING_SNAKE_CASE :List[str] ) -> Optional[int]: '''simple docstring''' if vertex not in self.adjacency: _a : Dict ={} self.num_vertices += 1 def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Any ) -> List[str]: '''simple docstring''' self.add_vertex(SCREAMING_SNAKE_CASE ) self.add_vertex(SCREAMING_SNAKE_CASE ) if head == tail: return _a : Any =weight _a : Tuple =weight def __UpperCAmelCase ( self :Dict ) -> Optional[int]: '''simple docstring''' _a : Union[str, Any] =self.get_edges() for edge in edges: _a , _a , _a : List[str] =edge edges.remove((tail, head, weight) ) for i in range(len(SCREAMING_SNAKE_CASE ) ): _a : str =list(edges[i] ) edges.sort(key=lambda SCREAMING_SNAKE_CASE : e[2] ) for i in range(len(SCREAMING_SNAKE_CASE ) - 1 ): if edges[i][2] >= edges[i + 1][2]: _a : Union[str, Any] =edges[i][2] + 1 for edge in edges: _a , _a , _a : Tuple =edge _a : Tuple =weight _a : List[Any] =weight def __str__( self :int ) -> str: '''simple docstring''' _a : int ="""""" for tail in self.adjacency: for head in self.adjacency[tail]: _a : str =self.adjacency[head][tail] string += f"{head} -> {tail} == {weight}\n" return string.rstrip("""\n""" ) def __UpperCAmelCase ( self :Optional[int] ) -> Optional[Any]: '''simple docstring''' _a : Union[str, Any] =[] for tail in self.adjacency: for head in self.adjacency[tail]: output.append((tail, head, self.adjacency[head][tail]) ) return output def __UpperCAmelCase ( self :List[Any] ) -> List[Any]: '''simple docstring''' return self.adjacency.keys() @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :Dict=None , SCREAMING_SNAKE_CASE :List[Any]=None ) -> Optional[int]: '''simple docstring''' _a : str =Graph() if vertices is None: _a : Union[str, Any] =[] if edges is None: _a : List[Any] =[] for vertex in vertices: g.add_vertex(SCREAMING_SNAKE_CASE ) for edge in edges: g.add_edge(*SCREAMING_SNAKE_CASE ) return g class A__ : def __init__( self :Optional[int] ) -> Union[str, Any]: '''simple docstring''' _a : Optional[int] ={} _a : List[str] ={} def __len__( self :List[Any] ) -> List[Any]: '''simple docstring''' return len(self.parent ) def __UpperCAmelCase ( self :Tuple , SCREAMING_SNAKE_CASE :Tuple ) -> Dict: '''simple docstring''' if item in self.parent: return self.find(SCREAMING_SNAKE_CASE ) _a : Optional[Any] =item _a : List[str] =0 return item def __UpperCAmelCase ( self :int , SCREAMING_SNAKE_CASE :Dict ) -> List[str]: '''simple docstring''' if item not in self.parent: return self.make_set(SCREAMING_SNAKE_CASE ) if item != self.parent[item]: _a : str =self.find(self.parent[item] ) return self.parent[item] def __UpperCAmelCase ( self :Optional[int] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :List[Any] ) -> Optional[Any]: '''simple docstring''' _a : Optional[int] =self.find(SCREAMING_SNAKE_CASE ) _a : Dict =self.find(SCREAMING_SNAKE_CASE ) if roota == roota: return roota if self.rank[roota] > self.rank[roota]: _a : Any =roota return roota if self.rank[roota] < self.rank[roota]: _a : List[str] =roota return roota if self.rank[roota] == self.rank[roota]: self.rank[roota] += 1 _a : List[Any] =roota return roota return None @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :Dict ) -> Union[str, Any]: '''simple docstring''' _a : Any =graph.num_vertices _a : Union[str, Any] =Graph.UnionFind() _a : Optional[int] =[] while num_components > 1: _a : str ={} for vertex in graph.get_vertices(): _a : List[str] =-1 _a : Any =graph.get_edges() for edge in edges: _a , _a , _a : Tuple =edge edges.remove((tail, head, weight) ) for edge in edges: _a , _a , _a : Any =edge _a : Any =union_find.find(SCREAMING_SNAKE_CASE ) _a : List[Any] =union_find.find(SCREAMING_SNAKE_CASE ) if seta != seta: if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight: _a : Optional[int] =[head, tail, weight] if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight: _a : List[Any] =[head, tail, weight] for vertex in cheap_edge: if cheap_edge[vertex] != -1: _a , _a , _a : Optional[Any] =cheap_edge[vertex] if union_find.find(SCREAMING_SNAKE_CASE ) != union_find.find(SCREAMING_SNAKE_CASE ): union_find.union(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) mst_edges.append(cheap_edge[vertex] ) _a : str =num_components - 1 _a : str =Graph.build(edges=SCREAMING_SNAKE_CASE ) return mst
276
1
'''simple docstring''' def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : list ) -> list: if any(not isinstance(_UpperCAmelCase ,_UpperCAmelCase ) or x < 0 for x in sequence ): raise TypeError("""Sequence must be list of non-negative integers""" ) for _ in range(len(_UpperCAmelCase ) ): for i, (rod_upper, rod_lower) in enumerate(zip(_UpperCAmelCase ,sequence[1:] ) ): if rod_upper > rod_lower: sequence[i] -= rod_upper - rod_lower sequence[i + 1] += rod_upper - rod_lower return sequence if __name__ == "__main__": assert bead_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5] assert bead_sort([7, 9, 4, 3, 5]) == [3, 4, 5, 7, 9]
276
'''simple docstring''' from datetime import datetime import requests from bsa import BeautifulSoup if __name__ == "__main__": A__: Union[str, Any] = input('''Enter image url: ''').strip() print(F"Downloading image from {url} ...") A__: Tuple = BeautifulSoup(requests.get(url).content, '''html.parser''') # The image URL is in the content field of the first meta tag with property og:image A__: Union[str, Any] = soup.find('''meta''', {'''property''': '''og:image'''})['''content'''] A__: List[Any] = requests.get(image_url).content A__: List[str] = F"{datetime.now():%Y-%m-%d_%H:%M:%S}.jpg" with open(file_name, '''wb''') as fp: fp.write(image_data) print(F"Done. Image saved to disk as {file_name}.")
276
1
'''simple docstring''' class A__ : def __init__( self :List[Any] ) -> None: '''simple docstring''' _a : dict[str, TrieNode] ={} # Mapping from char to TrieNode _a : List[str] =False def __UpperCAmelCase ( self :Tuple , SCREAMING_SNAKE_CASE :list[str] ) -> None: '''simple docstring''' for word in words: self.insert(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :str ) -> None: '''simple docstring''' _a : str =self for char in word: if char not in curr.nodes: _a : Dict =TrieNode() _a : List[Any] =curr.nodes[char] _a : int =True def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :str ) -> bool: '''simple docstring''' _a : int =self for char in word: if char not in curr.nodes: return False _a : List[Any] =curr.nodes[char] return curr.is_leaf def __UpperCAmelCase ( self :Dict , SCREAMING_SNAKE_CASE :str ) -> None: '''simple docstring''' def _delete(SCREAMING_SNAKE_CASE :TrieNode , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :int ) -> bool: if index == len(SCREAMING_SNAKE_CASE ): # If word does not exist if not curr.is_leaf: return False _a : Any =False return len(curr.nodes ) == 0 _a : int =word[index] _a : int =curr.nodes.get(SCREAMING_SNAKE_CASE ) # If char not in current trie node if not char_node: return False # Flag to check if node can be deleted _a : List[Any] =_delete(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , index + 1 ) if delete_curr: del curr.nodes[char] return len(curr.nodes ) == 0 return delete_curr _delete(self , SCREAMING_SNAKE_CASE , 0 ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : TrieNode ,_UpperCAmelCase : str ) -> None: if node.is_leaf: print(_UpperCAmelCase ,end=""" """ ) for key, value in node.nodes.items(): print_words(_UpperCAmelCase ,word + key ) def SCREAMING_SNAKE_CASE_ ( ) -> bool: _a : List[str] ="""banana bananas bandana band apple all beast""".split() _a : List[Any] =TrieNode() root.insert_many(_UpperCAmelCase ) # print_words(root, "") assert all(root.find(_UpperCAmelCase ) for word in words ) assert root.find("""banana""" ) assert not root.find("""bandanas""" ) assert not root.find("""apps""" ) assert root.find("""apple""" ) assert root.find("""all""" ) root.delete("""all""" ) assert not root.find("""all""" ) root.delete("""banana""" ) assert not root.find("""banana""" ) assert root.find("""bananas""" ) return True def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : bool ) -> None: print(str(_UpperCAmelCase ) ,"""works!""" if passes else """doesn't work :(""" ) def SCREAMING_SNAKE_CASE_ ( ) -> None: assert test_trie() def SCREAMING_SNAKE_CASE_ ( ) -> None: print_results("""Testing trie functionality""" ,test_trie() ) if __name__ == "__main__": main()
276
'''simple docstring''' A__: Tuple = ''' # Installazione di Transformers ! pip install transformers datasets # Per installare dalla fonte invece dell\'ultima versione rilasciata, commenta il comando sopra e # rimuovi la modalità commento al comando seguente. # ! pip install git+https://github.com/huggingface/transformers.git ''' A__: Tuple = [{'''type''': '''code''', '''content''': INSTALL_CONTENT}] A__: Any = { '''{processor_class}''': '''FakeProcessorClass''', '''{model_class}''': '''FakeModelClass''', '''{object_class}''': '''FakeObjectClass''', }
276
1
'''simple docstring''' def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int = 3 ,_UpperCAmelCase : int = 7 ,_UpperCAmelCase : int = 1000000 ) -> int: _a : Dict =0 _a : Optional[int] =1 for current_denominator in range(1 ,limit + 1 ): _a : str =current_denominator * numerator // denominator if current_denominator % denominator == 0: current_numerator -= 1 if current_numerator * max_denominator > current_denominator * max_numerator: _a : Dict =current_numerator _a : str =current_denominator return max_numerator if __name__ == "__main__": print(solution(numerator=3, denominator=7, limit=100_0000))
276
'''simple docstring''' A__: Optional[int] = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] A__: Any = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] A__: int = { 0: '''Sunday''', 1: '''Monday''', 2: '''Tuesday''', 3: '''Wednesday''', 4: '''Thursday''', 5: '''Friday''', 6: '''Saturday''', } def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ,_UpperCAmelCase : int ,_UpperCAmelCase : int ) -> str: assert len(str(_UpperCAmelCase ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 12, "month should be between 1 to 12" assert 1 <= day <= 31, "day should be between 1 to 31" # Doomsday algorithm: _a : List[str] =year // 100 _a : List[str] =(5 * (century % 4) + 2) % 7 _a : Optional[int] =year % 100 _a : Any =centurian % 12 _a : int =( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 _a : Optional[Any] =( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 400) == 0) else DOOMSDAY_LEAP[month - 1] ) _a : str =(dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
276
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available A__: List[Any] = { '''configuration_tapas''': ['''TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''TapasConfig'''], '''tokenization_tapas''': ['''TapasTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Optional[Any] = [ '''TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TapasForMaskedLM''', '''TapasForQuestionAnswering''', '''TapasForSequenceClassification''', '''TapasModel''', '''TapasPreTrainedModel''', '''load_tf_weights_in_tapas''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Tuple = [ '''TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFTapasForMaskedLM''', '''TFTapasForQuestionAnswering''', '''TFTapasForSequenceClassification''', '''TFTapasModel''', '''TFTapasPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_tapas import TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP, TapasConfig from .tokenization_tapas import TapasTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tapas import ( TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasPreTrainedModel, load_tf_weights_in_tapas, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_tapas import ( TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST, TFTapasForMaskedLM, TFTapasForQuestionAnswering, TFTapasForSequenceClassification, TFTapasModel, TFTapasPreTrainedModel, ) else: import sys A__: Optional[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
276
'''simple docstring''' from __future__ import annotations from typing import TypedDict class A__ ( UpperCAmelCase__ ): __UpperCamelCase : str __UpperCamelCase : int def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ) -> list[str]: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError("""The parameter s type must be str.""" ) return [s[i:] + s[:i] for i in range(len(_UpperCAmelCase ) )] def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ) -> BWTTransformDict: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError("""The parameter s type must be str.""" ) if not s: raise ValueError("""The parameter s must not be empty.""" ) _a : List[Any] =all_rotations(_UpperCAmelCase ) rotations.sort() # sort the list of rotations in alphabetically order # make a string composed of the last char of each rotation _a : BWTTransformDict ={ "bwt_string": "".join([word[-1] for word in rotations] ), "idx_original_string": rotations.index(_UpperCAmelCase ), } return response def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : int ) -> str: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError("""The parameter bwt_string type must be str.""" ) if not bwt_string: raise ValueError("""The parameter bwt_string must not be empty.""" ) try: _a : List[str] =int(_UpperCAmelCase ) except ValueError: raise TypeError( """The parameter idx_original_string type must be int or passive""" """ of cast to int.""" ) if idx_original_string < 0: raise ValueError("""The parameter idx_original_string must not be lower than 0.""" ) if idx_original_string >= len(_UpperCAmelCase ): raise ValueError( """The parameter idx_original_string must be lower than""" """ len(bwt_string).""" ) _a : Optional[int] =[""""""] * len(_UpperCAmelCase ) for _ in range(len(_UpperCAmelCase ) ): for i in range(len(_UpperCAmelCase ) ): _a : int =bwt_string[i] + ordered_rotations[i] ordered_rotations.sort() return ordered_rotations[idx_original_string] if __name__ == "__main__": A__: Any = '''Provide a string that I will generate its BWT transform: ''' A__: Union[str, Any] = input(entry_msg).strip() A__: Optional[int] = bwt_transform(s) print( F"Burrows Wheeler transform for string '{s}' results " F"in '{result['bwt_string']}'" ) A__: Union[str, Any] = reverse_bwt(result['''bwt_string'''], result['''idx_original_string''']) print( F"Reversing Burrows Wheeler transform for entry '{result['bwt_string']}' " F"we get original string '{original_string}'" )
276
1
'''simple docstring''' import logging import os from .state import PartialState class A__ ( logging.LoggerAdapter ): @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :Union[str, Any] ) -> Tuple: '''simple docstring''' _a : List[Any] =PartialState() return not main_process_only or (main_process_only and state.is_main_process) def __UpperCAmelCase ( self :Tuple , SCREAMING_SNAKE_CASE :Optional[int] , SCREAMING_SNAKE_CASE :Optional[int] , *SCREAMING_SNAKE_CASE :str , **SCREAMING_SNAKE_CASE :Any ) -> List[Any]: '''simple docstring''' if PartialState._shared_state == {}: raise RuntimeError( """You must initialize the accelerate state by calling either `PartialState()` or `Accelerator()` before using the logging utility.""" ) _a : List[str] =kwargs.pop("""main_process_only""" , SCREAMING_SNAKE_CASE ) _a : List[str] =kwargs.pop("""in_order""" , SCREAMING_SNAKE_CASE ) if self.isEnabledFor(SCREAMING_SNAKE_CASE ): if self._should_log(SCREAMING_SNAKE_CASE ): _a , _a : Any =self.process(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) self.logger.log(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) elif in_order: _a : Union[str, Any] =PartialState() for i in range(state.num_processes ): if i == state.process_index: _a , _a : Optional[Any] =self.process(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) self.logger.log(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) state.wait_for_everyone() def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : str = None ) -> Optional[int]: if log_level is None: _a : Union[str, Any] =os.environ.get("""ACCELERATE_LOG_LEVEL""" ,_UpperCAmelCase ) _a : Union[str, Any] =logging.getLogger(_UpperCAmelCase ) if log_level is not None: logger.setLevel(log_level.upper() ) logger.root.setLevel(log_level.upper() ) return MultiProcessAdapter(_UpperCAmelCase ,{} )
276
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available A__: List[str] = { '''configuration_chinese_clip''': [ '''CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ChineseCLIPConfig''', '''ChineseCLIPOnnxConfig''', '''ChineseCLIPTextConfig''', '''ChineseCLIPVisionConfig''', ], '''processing_chinese_clip''': ['''ChineseCLIPProcessor'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Optional[int] = ['''ChineseCLIPFeatureExtractor'''] A__: Any = ['''ChineseCLIPImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Dict = [ '''CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ChineseCLIPModel''', '''ChineseCLIPPreTrainedModel''', '''ChineseCLIPTextModel''', '''ChineseCLIPVisionModel''', ] if TYPE_CHECKING: from .configuration_chinese_clip import ( CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, ChineseCLIPConfig, ChineseCLIPOnnxConfig, ChineseCLIPTextConfig, ChineseCLIPVisionConfig, ) from .processing_chinese_clip import ChineseCLIPProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_chinese_clip import ChineseCLIPFeatureExtractor, ChineseCLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_chinese_clip import ( CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, ChineseCLIPModel, ChineseCLIPPreTrainedModel, ChineseCLIPTextModel, ChineseCLIPVisionModel, ) else: import sys A__: str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
276
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) A__: List[str] = {'''configuration_plbart''': ['''PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''PLBartConfig''']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: List[Any] = ['''PLBartTokenizer'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Union[str, Any] = [ '''PLBART_PRETRAINED_MODEL_ARCHIVE_LIST''', '''PLBartForCausalLM''', '''PLBartForConditionalGeneration''', '''PLBartForSequenceClassification''', '''PLBartModel''', '''PLBartPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_plbart import PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP, PLBartConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_plbart import PLBartTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_plbart import ( PLBART_PRETRAINED_MODEL_ARCHIVE_LIST, PLBartForCausalLM, PLBartForConditionalGeneration, PLBartForSequenceClassification, PLBartModel, PLBartPreTrainedModel, ) else: import sys A__: List[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
276
'''simple docstring''' class A__ : def __init__( self :List[Any] ) -> None: '''simple docstring''' _a : dict[str, TrieNode] ={} # Mapping from char to TrieNode _a : List[str] =False def __UpperCAmelCase ( self :Tuple , SCREAMING_SNAKE_CASE :list[str] ) -> None: '''simple docstring''' for word in words: self.insert(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :str ) -> None: '''simple docstring''' _a : str =self for char in word: if char not in curr.nodes: _a : Dict =TrieNode() _a : List[Any] =curr.nodes[char] _a : int =True def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :str ) -> bool: '''simple docstring''' _a : int =self for char in word: if char not in curr.nodes: return False _a : List[Any] =curr.nodes[char] return curr.is_leaf def __UpperCAmelCase ( self :Dict , SCREAMING_SNAKE_CASE :str ) -> None: '''simple docstring''' def _delete(SCREAMING_SNAKE_CASE :TrieNode , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :int ) -> bool: if index == len(SCREAMING_SNAKE_CASE ): # If word does not exist if not curr.is_leaf: return False _a : Any =False return len(curr.nodes ) == 0 _a : int =word[index] _a : int =curr.nodes.get(SCREAMING_SNAKE_CASE ) # If char not in current trie node if not char_node: return False # Flag to check if node can be deleted _a : List[Any] =_delete(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , index + 1 ) if delete_curr: del curr.nodes[char] return len(curr.nodes ) == 0 return delete_curr _delete(self , SCREAMING_SNAKE_CASE , 0 ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : TrieNode ,_UpperCAmelCase : str ) -> None: if node.is_leaf: print(_UpperCAmelCase ,end=""" """ ) for key, value in node.nodes.items(): print_words(_UpperCAmelCase ,word + key ) def SCREAMING_SNAKE_CASE_ ( ) -> bool: _a : List[str] ="""banana bananas bandana band apple all beast""".split() _a : List[Any] =TrieNode() root.insert_many(_UpperCAmelCase ) # print_words(root, "") assert all(root.find(_UpperCAmelCase ) for word in words ) assert root.find("""banana""" ) assert not root.find("""bandanas""" ) assert not root.find("""apps""" ) assert root.find("""apple""" ) assert root.find("""all""" ) root.delete("""all""" ) assert not root.find("""all""" ) root.delete("""banana""" ) assert not root.find("""banana""" ) assert root.find("""bananas""" ) return True def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : bool ) -> None: print(str(_UpperCAmelCase ) ,"""works!""" if passes else """doesn't work :(""" ) def SCREAMING_SNAKE_CASE_ ( ) -> None: assert test_trie() def SCREAMING_SNAKE_CASE_ ( ) -> None: print_results("""Testing trie functionality""" ,test_trie() ) if __name__ == "__main__": main()
276
1
'''simple docstring''' def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[int] ) -> Union[str, Any]: _a : Tuple =1 _a : List[str] =2 while i * i <= n: _a : Tuple =0 while n % i == 0: n //= i multiplicity += 1 n_divisors *= multiplicity + 1 i += 1 if n > 1: n_divisors *= 2 return n_divisors def SCREAMING_SNAKE_CASE_ ( ) -> Union[str, Any]: _a : List[Any] =1 _a : int =1 while True: i += 1 t_num += i if count_divisors(_UpperCAmelCase ) > 500: break return t_num if __name__ == "__main__": print(solution())
276
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available A__: str = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Tuple = ['''GPTSw3Tokenizer'''] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_swa import GPTSwaTokenizer else: import sys A__: str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
276
1
'''simple docstring''' import math def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ) -> bool: _a : Dict =math.loga(math.sqrt(4 * positive_integer + 1 ) / 2 + 1 / 2 ) return exponent == int(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : float = 1 / 12345 ) -> int: _a : Tuple =0 _a : Optional[Any] =0 _a : Optional[Any] =3 while True: _a : Optional[Any] =(integer**2 - 1) / 4 # if candidate is an integer, then there is a partition for k if partition_candidate == int(_UpperCAmelCase ): _a : List[Any] =int(_UpperCAmelCase ) total_partitions += 1 if check_partition_perfect(_UpperCAmelCase ): perfect_partitions += 1 if perfect_partitions > 0: if perfect_partitions / total_partitions < max_proportion: return int(_UpperCAmelCase ) integer += 1 if __name__ == "__main__": print(F"{solution() = }")
276
'''simple docstring''' import importlib.metadata import warnings from copy import deepcopy from packaging import version from ..utils import logging from .import_utils import is_accelerate_available, is_bitsandbytes_available if is_bitsandbytes_available(): import bitsandbytes as bnb import torch import torch.nn as nn from ..pytorch_utils import ConvaD if is_accelerate_available(): from accelerate import init_empty_weights from accelerate.utils import find_tied_parameters A__: str = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[Any] ,_UpperCAmelCase : List[str] ,_UpperCAmelCase : int ,_UpperCAmelCase : int=None ,_UpperCAmelCase : Optional[Any]=None ) -> Optional[Any]: # Recurse if needed if "." in tensor_name: _a : Union[str, Any] =tensor_name.split(""".""" ) for split in splits[:-1]: _a : Optional[Any] =getattr(_UpperCAmelCase ,_UpperCAmelCase ) if new_module is None: raise ValueError(F"{module} has no attribute {split}." ) _a : Optional[int] =new_module _a : Optional[int] =splits[-1] if tensor_name not in module._parameters and tensor_name not in module._buffers: raise ValueError(F"{module} does not have a parameter or a buffer named {tensor_name}." ) _a : Optional[Any] =tensor_name in module._buffers _a : str =getattr(_UpperCAmelCase ,_UpperCAmelCase ) if old_value.device == torch.device("""meta""" ) and device not in ["meta", torch.device("""meta""" )] and value is None: raise ValueError(F"{tensor_name} is on the meta device, we need a `value` to put in on {device}." ) _a : int =False _a : Tuple =False if is_buffer or not is_bitsandbytes_available(): _a : str =False _a : Optional[Any] =False else: _a : int =hasattr(bnb.nn ,"""Params4bit""" ) and isinstance(module._parameters[tensor_name] ,bnb.nn.Paramsabit ) _a : int =isinstance(module._parameters[tensor_name] ,bnb.nn.IntaParams ) if is_abit or is_abit: _a : Any =module._parameters[tensor_name] if param.device.type != "cuda": if value is None: _a : int =old_value.to(_UpperCAmelCase ) elif isinstance(_UpperCAmelCase ,torch.Tensor ): _a : str =value.to("""cpu""" ) if value.dtype == torch.inta: _a : int =version.parse(importlib.metadata.version("""bitsandbytes""" ) ) > version.parse( """0.37.2""" ) if not is_abit_serializable: raise ValueError( """Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. """ """Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`.""" ) else: _a : Dict =torch.tensor(_UpperCAmelCase ,device="""cpu""" ) # Support models using `Conv1D` in place of `nn.Linear` (e.g. gpt2) by transposing the weight matrix prior to quantization. # Since weights are saved in the correct "orientation", we skip transposing when loading. if issubclass(module.source_cls ,_UpperCAmelCase ) and fpaa_statistics is None: _a : int =new_value.T _a : Any =old_value.__dict__ if is_abit: _a : Any =bnb.nn.IntaParams(_UpperCAmelCase ,requires_grad=_UpperCAmelCase ,**_UpperCAmelCase ).to(_UpperCAmelCase ) elif is_abit: _a : Union[str, Any] =bnb.nn.Paramsabit(_UpperCAmelCase ,requires_grad=_UpperCAmelCase ,**_UpperCAmelCase ).to(_UpperCAmelCase ) _a : List[Any] =new_value if fpaa_statistics is not None: setattr(module.weight ,"""SCB""" ,fpaa_statistics.to(_UpperCAmelCase ) ) else: if value is None: _a : str =old_value.to(_UpperCAmelCase ) elif isinstance(_UpperCAmelCase ,torch.Tensor ): _a : Any =value.to(_UpperCAmelCase ) else: _a : str =torch.tensor(_UpperCAmelCase ,device=_UpperCAmelCase ) if is_buffer: _a : Optional[int] =new_value else: _a : Optional[Any] =nn.Parameter(_UpperCAmelCase ,requires_grad=old_value.requires_grad ) _a : Tuple =new_value def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : Union[str, Any]=None ,_UpperCAmelCase : List[Any]=None ,_UpperCAmelCase : str=None ,_UpperCAmelCase : Union[str, Any]=False ) -> Dict: for name, module in model.named_children(): if current_key_name is None: _a : Optional[int] =[] current_key_name.append(_UpperCAmelCase ) if (isinstance(_UpperCAmelCase ,nn.Linear ) or isinstance(_UpperCAmelCase ,_UpperCAmelCase )) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` if not any(key in """.""".join(_UpperCAmelCase ) for key in modules_to_not_convert ): with init_empty_weights(): if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): _a , _a : int =module.weight.shape else: _a : List[str] =module.in_features _a : Tuple =module.out_features if quantization_config.quantization_method() == "llm_int8": _a : Optional[Any] =bnb.nn.LinearabitLt( _UpperCAmelCase ,_UpperCAmelCase ,module.bias is not None ,has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight ,threshold=quantization_config.llm_inta_threshold ,) _a : Optional[Any] =True else: if ( quantization_config.llm_inta_skip_modules is not None and name in quantization_config.llm_inta_skip_modules ): pass else: _a : Dict =bnb.nn.Linearabit( _UpperCAmelCase ,_UpperCAmelCase ,module.bias is not None ,quantization_config.bnb_abit_compute_dtype ,compress_statistics=quantization_config.bnb_abit_use_double_quant ,quant_type=quantization_config.bnb_abit_quant_type ,) _a : List[Any] =True # Store the module class in case we need to transpose the weight later _a : int =type(_UpperCAmelCase ) # Force requires grad to False to avoid unexpected errors model._modules[name].requires_grad_(_UpperCAmelCase ) if len(list(module.children() ) ) > 0: _a , _a : List[Any] =_replace_with_bnb_linear( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,has_been_replaced=_UpperCAmelCase ,) # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : int=None ,_UpperCAmelCase : Union[str, Any]=None ,_UpperCAmelCase : Any=None ) -> Tuple: _a : Dict =["""lm_head"""] if modules_to_not_convert is None else modules_to_not_convert _a , _a : List[Any] =_replace_with_bnb_linear( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) if not has_been_replaced: logger.warning( """You are loading your model in 8bit or 4bit but no linear modules were found in your model.""" """ Please double check your model architecture, or submit an issue on github if you think this is""" """ a bug.""" ) return model def SCREAMING_SNAKE_CASE_ ( *_UpperCAmelCase : Any ,**_UpperCAmelCase : Any ) -> str: warnings.warn( """`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead""" ,_UpperCAmelCase ,) return replace_with_bnb_linear(*_UpperCAmelCase ,**_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( *_UpperCAmelCase : str ,**_UpperCAmelCase : Optional[int] ) -> Optional[int]: warnings.warn( """`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead""" ,_UpperCAmelCase ,) return set_module_quantized_tensor_to_device(*_UpperCAmelCase ,**_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ) -> Union[str, Any]: _a : Any =deepcopy(_UpperCAmelCase ) # this has 0 cost since it is done inside `init_empty_weights` context manager` tied_model.tie_weights() _a : List[Any] =find_tied_parameters(_UpperCAmelCase ) # For compatibility with Accelerate < 0.18 if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): _a : str =sum(list(tied_params.values() ) ,[] ) + list(tied_params.keys() ) else: _a : Optional[int] =sum(_UpperCAmelCase ,[] ) _a : List[Any] =len(_UpperCAmelCase ) > 0 # Check if it is a base model _a : Tuple =not hasattr(_UpperCAmelCase ,model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head _a : List[Any] =list(model.named_children() ) _a : Dict =[list_modules[-1][0]] # add last module together with tied weights _a : List[str] =set(_UpperCAmelCase ) - set(_UpperCAmelCase ) _a : str =list(set(_UpperCAmelCase ) ) + list(_UpperCAmelCase ) # remove ".weight" from the keys _a : List[Any] =[""".weight""", """.bias"""] _a : Any =[] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: _a : Any =name.replace(_UpperCAmelCase ,"""""" ) filtered_module_names.append(_UpperCAmelCase ) return filtered_module_names
276
1
'''simple docstring''' 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 SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[str] ,_UpperCAmelCase : List[str] ) -> int: # Load checkpoint _a : Dict =torch.load(_UpperCAmelCase ,map_location="""cpu""" ) _a : Union[str, Any] =chkpt["""model"""] # We have the base model one level deeper than the original XLM repository _a : Tuple ={} for k, v in state_dict.items(): if "pred_layer" in k: _a : Dict =v else: _a : int =v _a : List[str] =chkpt["""params"""] _a : Dict ={n: v for n, v in config.items() if not isinstance(_UpperCAmelCase ,(torch.FloatTensor, numpy.ndarray) )} _a : Dict =chkpt["""dico_word2id"""] _a : str ={s + """</w>""" if s.find("""@@""" ) == -1 and i > 13 else s.replace("""@@""" ,"""""" ): i for s, i in vocab.items()} # Save pytorch-model _a : Any =pytorch_dump_folder_path + """/""" + WEIGHTS_NAME _a : Optional[Any] =pytorch_dump_folder_path + """/""" + CONFIG_NAME _a : Optional[int] =pytorch_dump_folder_path + """/""" + VOCAB_FILES_NAMES["""vocab_file"""] print(F"Save PyTorch model to {pytorch_weights_dump_path}" ) torch.save(_UpperCAmelCase ,_UpperCAmelCase ) print(F"Save configuration file to {pytorch_config_dump_path}" ) with open(_UpperCAmelCase ,"""w""" ,encoding="""utf-8""" ) as f: f.write(json.dumps(_UpperCAmelCase ,indent=2 ) + """\n""" ) print(F"Save vocab file to {pytorch_config_dump_path}" ) with open(_UpperCAmelCase ,"""w""" ,encoding="""utf-8""" ) as f: f.write(json.dumps(_UpperCAmelCase ,indent=2 ) + """\n""" ) if __name__ == "__main__": A__: Union[str, Any] = 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.''' ) A__: Union[str, Any] = parser.parse_args() convert_xlm_checkpoint_to_pytorch(args.xlm_checkpoint_path, args.pytorch_dump_folder_path)
276
'''simple docstring''' import logging import os from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union from filelock import FileLock from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available A__: int = logging.getLogger(__name__) @dataclass class A__ : __UpperCamelCase : str __UpperCamelCase : List[str] __UpperCamelCase : Optional[List[str]] @dataclass class A__ : __UpperCamelCase : List[int] __UpperCamelCase : List[int] __UpperCamelCase : Optional[List[int]] = None __UpperCamelCase : Optional[List[int]] = None class A__ ( UpperCAmelCase__ ): __UpperCamelCase : str = "train" __UpperCamelCase : Tuple = "dev" __UpperCamelCase : str = "test" class A__ : @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :Union[Split, str] ) -> List[InputExample]: '''simple docstring''' raise NotImplementedError @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :str ) -> List[str]: '''simple docstring''' raise NotImplementedError @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :List[InputExample] , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :PreTrainedTokenizer , SCREAMING_SNAKE_CASE :str=False , SCREAMING_SNAKE_CASE :Optional[Any]="[CLS]" , SCREAMING_SNAKE_CASE :Optional[int]=1 , SCREAMING_SNAKE_CASE :Any="[SEP]" , SCREAMING_SNAKE_CASE :List[Any]=False , SCREAMING_SNAKE_CASE :Union[str, Any]=False , SCREAMING_SNAKE_CASE :List[str]=0 , SCREAMING_SNAKE_CASE :str=0 , SCREAMING_SNAKE_CASE :Dict=-1_0_0 , SCREAMING_SNAKE_CASE :Optional[int]=0 , SCREAMING_SNAKE_CASE :Tuple=True , ) -> List[InputFeatures]: '''simple docstring''' _a : str ={label: i for i, label in enumerate(SCREAMING_SNAKE_CASE )} _a : Tuple =[] for ex_index, example in enumerate(SCREAMING_SNAKE_CASE ): if ex_index % 1_0_0_0_0 == 0: logger.info("""Writing example %d of %d""" , SCREAMING_SNAKE_CASE , len(SCREAMING_SNAKE_CASE ) ) _a : Optional[Any] =[] _a : List[Any] =[] for word, label in zip(example.words , example.labels ): _a : Optional[int] =tokenizer.tokenize(SCREAMING_SNAKE_CASE ) # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space. if len(SCREAMING_SNAKE_CASE ) > 0: tokens.extend(SCREAMING_SNAKE_CASE ) # Use the real label id for the first token of the word, and padding ids for the remaining tokens label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(SCREAMING_SNAKE_CASE ) - 1) ) # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa. _a : Optional[int] =tokenizer.num_special_tokens_to_add() if len(SCREAMING_SNAKE_CASE ) > max_seq_length - special_tokens_count: _a : List[Any] =tokens[: (max_seq_length - special_tokens_count)] _a : Tuple =label_ids[: (max_seq_length - special_tokens_count)] # The convention in BERT is: # (a) For sequence pairs: # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP] # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1 # (b) For single sequences: # tokens: [CLS] the dog is hairy . [SEP] # type_ids: 0 0 0 0 0 0 0 # # Where "type_ids" are used to indicate whether this is the first # sequence or the second sequence. The embedding vectors for `type=0` and # `type=1` were learned during pre-training and are added to the wordpiece # embedding vector (and position vector). This is not *strictly* necessary # since the [SEP] token unambiguously separates the sequences, but it makes # it easier for the model to learn the concept of sequences. # # For classification tasks, the first vector (corresponding to [CLS]) is # used as the "sentence vector". Note that this only makes sense because # the entire model is fine-tuned. tokens += [sep_token] label_ids += [pad_token_label_id] if sep_token_extra: # roberta uses an extra separator b/w pairs of sentences tokens += [sep_token] label_ids += [pad_token_label_id] _a : Dict =[sequence_a_segment_id] * len(SCREAMING_SNAKE_CASE ) if cls_token_at_end: tokens += [cls_token] label_ids += [pad_token_label_id] segment_ids += [cls_token_segment_id] else: _a : Any =[cls_token] + tokens _a : Dict =[pad_token_label_id] + label_ids _a : Union[str, Any] =[cls_token_segment_id] + segment_ids _a : List[str] =tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE ) # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. _a : Optional[int] =[1 if mask_padding_with_zero else 0] * len(SCREAMING_SNAKE_CASE ) # Zero-pad up to the sequence length. _a : Union[str, Any] =max_seq_length - len(SCREAMING_SNAKE_CASE ) if pad_on_left: _a : Optional[Any] =([pad_token] * padding_length) + input_ids _a : Optional[int] =([0 if mask_padding_with_zero else 1] * padding_length) + input_mask _a : Union[str, Any] =([pad_token_segment_id] * padding_length) + segment_ids _a : Dict =([pad_token_label_id] * padding_length) + label_ids else: input_ids += [pad_token] * padding_length input_mask += [0 if mask_padding_with_zero else 1] * padding_length segment_ids += [pad_token_segment_id] * padding_length label_ids += [pad_token_label_id] * padding_length assert len(SCREAMING_SNAKE_CASE ) == max_seq_length assert len(SCREAMING_SNAKE_CASE ) == max_seq_length assert len(SCREAMING_SNAKE_CASE ) == max_seq_length assert len(SCREAMING_SNAKE_CASE ) == max_seq_length if ex_index < 5: logger.info("""*** Example ***""" ) logger.info("""guid: %s""" , example.guid ) logger.info("""tokens: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in tokens] ) ) logger.info("""input_ids: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in input_ids] ) ) logger.info("""input_mask: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in input_mask] ) ) logger.info("""segment_ids: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in segment_ids] ) ) logger.info("""label_ids: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in label_ids] ) ) if "token_type_ids" not in tokenizer.model_input_names: _a : Tuple =None features.append( InputFeatures( input_ids=SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , token_type_ids=SCREAMING_SNAKE_CASE , label_ids=SCREAMING_SNAKE_CASE ) ) return features if is_torch_available(): import torch from torch import nn from torch.utils.data import Dataset class A__ ( UpperCAmelCase__ ): __UpperCamelCase : List[InputFeatures] __UpperCamelCase : int = nn.CrossEntropyLoss().ignore_index def __init__( self :Dict , SCREAMING_SNAKE_CASE :TokenClassificationTask , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :PreTrainedTokenizer , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Optional[int] = None , SCREAMING_SNAKE_CASE :int=False , SCREAMING_SNAKE_CASE :Split = Split.train , ) -> List[str]: '''simple docstring''' # Load data features from cache or dataset file _a : Optional[Any] =os.path.join( SCREAMING_SNAKE_CASE , """cached_{}_{}_{}""".format(mode.value , tokenizer.__class__.__name__ , str(SCREAMING_SNAKE_CASE ) ) , ) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. _a : List[str] =cached_features_file + """.lock""" with FileLock(SCREAMING_SNAKE_CASE ): if os.path.exists(SCREAMING_SNAKE_CASE ) and not overwrite_cache: logger.info(f"Loading features from cached file {cached_features_file}" ) _a : Any =torch.load(SCREAMING_SNAKE_CASE ) else: logger.info(f"Creating features from dataset file at {data_dir}" ) _a : Any =token_classification_task.read_examples_from_file(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # TODO clean up all this to leverage built-in features of tokenizers _a : List[str] =token_classification_task.convert_examples_to_features( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cls_token_at_end=bool(model_type in ["""xlnet"""] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ["""xlnet"""] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=SCREAMING_SNAKE_CASE , pad_on_left=bool(tokenizer.padding_side == """left""" ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info(f"Saving features into cached file {cached_features_file}" ) torch.save(self.features , SCREAMING_SNAKE_CASE ) def __len__( self :Optional[int] ) -> Union[str, Any]: '''simple docstring''' return len(self.features ) def __getitem__( self :Dict , SCREAMING_SNAKE_CASE :int ) -> InputFeatures: '''simple docstring''' return self.features[i] if is_tf_available(): import tensorflow as tf class A__ : __UpperCamelCase : List[InputFeatures] __UpperCamelCase : int = -100 def __init__( self :str , SCREAMING_SNAKE_CASE :TokenClassificationTask , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :PreTrainedTokenizer , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Optional[int] = None , SCREAMING_SNAKE_CASE :str=False , SCREAMING_SNAKE_CASE :Split = Split.train , ) -> Any: '''simple docstring''' _a : Tuple =token_classification_task.read_examples_from_file(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # TODO clean up all this to leverage built-in features of tokenizers _a : List[Any] =token_classification_task.convert_examples_to_features( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cls_token_at_end=bool(model_type in ["""xlnet"""] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ["""xlnet"""] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=SCREAMING_SNAKE_CASE , pad_on_left=bool(tokenizer.padding_side == """left""" ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) def gen(): for ex in self.features: if ex.token_type_ids is None: yield ( {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label_ids, ) else: yield ( { "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label_ids, ) if "token_type_ids" not in tokenizer.model_input_names: _a : Union[str, Any] =tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE , ({"""input_ids""": tf.intaa, """attention_mask""": tf.intaa}, tf.intaa) , ( {"""input_ids""": tf.TensorShape([None] ), """attention_mask""": tf.TensorShape([None] )}, tf.TensorShape([None] ), ) , ) else: _a : Union[str, Any] =tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE , ({"""input_ids""": tf.intaa, """attention_mask""": tf.intaa, """token_type_ids""": tf.intaa}, tf.intaa) , ( { """input_ids""": tf.TensorShape([None] ), """attention_mask""": tf.TensorShape([None] ), """token_type_ids""": tf.TensorShape([None] ), }, tf.TensorShape([None] ), ) , ) def __UpperCAmelCase ( self :Tuple ) -> Any: '''simple docstring''' _a : List[Any] =self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features ) ) ) return self.dataset def __len__( self :str ) -> Optional[int]: '''simple docstring''' return len(self.features ) def __getitem__( self :int , SCREAMING_SNAKE_CASE :str ) -> InputFeatures: '''simple docstring''' return self.features[i]
276
1
'''simple docstring''' def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ) -> Any: return [ { 0: [1, 2], 1: [0, 2], 2: [0, 1, 3, 5], 3: [2, 4], 4: [3], 5: [2, 6, 8], 6: [5, 7], 7: [6, 8], 8: [5, 7], }, { 0: [6], 1: [9], 2: [4, 5], 3: [4], 4: [2, 3], 5: [2], 6: [0, 7], 7: [6], 8: [], 9: [1], }, { 0: [4], 1: [6], 2: [], 3: [5, 6, 7], 4: [0, 6], 5: [3, 8, 9], 6: [1, 3, 4, 7], 7: [3, 6, 8, 9], 8: [5, 7], 9: [5, 7], }, { 0: [1, 3], 1: [0, 2, 4], 2: [1, 3, 4], 3: [0, 2, 4], 4: [1, 2, 3], }, ][index] def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : dict[int, list[int]] ) -> list[tuple[int, int]]: _a : Optional[int] =0 _a : Union[str, Any] =len(_UpperCAmelCase ) # No of vertices in graph _a : List[str] =[0] * n _a : int =[False] * n def dfs(_UpperCAmelCase : Any ,_UpperCAmelCase : List[str] ,_UpperCAmelCase : Any ,_UpperCAmelCase : Any ): _a : Optional[Any] =True _a : Optional[Any] =id_ id_ += 1 for to in graph[at]: if to == parent: pass elif not visited[to]: dfs(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,id_ ) _a : str =min(low[at] ,low[to] ) if id_ <= low[to]: bridges.append((at, to) if at < to else (to, at) ) else: # This edge is a back edge and cannot be a bridge _a : List[Any] =min(low[at] ,low[to] ) _a : list[tuple[int, int]] =[] for i in range(_UpperCAmelCase ): if not visited[i]: dfs(_UpperCAmelCase ,-1 ,_UpperCAmelCase ,id_ ) return bridges if __name__ == "__main__": import doctest doctest.testmod()
276
'''simple docstring''' from __future__ import annotations class A__ : def __init__( self :Union[str, Any] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :str ) -> Optional[int]: '''simple docstring''' _a , _a : List[str] =text, pattern _a , _a : Union[str, Any] =len(SCREAMING_SNAKE_CASE ), len(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Optional[int] , SCREAMING_SNAKE_CASE :str ) -> int: '''simple docstring''' for i in range(self.patLen - 1 , -1 , -1 ): if char == self.pattern[i]: return i return -1 def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :int ) -> int: '''simple docstring''' for i in range(self.patLen - 1 , -1 , -1 ): if self.pattern[i] != self.text[current_pos + i]: return current_pos + i return -1 def __UpperCAmelCase ( self :Union[str, Any] ) -> list[int]: '''simple docstring''' # searches pattern in text and returns index positions _a : Union[str, Any] =[] for i in range(self.textLen - self.patLen + 1 ): _a : Any =self.mismatch_in_text(SCREAMING_SNAKE_CASE ) if mismatch_index == -1: positions.append(SCREAMING_SNAKE_CASE ) else: _a : int =self.match_in_pattern(self.text[mismatch_index] ) _a : List[str] =( mismatch_index - match_index ) # shifting index lgtm [py/multiple-definition] return positions A__: Any = '''ABAABA''' A__: int = '''AB''' A__: Optional[int] = BoyerMooreSearch(text, pattern) A__: Optional[Any] = bms.bad_character_heuristic() if len(positions) == 0: print('''No match found''') else: print('''Pattern found in following positions: ''') print(positions)
276
1
'''simple docstring''' A__: Optional[int] = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] A__: Any = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] A__: int = { 0: '''Sunday''', 1: '''Monday''', 2: '''Tuesday''', 3: '''Wednesday''', 4: '''Thursday''', 5: '''Friday''', 6: '''Saturday''', } def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ,_UpperCAmelCase : int ,_UpperCAmelCase : int ) -> str: assert len(str(_UpperCAmelCase ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 12, "month should be between 1 to 12" assert 1 <= day <= 31, "day should be between 1 to 31" # Doomsday algorithm: _a : List[str] =year // 100 _a : List[str] =(5 * (century % 4) + 2) % 7 _a : Optional[int] =year % 100 _a : Any =centurian % 12 _a : int =( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 _a : Optional[Any] =( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 400) == 0) else DOOMSDAY_LEAP[month - 1] ) _a : str =(dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
276
'''simple docstring''' 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''' ) A__: Dict = None A__: Tuple = { '''7B''': 1_1008, '''13B''': 1_3824, '''30B''': 1_7920, '''65B''': 2_2016, '''70B''': 2_8672, } A__: Any = { '''7B''': 1, '''7Bf''': 1, '''13B''': 2, '''13Bf''': 2, '''30B''': 4, '''65B''': 8, '''70B''': 8, '''70Bf''': 8, } def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Optional[int]=1 ,_UpperCAmelCase : List[str]=256 ) -> Dict: return multiple_of * ((int(ffn_dim_multiplier * int(8 * n / 3 ) ) + multiple_of - 1) // multiple_of) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[Any] ) -> List[str]: with open(_UpperCAmelCase ,"""r""" ) as f: return json.load(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : Optional[Any] ) -> Tuple: with open(_UpperCAmelCase ,"""w""" ) as f: json.dump(_UpperCAmelCase ,_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : int ,_UpperCAmelCase : List[Any]=True ) -> Union[str, Any]: os.makedirs(_UpperCAmelCase ,exist_ok=_UpperCAmelCase ) _a : Union[str, Any] =os.path.join(_UpperCAmelCase ,"""tmp""" ) os.makedirs(_UpperCAmelCase ,exist_ok=_UpperCAmelCase ) _a : int =read_json(os.path.join(_UpperCAmelCase ,"""params.json""" ) ) _a : int =NUM_SHARDS[model_size] _a : Dict =params["""n_layers"""] _a : Union[str, Any] =params["""n_heads"""] _a : List[str] =n_heads // num_shards _a : int =params["""dim"""] _a : Union[str, Any] =dim // n_heads _a : int =1_0_0_0_0.0 _a : str =1.0 / (base ** (torch.arange(0 ,_UpperCAmelCase ,2 ).float() / dims_per_head)) if "n_kv_heads" in params: _a : str =params["""n_kv_heads"""] # for GQA / MQA _a : Optional[Any] =n_heads_per_shard // num_key_value_heads _a : Optional[int] =dim // num_key_value_heads else: # compatibility with other checkpoints _a : str =n_heads _a : Any =n_heads_per_shard _a : str =dim # permute for sliced rotary def permute(_UpperCAmelCase : Tuple ,_UpperCAmelCase : Optional[int]=n_heads ,_UpperCAmelCase : Optional[int]=dim ,_UpperCAmelCase : List[str]=dim ): return w.view(_UpperCAmelCase ,dima // n_heads // 2 ,2 ,_UpperCAmelCase ).transpose(1 ,2 ).reshape(_UpperCAmelCase ,_UpperCAmelCase ) 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.) _a : Any =torch.load(os.path.join(_UpperCAmelCase ,"""consolidated.00.pth""" ) ,map_location="""cpu""" ) else: # Sharded _a : List[Any] =[ torch.load(os.path.join(_UpperCAmelCase ,F"consolidated.{i:02d}.pth" ) ,map_location="""cpu""" ) for i in range(_UpperCAmelCase ) ] _a : Any =0 _a : Optional[int] ={"""weight_map""": {}} for layer_i in range(_UpperCAmelCase ): _a : List[str] =F"pytorch_model-{layer_i + 1}-of-{n_layers + 1}.bin" if model_size == "7B": # Unsharded _a : List[str] ={ 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. _a : Tuple ={ 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(), } _a : str =permute( torch.cat( [ loaded[i][F"layers.{layer_i}.attention.wq.weight"].view(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) for i in range(_UpperCAmelCase ) ] ,dim=0 ,).reshape(_UpperCAmelCase ,_UpperCAmelCase ) ) _a : Tuple =permute( torch.cat( [ loaded[i][F"layers.{layer_i}.attention.wk.weight"].view( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) for i in range(_UpperCAmelCase ) ] ,dim=0 ,).reshape(_UpperCAmelCase ,_UpperCAmelCase ) ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,) _a : Any =torch.cat( [ loaded[i][F"layers.{layer_i}.attention.wv.weight"].view( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) for i in range(_UpperCAmelCase ) ] ,dim=0 ,).reshape(_UpperCAmelCase ,_UpperCAmelCase ) _a : List[str] =torch.cat( [loaded[i][F"layers.{layer_i}.attention.wo.weight"] for i in range(_UpperCAmelCase )] ,dim=1 ) _a : Union[str, Any] =torch.cat( [loaded[i][F"layers.{layer_i}.feed_forward.w1.weight"] for i in range(_UpperCAmelCase )] ,dim=0 ) _a : Tuple =torch.cat( [loaded[i][F"layers.{layer_i}.feed_forward.w2.weight"] for i in range(_UpperCAmelCase )] ,dim=1 ) _a : Union[str, Any] =torch.cat( [loaded[i][F"layers.{layer_i}.feed_forward.w3.weight"] for i in range(_UpperCAmelCase )] ,dim=0 ) _a : str =inv_freq for k, v in state_dict.items(): _a : Any =filename param_count += v.numel() torch.save(_UpperCAmelCase ,os.path.join(_UpperCAmelCase ,_UpperCAmelCase ) ) _a : Union[str, Any] =F"pytorch_model-{n_layers + 1}-of-{n_layers + 1}.bin" if model_size == "7B": # Unsharded _a : List[str] ={ """model.embed_tokens.weight""": loaded["""tok_embeddings.weight"""], """model.norm.weight""": loaded["""norm.weight"""], """lm_head.weight""": loaded["""output.weight"""], } else: _a : int ={ """model.norm.weight""": loaded[0]["""norm.weight"""], """model.embed_tokens.weight""": torch.cat( [loaded[i]["""tok_embeddings.weight"""] for i in range(_UpperCAmelCase )] ,dim=1 ), """lm_head.weight""": torch.cat([loaded[i]["""output.weight"""] for i in range(_UpperCAmelCase )] ,dim=0 ), } for k, v in state_dict.items(): _a : Dict =filename param_count += v.numel() torch.save(_UpperCAmelCase ,os.path.join(_UpperCAmelCase ,_UpperCAmelCase ) ) # Write configs _a : Tuple ={"""total_size""": param_count * 2} write_json(_UpperCAmelCase ,os.path.join(_UpperCAmelCase ,"""pytorch_model.bin.index.json""" ) ) _a : Optional[Any] =params["""ffn_dim_multiplier"""] if """ffn_dim_multiplier""" in params else 1 _a : int =params["""multiple_of"""] if """multiple_of""" in params else 256 _a : List[Any] =LlamaConfig( hidden_size=_UpperCAmelCase ,intermediate_size=compute_intermediate_size(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) ,num_attention_heads=params["""n_heads"""] ,num_hidden_layers=params["""n_layers"""] ,rms_norm_eps=params["""norm_eps"""] ,num_key_value_heads=_UpperCAmelCase ,) config.save_pretrained(_UpperCAmelCase ) # 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.""" ) _a : Any =LlamaForCausalLM.from_pretrained(_UpperCAmelCase ,torch_dtype=torch.floataa ,low_cpu_mem_usage=_UpperCAmelCase ) # Avoid saving this as part of the config. del model.config._name_or_path print("""Saving in the Transformers format.""" ) model.save_pretrained(_UpperCAmelCase ,safe_serialization=_UpperCAmelCase ) shutil.rmtree(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ,_UpperCAmelCase : int ) -> Optional[Any]: # Initialize the tokenizer based on the `spm` model _a : List[str] =LlamaTokenizer if LlamaTokenizerFast is None else LlamaTokenizerFast print(F"Saving a {tokenizer_class.__name__} to {tokenizer_path}." ) _a : List[Any] =tokenizer_class(_UpperCAmelCase ) tokenizer.save_pretrained(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( ) -> Union[str, Any]: _a : List[str] =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=_UpperCAmelCase ,help="""Whether or not to save using `safetensors`.""" ) _a : Optional[Any] =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 ,) _a : List[Any] =os.path.join(args.input_dir ,"""tokenizer.model""" ) write_tokenizer(args.output_dir ,_UpperCAmelCase ) if __name__ == "__main__": main()
276
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) A__: Optional[int] = {'''configuration_unispeech''': ['''UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''UniSpeechConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Optional[Any] = [ '''UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST''', '''UniSpeechForCTC''', '''UniSpeechForPreTraining''', '''UniSpeechForSequenceClassification''', '''UniSpeechModel''', '''UniSpeechPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_unispeech import UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_unispeech import ( UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST, UniSpeechForCTC, UniSpeechForPreTraining, UniSpeechForSequenceClassification, UniSpeechModel, UniSpeechPreTrainedModel, ) else: import sys A__: Tuple = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
276
'''simple docstring''' import contextlib import os import sqlitea import pytest from datasets import Dataset, Features, Value from datasets.io.sql import SqlDatasetReader, SqlDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases, require_sqlalchemy def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Any ,_UpperCAmelCase : str ) -> Dict: assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ) 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 @require_sqlalchemy @pytest.mark.parametrize("""keep_in_memory""" ,[False, True] ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Optional[int] ,_UpperCAmelCase : str ) -> Optional[Any]: _a : Any =tmp_path / """cache""" _a : int ={"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): _a : Tuple =SqlDatasetReader( """dataset""" ,"""sqlite:///""" + sqlite_path ,cache_dir=_UpperCAmelCase ,keep_in_memory=_UpperCAmelCase ).read() _check_sql_dataset(_UpperCAmelCase ,_UpperCAmelCase ) @require_sqlalchemy @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 SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[Any] ,_UpperCAmelCase : Dict ,_UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : int ) -> List[Any]: _a : Union[str, Any] =tmp_path / """cache""" _a : str ={"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} _a : Optional[int] =features.copy() if features else default_expected_features _a : Union[str, Any] =( Features({feature: Value(_UpperCAmelCase ) for feature, dtype in features.items()} ) if features is not None else None ) _a : Optional[Any] =SqlDatasetReader("""dataset""" ,"""sqlite:///""" + sqlite_path ,features=_UpperCAmelCase ,cache_dir=_UpperCAmelCase ).read() _check_sql_dataset(_UpperCAmelCase ,_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[Any] ) -> List[str]: with contextlib.closing(sqlitea.connect(_UpperCAmelCase ) ) as con: _a : Any =con.cursor() cur.execute("""SELECT * FROM dataset""" ) for row in cur: yield row @require_sqlalchemy def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Dict ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : List[str] ) -> Union[str, Any]: _a : Union[str, Any] =tmp_path / """cache""" _a : Union[str, Any] =os.path.join(_UpperCAmelCase ,"""tmp.sql""" ) _a : Tuple =SqlDatasetReader("""dataset""" ,"""sqlite:///""" + sqlite_path ,cache_dir=_UpperCAmelCase ).read() SqlDatasetWriter(_UpperCAmelCase ,"""dataset""" ,"""sqlite:///""" + output_sqlite_path ,num_proc=1 ).write() _a : Tuple =iter_sql_file(_UpperCAmelCase ) _a : List[Any] =iter_sql_file(_UpperCAmelCase ) for rowa, rowa in zip(_UpperCAmelCase ,_UpperCAmelCase ): assert rowa == rowa @require_sqlalchemy def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Any ,_UpperCAmelCase : List[Any] ) -> Optional[int]: _a : int =tmp_path / """cache""" _a : Any =os.path.join(_UpperCAmelCase ,"""tmp.sql""" ) _a : Union[str, Any] =SqlDatasetReader("""dataset""" ,"""sqlite:///""" + sqlite_path ,cache_dir=_UpperCAmelCase ).read() SqlDatasetWriter(_UpperCAmelCase ,"""dataset""" ,"""sqlite:///""" + output_sqlite_path ,num_proc=2 ).write() _a : List[Any] =iter_sql_file(_UpperCAmelCase ) _a : str =iter_sql_file(_UpperCAmelCase ) for rowa, rowa in zip(_UpperCAmelCase ,_UpperCAmelCase ): assert rowa == rowa @require_sqlalchemy def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : str ,_UpperCAmelCase : List[Any] ) -> List[str]: _a : List[str] =tmp_path / """cache""" _a : Dict =os.path.join(_UpperCAmelCase ,"""tmp.sql""" ) _a : Optional[Any] =SqlDatasetReader("""dataset""" ,"""sqlite:///""" + sqlite_path ,cache_dir=_UpperCAmelCase ).read() with pytest.raises(_UpperCAmelCase ): SqlDatasetWriter(_UpperCAmelCase ,"""dataset""" ,"""sqlite:///""" + output_sqlite_path ,num_proc=0 ).write()
276
1
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import XLMRobertaTokenizerFast from diffusers import DDIMScheduler, KandinskyImgaImgPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class A__ ( UpperCAmelCase__ , unittest.TestCase ): __UpperCamelCase : List[str] = KandinskyImgaImgPipeline __UpperCamelCase : Optional[int] = ["prompt", "image_embeds", "negative_image_embeds", "image"] __UpperCamelCase : Any = [ "prompt", "negative_prompt", "image_embeds", "negative_image_embeds", "image", ] __UpperCamelCase : List[Any] = [ "generator", "height", "width", "strength", "guidance_scale", "negative_prompt", "num_inference_steps", "return_dict", "guidance_scale", "num_images_per_prompt", "output_type", "return_dict", ] __UpperCamelCase : Any = False @property def __UpperCAmelCase ( self :Dict ) -> Optional[Any]: '''simple docstring''' return 3_2 @property def __UpperCAmelCase ( self :List[str] ) -> Optional[int]: '''simple docstring''' return 3_2 @property def __UpperCAmelCase ( self :Dict ) -> Dict: '''simple docstring''' return self.time_input_dim @property def __UpperCAmelCase ( self :Optional[Any] ) -> Any: '''simple docstring''' return self.time_input_dim * 4 @property def __UpperCAmelCase ( self :Union[str, Any] ) -> List[str]: '''simple docstring''' return 1_0_0 @property def __UpperCAmelCase ( self :str ) -> Any: '''simple docstring''' _a : Tuple =XLMRobertaTokenizerFast.from_pretrained("""YiYiXu/tiny-random-mclip-base""" ) return tokenizer @property def __UpperCAmelCase ( self :Union[str, Any] ) -> Optional[int]: '''simple docstring''' torch.manual_seed(0 ) _a : List[Any] =MCLIPConfig( numDims=self.cross_attention_dim , transformerDimensions=self.text_embedder_hidden_size , hidden_size=self.text_embedder_hidden_size , intermediate_size=3_7 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=1_0_0_5 , ) _a : Dict =MultilingualCLIP(SCREAMING_SNAKE_CASE ) _a : Optional[int] =text_encoder.eval() return text_encoder @property def __UpperCAmelCase ( self :Optional[int] ) -> Union[str, Any]: '''simple docstring''' torch.manual_seed(0 ) _a : Optional[Any] ={ """in_channels""": 4, # Out channels is double in channels because predicts mean and variance """out_channels""": 8, """addition_embed_type""": """text_image""", """down_block_types""": ("""ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D"""), """up_block_types""": ("""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""), """mid_block_type""": """UNetMidBlock2DSimpleCrossAttn""", """block_out_channels""": (self.block_out_channels_a, self.block_out_channels_a * 2), """layers_per_block""": 1, """encoder_hid_dim""": self.text_embedder_hidden_size, """encoder_hid_dim_type""": """text_image_proj""", """cross_attention_dim""": self.cross_attention_dim, """attention_head_dim""": 4, """resnet_time_scale_shift""": """scale_shift""", """class_embed_type""": None, } _a : Optional[int] =UNetaDConditionModel(**SCREAMING_SNAKE_CASE ) return model @property def __UpperCAmelCase ( self :Optional[Any] ) -> Optional[int]: '''simple docstring''' return { "block_out_channels": [3_2, 6_4], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 1_2, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def __UpperCAmelCase ( self :Tuple ) -> str: '''simple docstring''' torch.manual_seed(0 ) _a : int =VQModel(**self.dummy_movq_kwargs ) return model def __UpperCAmelCase ( self :str ) -> List[Any]: '''simple docstring''' _a : Union[str, Any] =self.dummy_text_encoder _a : List[Any] =self.dummy_tokenizer _a : Optional[int] =self.dummy_unet _a : str =self.dummy_movq _a : int ={ """num_train_timesteps""": 1_0_0_0, """beta_schedule""": """linear""", """beta_start""": 0.00_085, """beta_end""": 0.012, """clip_sample""": False, """set_alpha_to_one""": False, """steps_offset""": 0, """prediction_type""": """epsilon""", """thresholding""": False, } _a : Union[str, Any] =DDIMScheduler(**SCREAMING_SNAKE_CASE ) _a : List[str] ={ """text_encoder""": text_encoder, """tokenizer""": tokenizer, """unet""": unet, """scheduler""": scheduler, """movq""": movq, } return components def __UpperCAmelCase ( self :Dict , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :List[Any]=0 ) -> Tuple: '''simple docstring''' _a : List[Any] =floats_tensor((1, self.cross_attention_dim) , rng=random.Random(SCREAMING_SNAKE_CASE ) ).to(SCREAMING_SNAKE_CASE ) _a : List[Any] =floats_tensor((1, self.cross_attention_dim) , rng=random.Random(seed + 1 ) ).to(SCREAMING_SNAKE_CASE ) # create init_image _a : Union[str, Any] =floats_tensor((1, 3, 6_4, 6_4) , rng=random.Random(SCREAMING_SNAKE_CASE ) ).to(SCREAMING_SNAKE_CASE ) _a : Dict =image.cpu().permute(0 , 2 , 3 , 1 )[0] _a : Union[str, Any] =Image.fromarray(np.uinta(SCREAMING_SNAKE_CASE ) ).convert("""RGB""" ).resize((2_5_6, 2_5_6) ) if str(SCREAMING_SNAKE_CASE ).startswith("""mps""" ): _a : Optional[Any] =torch.manual_seed(SCREAMING_SNAKE_CASE ) else: _a : Tuple =torch.Generator(device=SCREAMING_SNAKE_CASE ).manual_seed(SCREAMING_SNAKE_CASE ) _a : Dict ={ """prompt""": """horse""", """image""": init_image, """image_embeds""": image_embeds, """negative_image_embeds""": negative_image_embeds, """generator""": generator, """height""": 6_4, """width""": 6_4, """num_inference_steps""": 1_0, """guidance_scale""": 7.0, """strength""": 0.2, """output_type""": """np""", } return inputs def __UpperCAmelCase ( self :Optional[int] ) -> Optional[Any]: '''simple docstring''' _a : Any ="""cpu""" _a : Union[str, Any] =self.get_dummy_components() _a : Optional[Any] =self.pipeline_class(**SCREAMING_SNAKE_CASE ) _a : int =pipe.to(SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE ) _a : str =pipe(**self.get_dummy_inputs(SCREAMING_SNAKE_CASE ) ) _a : Optional[Any] =output.images _a : Tuple =pipe( **self.get_dummy_inputs(SCREAMING_SNAKE_CASE ) , return_dict=SCREAMING_SNAKE_CASE , )[0] _a : str =image[0, -3:, -3:, -1] _a : List[Any] =image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) _a : int =np.array( [0.61_474_943, 0.6_073_539, 0.43_308_544, 0.5_928_269, 0.47_493_595, 0.46_755_973, 0.4_613_838, 0.45_368_797, 0.50_119_233] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), f" expected_slice {expected_slice}, but got {image_slice.flatten()}" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), f" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}" @slow @require_torch_gpu class A__ ( unittest.TestCase ): def __UpperCAmelCase ( self :str ) -> Any: '''simple docstring''' # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __UpperCAmelCase ( self :Tuple ) -> Optional[Any]: '''simple docstring''' _a : Optional[Any] =load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/kandinsky_img2img_frog.npy""" ) _a : Dict =load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/cat.png""" ) _a : Any ="""A red cartoon frog, 4k""" _a : int =KandinskyPriorPipeline.from_pretrained( """kandinsky-community/kandinsky-2-1-prior""" , torch_dtype=torch.floataa ) pipe_prior.to(SCREAMING_SNAKE_CASE ) _a : Optional[int] =KandinskyImgaImgPipeline.from_pretrained( """kandinsky-community/kandinsky-2-1""" , torch_dtype=torch.floataa ) _a : int =pipeline.to(SCREAMING_SNAKE_CASE ) pipeline.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE ) _a : Tuple =torch.Generator(device="""cpu""" ).manual_seed(0 ) _a , _a : Any =pipe_prior( SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE , num_inference_steps=5 , negative_prompt="""""" , ).to_tuple() _a : int =pipeline( SCREAMING_SNAKE_CASE , image=SCREAMING_SNAKE_CASE , image_embeds=SCREAMING_SNAKE_CASE , negative_image_embeds=SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE , num_inference_steps=1_0_0 , height=7_6_8 , width=7_6_8 , strength=0.2 , output_type="""np""" , ) _a : Optional[Any] =output.images[0] assert image.shape == (7_6_8, 7_6_8, 3) assert_mean_pixel_difference(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
276
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A__: List[str] = logging.get_logger(__name__) A__: Union[str, Any] = { '''facebook/data2vec-text-base''': '''https://huggingface.co/data2vec/resolve/main/config.json''', } class A__ ( UpperCAmelCase__ ): __UpperCamelCase : int = "data2vec-text" def __init__( self :str , SCREAMING_SNAKE_CASE :Optional[Any]=3_0_5_2_2 , SCREAMING_SNAKE_CASE :Any=7_6_8 , SCREAMING_SNAKE_CASE :List[Any]=1_2 , SCREAMING_SNAKE_CASE :List[str]=1_2 , SCREAMING_SNAKE_CASE :Dict=3_0_7_2 , SCREAMING_SNAKE_CASE :List[str]="gelu" , SCREAMING_SNAKE_CASE :Any=0.1 , SCREAMING_SNAKE_CASE :List[str]=0.1 , SCREAMING_SNAKE_CASE :int=5_1_2 , SCREAMING_SNAKE_CASE :int=2 , SCREAMING_SNAKE_CASE :Union[str, Any]=0.02 , SCREAMING_SNAKE_CASE :Dict=1e-12 , SCREAMING_SNAKE_CASE :int=1 , SCREAMING_SNAKE_CASE :Dict=0 , SCREAMING_SNAKE_CASE :List[Any]=2 , SCREAMING_SNAKE_CASE :str="absolute" , SCREAMING_SNAKE_CASE :Tuple=True , SCREAMING_SNAKE_CASE :Union[str, Any]=None , **SCREAMING_SNAKE_CASE :Union[str, Any] , ) -> List[str]: '''simple docstring''' super().__init__(pad_token_id=SCREAMING_SNAKE_CASE , bos_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) _a : Optional[Any] =vocab_size _a : Optional[Any] =hidden_size _a : Any =num_hidden_layers _a : List[str] =num_attention_heads _a : Union[str, Any] =hidden_act _a : Any =intermediate_size _a : str =hidden_dropout_prob _a : Optional[Any] =attention_probs_dropout_prob _a : Optional[Any] =max_position_embeddings _a : Union[str, Any] =type_vocab_size _a : Tuple =initializer_range _a : Optional[int] =layer_norm_eps _a : Tuple =position_embedding_type _a : int =use_cache _a : List[str] =classifier_dropout class A__ ( UpperCAmelCase__ ): @property def __UpperCAmelCase ( self :int ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' 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), ] )
276
1
'''simple docstring''' import argparse import torch from transformers import BertForMaskedLM if __name__ == "__main__": A__: str = argparse.ArgumentParser( description=( '''Extraction some layers of the full BertForMaskedLM or RObertaForMaskedLM for Transfer Learned''' ''' Distillation''' ) ) parser.add_argument('''--model_type''', default='''bert''', choices=['''bert''']) parser.add_argument('''--model_name''', default='''bert-base-uncased''', type=str) parser.add_argument('''--dump_checkpoint''', default='''serialization_dir/tf_bert-base-uncased_0247911.pth''', type=str) parser.add_argument('''--vocab_transform''', action='''store_true''') A__: Optional[int] = parser.parse_args() if args.model_type == "bert": A__: Optional[int] = BertForMaskedLM.from_pretrained(args.model_name) A__: str = '''bert''' else: raise ValueError('''args.model_type should be "bert".''') A__: Optional[int] = model.state_dict() A__: str = {} for w in ["word_embeddings", "position_embeddings"]: A__: Any = state_dict[F"{prefix}.embeddings.{w}.weight"] for w in ["weight", "bias"]: A__: List[Any] = state_dict[F"{prefix}.embeddings.LayerNorm.{w}"] A__: Tuple = 0 for teacher_idx in [0, 2, 4, 7, 9, 11]: for w in ["weight", "bias"]: A__: List[Any] = state_dict[ F"{prefix}.encoder.layer.{teacher_idx}.attention.self.query.{w}" ] A__: str = state_dict[ F"{prefix}.encoder.layer.{teacher_idx}.attention.self.key.{w}" ] A__: Dict = state_dict[ F"{prefix}.encoder.layer.{teacher_idx}.attention.self.value.{w}" ] A__: List[Any] = state_dict[ F"{prefix}.encoder.layer.{teacher_idx}.attention.output.dense.{w}" ] A__: Tuple = state_dict[ F"{prefix}.encoder.layer.{teacher_idx}.attention.output.LayerNorm.{w}" ] A__: Optional[Any] = state_dict[ F"{prefix}.encoder.layer.{teacher_idx}.intermediate.dense.{w}" ] A__: str = state_dict[ F"{prefix}.encoder.layer.{teacher_idx}.output.dense.{w}" ] A__: Union[str, Any] = state_dict[ F"{prefix}.encoder.layer.{teacher_idx}.output.LayerNorm.{w}" ] std_idx += 1 A__: int = state_dict['''cls.predictions.decoder.weight'''] A__: Tuple = state_dict['''cls.predictions.bias'''] if args.vocab_transform: for w in ["weight", "bias"]: A__: Any = state_dict[F"cls.predictions.transform.dense.{w}"] A__: List[Any] = state_dict[F"cls.predictions.transform.LayerNorm.{w}"] print(F"N layers selected for distillation: {std_idx}") print(F"Number of params transferred for distillation: {len(compressed_sd.keys())}") print(F"Save transferred checkpoint to {args.dump_checkpoint}.") torch.save(compressed_sd, args.dump_checkpoint)
276
'''simple docstring''' from typing import Dict, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import flip_channel_order, resize, to_channel_dimension_format, to_pil_image from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_pytesseract_available, is_vision_available, logging, requires_backends if is_vision_available(): import PIL # soft dependency if is_pytesseract_available(): import pytesseract A__: Union[str, Any] = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : List[str] ) -> int: return [ int(1000 * (box[0] / width) ), int(1000 * (box[1] / height) ), int(1000 * (box[2] / width) ), int(1000 * (box[3] / height) ), ] def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : np.ndarray ,_UpperCAmelCase : Optional[str] ,_UpperCAmelCase : Optional[str] = None ) -> Optional[int]: _a : Any =tesseract_config if tesseract_config is not None else """""" # apply OCR _a : Optional[Any] =to_pil_image(_UpperCAmelCase ) _a , _a : List[Any] =pil_image.size _a : List[str] =pytesseract.image_to_data(_UpperCAmelCase ,lang=_UpperCAmelCase ,output_type="""dict""" ,config=_UpperCAmelCase ) _a , _a , _a , _a , _a : str =data["""text"""], data["""left"""], data["""top"""], data["""width"""], data["""height"""] # filter empty words and corresponding coordinates _a : Tuple =[idx for idx, word in enumerate(_UpperCAmelCase ) if not word.strip()] _a : List[Any] =[word for idx, word in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] _a : Dict =[coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] _a : List[str] =[coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] _a : Union[str, Any] =[coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] _a : Union[str, Any] =[coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] # turn coordinates into (left, top, left+width, top+height) format _a : List[str] =[] for x, y, w, h in zip(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ): _a : int =[x, y, x + w, y + h] actual_boxes.append(_UpperCAmelCase ) # finally, normalize the bounding boxes _a : str =[] for box in actual_boxes: normalized_boxes.append(normalize_box(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) ) assert len(_UpperCAmelCase ) == len(_UpperCAmelCase ), "Not as many words as there are bounding boxes" return words, normalized_boxes class A__ ( UpperCAmelCase__ ): __UpperCamelCase : List[Any] = ["pixel_values"] def __init__( self :Tuple , SCREAMING_SNAKE_CASE :bool = True , SCREAMING_SNAKE_CASE :Dict[str, int] = None , SCREAMING_SNAKE_CASE :PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE :bool = True , SCREAMING_SNAKE_CASE :Optional[str] = None , SCREAMING_SNAKE_CASE :Optional[str] = "" , **SCREAMING_SNAKE_CASE :Tuple , ) -> None: '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE ) _a : List[Any] =size if size is not None else {"""height""": 2_2_4, """width""": 2_2_4} _a : Tuple =get_size_dict(SCREAMING_SNAKE_CASE ) _a : Dict =do_resize _a : Tuple =size _a : str =resample _a : Dict =apply_ocr _a : Union[str, Any] =ocr_lang _a : Dict =tesseract_config def __UpperCAmelCase ( self :List[str] , SCREAMING_SNAKE_CASE :np.ndarray , SCREAMING_SNAKE_CASE :Dict[str, int] , SCREAMING_SNAKE_CASE :PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE :Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE :Dict , ) -> np.ndarray: '''simple docstring''' _a : int =get_size_dict(SCREAMING_SNAKE_CASE ) if "height" not in size or "width" not in size: raise ValueError(f"The size dictionary must contain the keys 'height' and 'width'. Got {size.keys()}" ) _a : Any =(size["""height"""], size["""width"""]) return resize(SCREAMING_SNAKE_CASE , size=SCREAMING_SNAKE_CASE , resample=SCREAMING_SNAKE_CASE , data_format=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Dict , SCREAMING_SNAKE_CASE :ImageInput , SCREAMING_SNAKE_CASE :bool = None , SCREAMING_SNAKE_CASE :Dict[str, int] = None , SCREAMING_SNAKE_CASE :PILImageResampling = None , SCREAMING_SNAKE_CASE :bool = None , SCREAMING_SNAKE_CASE :Optional[str] = None , SCREAMING_SNAKE_CASE :Optional[str] = None , SCREAMING_SNAKE_CASE :Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE :ChannelDimension = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE :Optional[Any] , ) -> PIL.Image.Image: '''simple docstring''' _a : Optional[int] =do_resize if do_resize is not None else self.do_resize _a : Optional[int] =size if size is not None else self.size _a : str =get_size_dict(SCREAMING_SNAKE_CASE ) _a : List[str] =resample if resample is not None else self.resample _a : int =apply_ocr if apply_ocr is not None else self.apply_ocr _a : str =ocr_lang if ocr_lang is not None else self.ocr_lang _a : Union[str, Any] =tesseract_config if tesseract_config is not None else self.tesseract_config _a : List[str] =make_list_of_images(SCREAMING_SNAKE_CASE ) if not valid_images(SCREAMING_SNAKE_CASE ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None: raise ValueError("""Size must be specified if do_resize is True.""" ) # All transformations expect numpy arrays. _a : List[Any] =[to_numpy_array(SCREAMING_SNAKE_CASE ) for image in images] if apply_ocr: requires_backends(self , """pytesseract""" ) _a : Any =[] _a : Any =[] for image in images: _a , _a : int =apply_tesseract(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) words_batch.append(SCREAMING_SNAKE_CASE ) boxes_batch.append(SCREAMING_SNAKE_CASE ) if do_resize: _a : Union[str, Any] =[self.resize(image=SCREAMING_SNAKE_CASE , size=SCREAMING_SNAKE_CASE , resample=SCREAMING_SNAKE_CASE ) for image in images] # flip color channels from RGB to BGR (as Detectron2 requires this) _a : Dict =[flip_channel_order(SCREAMING_SNAKE_CASE ) for image in images] _a : str =[to_channel_dimension_format(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for image in images] _a : str =BatchFeature(data={"""pixel_values""": images} , tensor_type=SCREAMING_SNAKE_CASE ) if apply_ocr: _a : List[Any] =words_batch _a : Dict =boxes_batch return data
276
1
'''simple docstring''' import os import shutil import sys import tempfile import unittest from pathlib import Path import pytest import transformers from transformers import ( BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, AutoTokenizer, BertConfig, BertTokenizer, BertTokenizerFast, CTRLTokenizer, GPTaTokenizer, GPTaTokenizerFast, PreTrainedTokenizerFast, RobertaTokenizer, RobertaTokenizerFast, is_tokenizers_available, ) from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig from transformers.models.auto.tokenization_auto import ( TOKENIZER_MAPPING, get_tokenizer_config, tokenizer_class_from_name, ) from transformers.models.roberta.configuration_roberta import RobertaConfig from transformers.testing_utils import ( DUMMY_DIFF_TOKENIZER_IDENTIFIER, DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, RequestCounter, require_tokenizers, slow, ) sys.path.append(str(Path(__file__).parent.parent.parent.parent / '''utils''')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_tokenization import CustomTokenizer # noqa E402 if is_tokenizers_available(): from test_module.custom_tokenization_fast import CustomTokenizerFast class A__ ( unittest.TestCase ): def __UpperCAmelCase ( self :List[str] ) -> List[Any]: '''simple docstring''' _a : Optional[int] =0 @slow def __UpperCAmelCase ( self :Union[str, Any] ) -> List[str]: '''simple docstring''' for model_name in (x for x in BERT_PRETRAINED_CONFIG_ARCHIVE_MAP.keys() if "japanese" not in x): _a : int =AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , (BertTokenizer, BertTokenizerFast) ) self.assertGreater(len(SCREAMING_SNAKE_CASE ) , 0 ) for model_name in GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP.keys(): _a : List[str] =AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , (GPTaTokenizer, GPTaTokenizerFast) ) self.assertGreater(len(SCREAMING_SNAKE_CASE ) , 0 ) def __UpperCAmelCase ( self :int ) -> Optional[int]: '''simple docstring''' _a : Union[str, Any] =AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(tokenizer.vocab_size , 1_2 ) def __UpperCAmelCase ( self :List[str] ) -> Optional[int]: '''simple docstring''' _a : Dict =AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , (RobertaTokenizer, RobertaTokenizerFast) ) self.assertEqual(tokenizer.vocab_size , 2_0 ) def __UpperCAmelCase ( self :List[Any] ) -> List[str]: '''simple docstring''' _a : Any =AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # Check that tokenizer_type ≠ model_type _a : Optional[Any] =AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE , config=SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(tokenizer.vocab_size , 1_2 ) def __UpperCAmelCase ( self :Tuple ) -> Dict: '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy("""./tests/fixtures/vocab.txt""" , os.path.join(SCREAMING_SNAKE_CASE , """vocab.txt""" ) ) _a : List[Any] =AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE , tokenizer_type="""bert""" , use_fast=SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy("""./tests/fixtures/vocab.json""" , os.path.join(SCREAMING_SNAKE_CASE , """vocab.json""" ) ) shutil.copy("""./tests/fixtures/merges.txt""" , os.path.join(SCREAMING_SNAKE_CASE , """merges.txt""" ) ) _a : int =AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE , tokenizer_type="""gpt2""" , use_fast=SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) @require_tokenizers def __UpperCAmelCase ( self :List[Any] ) -> int: '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy("""./tests/fixtures/vocab.txt""" , os.path.join(SCREAMING_SNAKE_CASE , """vocab.txt""" ) ) _a : int =AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE , tokenizer_type="""bert""" ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy("""./tests/fixtures/vocab.json""" , os.path.join(SCREAMING_SNAKE_CASE , """vocab.json""" ) ) shutil.copy("""./tests/fixtures/merges.txt""" , os.path.join(SCREAMING_SNAKE_CASE , """merges.txt""" ) ) _a : Optional[int] =AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE , tokenizer_type="""gpt2""" ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Optional[Any] ) -> Any: '''simple docstring''' with pytest.raises(SCREAMING_SNAKE_CASE ): AutoTokenizer.from_pretrained("""./""" , tokenizer_type="""xxx""" ) @require_tokenizers def __UpperCAmelCase ( self :Any ) -> str: '''simple docstring''' for tokenizer_class in [BertTokenizer, BertTokenizerFast, AutoTokenizer]: _a : Optional[int] =tokenizer_class.from_pretrained("""wietsedv/bert-base-dutch-cased""" ) self.assertIsInstance(SCREAMING_SNAKE_CASE , (BertTokenizer, BertTokenizerFast) ) if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): self.assertEqual(tokenizer.basic_tokenizer.do_lower_case , SCREAMING_SNAKE_CASE ) else: self.assertEqual(tokenizer.do_lower_case , SCREAMING_SNAKE_CASE ) self.assertEqual(tokenizer.model_max_length , 5_1_2 ) @require_tokenizers def __UpperCAmelCase ( self :Optional[Any] ) -> int: '''simple docstring''' for tokenizer_class in [BertTokenizer, BertTokenizerFast, AutoTokenizer]: with self.assertRaisesRegex( SCREAMING_SNAKE_CASE , """julien-c/herlolip-not-exists is not a local folder and is not a valid model identifier""" , ): _a : Any =tokenizer_class.from_pretrained("""julien-c/herlolip-not-exists""" ) def __UpperCAmelCase ( self :List[Any] ) -> List[Any]: '''simple docstring''' # tests: https://github.com/huggingface/transformers/pull/13251 # 1. models with `-`, e.g. xlm-roberta -> xlm_roberta # 2. models that don't remap 1-1 from model-name to model file, e.g., openai-gpt -> openai _a : Dict =TOKENIZER_MAPPING.values() _a : Tuple =[] for slow_tok, fast_tok in tokenizers: if slow_tok is not None: tokenizer_names.append(slow_tok.__name__ ) if fast_tok is not None: tokenizer_names.append(fast_tok.__name__ ) for tokenizer_name in tokenizer_names: # must find the right class tokenizer_class_from_name(SCREAMING_SNAKE_CASE ) @require_tokenizers def __UpperCAmelCase ( self :int ) -> List[str]: '''simple docstring''' self.assertIsInstance(AutoTokenizer.from_pretrained("""bert-base-cased""" , use_fast=SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE ) self.assertIsInstance(AutoTokenizer.from_pretrained("""bert-base-cased""" ) , SCREAMING_SNAKE_CASE ) @require_tokenizers def __UpperCAmelCase ( self :int ) -> int: '''simple docstring''' _a : List[str] =AutoTokenizer.from_pretrained("""distilbert-base-uncased""" , do_lower_case=SCREAMING_SNAKE_CASE ) _a : List[Any] ="""Hello, world. How are you?""" _a : Optional[int] =tokenizer.tokenize(SCREAMING_SNAKE_CASE ) self.assertEqual("""[UNK]""" , tokens[0] ) _a : Optional[int] =AutoTokenizer.from_pretrained("""microsoft/mpnet-base""" , do_lower_case=SCREAMING_SNAKE_CASE ) _a : int =tokenizer.tokenize(SCREAMING_SNAKE_CASE ) self.assertEqual("""[UNK]""" , tokens[0] ) @require_tokenizers def __UpperCAmelCase ( self :Tuple ) -> Optional[Any]: '''simple docstring''' _a : Optional[int] =AutoTokenizer.from_pretrained("""robot-test/dummy-tokenizer-fast-with-model-config""" ) self.assertEqual(type(SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE ) self.assertEqual(tokenizer.model_max_length , 5_1_2 ) self.assertEqual(tokenizer.vocab_size , 3_0_0_0_0 ) self.assertEqual(tokenizer.unk_token , """[UNK]""" ) self.assertEqual(tokenizer.padding_side , """right""" ) self.assertEqual(tokenizer.truncation_side , """right""" ) def __UpperCAmelCase ( self :Optional[int] ) -> Any: '''simple docstring''' _a : int =AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , (BertTokenizer, BertTokenizerFast) ) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(SCREAMING_SNAKE_CASE ) _a : Optional[Any] =AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , tokenizer.__class__ ) self.assertEqual(tokenizera.vocab_size , 1_2 ) def __UpperCAmelCase ( self :Optional[Any] ) -> List[Any]: '''simple docstring''' _a : str =AutoTokenizer.from_pretrained("""ctrl""" ) # There is no fast CTRL so this always gives us a slow tokenizer. self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :List[str] ) -> Union[str, Any]: '''simple docstring''' # Check we can load the tokenizer config of an online model. _a : Optional[int] =get_tokenizer_config("""bert-base-cased""" ) _a : Any =config.pop("""_commit_hash""" , SCREAMING_SNAKE_CASE ) # If we ever update bert-base-cased tokenizer config, this dict here will need to be updated. self.assertEqual(SCREAMING_SNAKE_CASE , {"""do_lower_case""": False} ) # This model does not have a tokenizer_config so we get back an empty dict. _a : List[str] =get_tokenizer_config(SCREAMING_SNAKE_CASE ) self.assertDictEqual(SCREAMING_SNAKE_CASE , {} ) # A tokenizer saved with `save_pretrained` always creates a tokenizer config. _a : str =AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE ) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(SCREAMING_SNAKE_CASE ) _a : Any =get_tokenizer_config(SCREAMING_SNAKE_CASE ) # Check the class of the tokenizer was properly saved (note that it always saves the slow class). self.assertEqual(config["""tokenizer_class"""] , """BertTokenizer""" ) def __UpperCAmelCase ( self :Optional[Any] ) -> Any: '''simple docstring''' try: AutoConfig.register("""custom""" , SCREAMING_SNAKE_CASE ) AutoTokenizer.register(SCREAMING_SNAKE_CASE , slow_tokenizer_class=SCREAMING_SNAKE_CASE ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(SCREAMING_SNAKE_CASE ): AutoTokenizer.register(SCREAMING_SNAKE_CASE , slow_tokenizer_class=SCREAMING_SNAKE_CASE ) _a : List[str] =CustomTokenizer.from_pretrained(SCREAMING_SNAKE_CASE ) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(SCREAMING_SNAKE_CASE ) _a : Any =AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] @require_tokenizers def __UpperCAmelCase ( self :List[str] ) -> Optional[Any]: '''simple docstring''' try: AutoConfig.register("""custom""" , SCREAMING_SNAKE_CASE ) # Can register in two steps AutoTokenizer.register(SCREAMING_SNAKE_CASE , slow_tokenizer_class=SCREAMING_SNAKE_CASE ) self.assertEqual(TOKENIZER_MAPPING[CustomConfig] , (CustomTokenizer, None) ) AutoTokenizer.register(SCREAMING_SNAKE_CASE , fast_tokenizer_class=SCREAMING_SNAKE_CASE ) self.assertEqual(TOKENIZER_MAPPING[CustomConfig] , (CustomTokenizer, CustomTokenizerFast) ) del TOKENIZER_MAPPING._extra_content[CustomConfig] # Can register in one step AutoTokenizer.register( SCREAMING_SNAKE_CASE , slow_tokenizer_class=SCREAMING_SNAKE_CASE , fast_tokenizer_class=SCREAMING_SNAKE_CASE ) self.assertEqual(TOKENIZER_MAPPING[CustomConfig] , (CustomTokenizer, CustomTokenizerFast) ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(SCREAMING_SNAKE_CASE ): AutoTokenizer.register(SCREAMING_SNAKE_CASE , fast_tokenizer_class=SCREAMING_SNAKE_CASE ) # We pass through a bert tokenizer fast cause there is no converter slow to fast for our new toknizer # and that model does not have a tokenizer.json with tempfile.TemporaryDirectory() as tmp_dir: _a : int =BertTokenizerFast.from_pretrained(SCREAMING_SNAKE_CASE ) bert_tokenizer.save_pretrained(SCREAMING_SNAKE_CASE ) _a : int =CustomTokenizerFast.from_pretrained(SCREAMING_SNAKE_CASE ) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(SCREAMING_SNAKE_CASE ) _a : Tuple =AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) _a : Any =AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE , use_fast=SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] def __UpperCAmelCase ( self :int ) -> Tuple: '''simple docstring''' # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(SCREAMING_SNAKE_CASE ): _a : Dict =AutoTokenizer.from_pretrained("""hf-internal-testing/test_dynamic_tokenizer""" ) # If remote code is disabled, we can't load this config. with self.assertRaises(SCREAMING_SNAKE_CASE ): _a : Optional[Any] =AutoTokenizer.from_pretrained( """hf-internal-testing/test_dynamic_tokenizer""" , trust_remote_code=SCREAMING_SNAKE_CASE ) _a : Any =AutoTokenizer.from_pretrained("""hf-internal-testing/test_dynamic_tokenizer""" , trust_remote_code=SCREAMING_SNAKE_CASE ) self.assertTrue(tokenizer.special_attribute_present ) # Test tokenizer can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE , trust_remote_code=SCREAMING_SNAKE_CASE ) self.assertTrue(reloaded_tokenizer.special_attribute_present ) if is_tokenizers_available(): self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizerFast""" ) self.assertEqual(reloaded_tokenizer.__class__.__name__ , """NewTokenizerFast""" ) # Test we can also load the slow version _a : List[Any] =AutoTokenizer.from_pretrained( """hf-internal-testing/test_dynamic_tokenizer""" , trust_remote_code=SCREAMING_SNAKE_CASE , use_fast=SCREAMING_SNAKE_CASE ) self.assertTrue(tokenizer.special_attribute_present ) self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizer""" ) # Test tokenizer can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(SCREAMING_SNAKE_CASE ) _a : Tuple =AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE , trust_remote_code=SCREAMING_SNAKE_CASE , use_fast=SCREAMING_SNAKE_CASE ) self.assertEqual(reloaded_tokenizer.__class__.__name__ , """NewTokenizer""" ) self.assertTrue(reloaded_tokenizer.special_attribute_present ) else: self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizer""" ) self.assertEqual(reloaded_tokenizer.__class__.__name__ , """NewTokenizer""" ) @require_tokenizers def __UpperCAmelCase ( self :List[str] ) -> Tuple: '''simple docstring''' class A__ ( UpperCAmelCase__ ): __UpperCamelCase : str = False class A__ ( UpperCAmelCase__ ): __UpperCamelCase : List[str] = NewTokenizer __UpperCamelCase : Tuple = False try: AutoConfig.register("""custom""" , SCREAMING_SNAKE_CASE ) AutoTokenizer.register(SCREAMING_SNAKE_CASE , slow_tokenizer_class=SCREAMING_SNAKE_CASE ) AutoTokenizer.register(SCREAMING_SNAKE_CASE , fast_tokenizer_class=SCREAMING_SNAKE_CASE ) # If remote code is not set, the default is to use local _a : str =AutoTokenizer.from_pretrained("""hf-internal-testing/test_dynamic_tokenizer""" ) self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizerFast""" ) self.assertFalse(tokenizer.special_attribute_present ) _a : Optional[int] =AutoTokenizer.from_pretrained("""hf-internal-testing/test_dynamic_tokenizer""" , use_fast=SCREAMING_SNAKE_CASE ) self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizer""" ) self.assertFalse(tokenizer.special_attribute_present ) # If remote code is disabled, we load the local one. _a : Tuple =AutoTokenizer.from_pretrained( """hf-internal-testing/test_dynamic_tokenizer""" , trust_remote_code=SCREAMING_SNAKE_CASE ) self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizerFast""" ) self.assertFalse(tokenizer.special_attribute_present ) _a : List[str] =AutoTokenizer.from_pretrained( """hf-internal-testing/test_dynamic_tokenizer""" , trust_remote_code=SCREAMING_SNAKE_CASE , use_fast=SCREAMING_SNAKE_CASE ) self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizer""" ) self.assertFalse(tokenizer.special_attribute_present ) # If remote is enabled, we load from the Hub _a : Optional[int] =AutoTokenizer.from_pretrained( """hf-internal-testing/test_dynamic_tokenizer""" , trust_remote_code=SCREAMING_SNAKE_CASE ) self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizerFast""" ) self.assertTrue(tokenizer.special_attribute_present ) _a : Dict =AutoTokenizer.from_pretrained( """hf-internal-testing/test_dynamic_tokenizer""" , trust_remote_code=SCREAMING_SNAKE_CASE , use_fast=SCREAMING_SNAKE_CASE ) self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizer""" ) self.assertTrue(tokenizer.special_attribute_present ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] def __UpperCAmelCase ( self :List[str] ) -> Dict: '''simple docstring''' _a : List[str] =AutoTokenizer.from_pretrained( """hf-internal-testing/test_dynamic_tokenizer_legacy""" , trust_remote_code=SCREAMING_SNAKE_CASE ) self.assertTrue(tokenizer.special_attribute_present ) if is_tokenizers_available(): self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizerFast""" ) # Test we can also load the slow version _a : str =AutoTokenizer.from_pretrained( """hf-internal-testing/test_dynamic_tokenizer_legacy""" , trust_remote_code=SCREAMING_SNAKE_CASE , use_fast=SCREAMING_SNAKE_CASE ) self.assertTrue(tokenizer.special_attribute_present ) self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizer""" ) else: self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizer""" ) def __UpperCAmelCase ( self :int ) -> int: '''simple docstring''' with self.assertRaisesRegex( SCREAMING_SNAKE_CASE , """bert-base is not a local folder and is not a valid model identifier""" ): _a : Dict =AutoTokenizer.from_pretrained("""bert-base""" ) def __UpperCAmelCase ( self :Optional[int] ) -> Dict: '''simple docstring''' with self.assertRaisesRegex( SCREAMING_SNAKE_CASE , r"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)""" ): _a : int =AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE , revision="""aaaaaa""" ) def __UpperCAmelCase ( self :Union[str, Any] ) -> Tuple: '''simple docstring''' # Make sure we have cached the tokenizer. _a : int =AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-bert""" ) with RequestCounter() as counter: _a : Optional[Any] =AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-bert""" ) self.assertEqual(counter.get_request_count , 0 ) self.assertEqual(counter.head_request_count , 1 ) self.assertEqual(counter.other_request_count , 0 )
276
'''simple docstring''' from __future__ import annotations import requests def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ) -> dict: _a : Any =F"https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty" return requests.get(_UpperCAmelCase ).json() def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int = 10 ) -> list[dict]: _a : Union[str, Any] ="""https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty""" _a : int =requests.get(_UpperCAmelCase ).json()[:max_stories] return [get_hackernews_story(_UpperCAmelCase ) for story_id in story_ids] def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int = 10 ) -> str: _a : Union[str, Any] =hackernews_top_stories(_UpperCAmelCase ) return "\n".join("""* [{title}]({url})""".format(**_UpperCAmelCase ) for story in stories ) if __name__ == "__main__": print(hackernews_top_stories_as_markdown())
276
1
'''simple docstring''' import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class A__ ( UpperCAmelCase__ , UpperCAmelCase__ ): @register_to_config def __init__( self :Optional[Any] , *, SCREAMING_SNAKE_CASE :int = 4 , SCREAMING_SNAKE_CASE :int = 7_6_8 , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :List[Any] , ) -> Union[str, Any]: '''simple docstring''' super().__init__() _a : Optional[int] =nn.Parameter(torch.zeros(SCREAMING_SNAKE_CASE ) ) # parameters for additional clip time embeddings _a : str =nn.Linear(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) _a : Optional[Any] =nn.Linear(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # parameters for encoder hidden states _a : List[Any] =clip_extra_context_tokens _a : List[str] =nn.Linear( SCREAMING_SNAKE_CASE , self.clip_extra_context_tokens * cross_attention_dim ) _a : List[Any] =nn.Linear(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) _a : List[str] =nn.LayerNorm(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Any , *, SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :List[Any] , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :List[str] ) -> Optional[int]: '''simple docstring''' if do_classifier_free_guidance: # Add the classifier free guidance embeddings to the image embeddings _a : Tuple =image_embeddings.shape[0] _a : List[Any] =self.learned_classifier_free_guidance_embeddings.unsqueeze(0 ) _a : List[str] =classifier_free_guidance_embeddings.expand( SCREAMING_SNAKE_CASE , -1 ) _a : str =torch.cat([classifier_free_guidance_embeddings, image_embeddings] , dim=0 ) # The image embeddings batch size and the text embeddings batch size are equal assert image_embeddings.shape[0] == prompt_embeds.shape[0] _a : List[Any] =prompt_embeds.shape[0] # "Specifically, we modify the architecture described in Nichol et al. (2021) by projecting and # adding CLIP embeddings to the existing timestep embedding, ... _a : Any =self.embedding_proj(SCREAMING_SNAKE_CASE ) _a : Any =self.clip_image_embeddings_project_to_time_embeddings(SCREAMING_SNAKE_CASE ) _a : List[str] =time_projected_image_embeddings + time_projected_prompt_embeds # ... and by projecting CLIP embeddings into four # extra tokens of context that are concatenated to the sequence of outputs from the GLIDE text encoder" _a : str =self.clip_extra_context_tokens_proj(SCREAMING_SNAKE_CASE ) _a : List[str] =clip_extra_context_tokens.reshape(SCREAMING_SNAKE_CASE , -1 , self.clip_extra_context_tokens ) _a : int =clip_extra_context_tokens.permute(0 , 2 , 1 ) _a : Optional[Any] =self.encoder_hidden_states_proj(SCREAMING_SNAKE_CASE ) _a : str =self.text_encoder_hidden_states_norm(SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =torch.cat([clip_extra_context_tokens, text_encoder_hidden_states] , dim=1 ) return text_encoder_hidden_states, additive_clip_time_embeddings
276
'''simple docstring''' from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .modeling_utils import ModelMixin from .vae import Decoder, DecoderOutput, Encoder, VectorQuantizer @dataclass class A__ ( UpperCAmelCase__ ): __UpperCamelCase : torch.FloatTensor class A__ ( UpperCAmelCase__ , UpperCAmelCase__ ): @register_to_config def __init__( self :Optional[Any] , SCREAMING_SNAKE_CASE :int = 3 , SCREAMING_SNAKE_CASE :int = 3 , SCREAMING_SNAKE_CASE :Tuple[str] = ("DownEncoderBlock2D",) , SCREAMING_SNAKE_CASE :Tuple[str] = ("UpDecoderBlock2D",) , SCREAMING_SNAKE_CASE :Tuple[int] = (6_4,) , SCREAMING_SNAKE_CASE :int = 1 , SCREAMING_SNAKE_CASE :str = "silu" , SCREAMING_SNAKE_CASE :int = 3 , SCREAMING_SNAKE_CASE :int = 3_2 , SCREAMING_SNAKE_CASE :int = 2_5_6 , SCREAMING_SNAKE_CASE :int = 3_2 , SCREAMING_SNAKE_CASE :Optional[int] = None , SCREAMING_SNAKE_CASE :float = 0.18_215 , SCREAMING_SNAKE_CASE :str = "group" , ) -> Optional[int]: '''simple docstring''' super().__init__() # pass init params to Encoder _a : Union[str, Any] =Encoder( in_channels=SCREAMING_SNAKE_CASE , out_channels=SCREAMING_SNAKE_CASE , down_block_types=SCREAMING_SNAKE_CASE , block_out_channels=SCREAMING_SNAKE_CASE , layers_per_block=SCREAMING_SNAKE_CASE , act_fn=SCREAMING_SNAKE_CASE , norm_num_groups=SCREAMING_SNAKE_CASE , double_z=SCREAMING_SNAKE_CASE , ) _a : Optional[int] =vq_embed_dim if vq_embed_dim is not None else latent_channels _a : Optional[int] =nn.Convad(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , 1 ) _a : str =VectorQuantizer(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , beta=0.25 , remap=SCREAMING_SNAKE_CASE , sane_index_shape=SCREAMING_SNAKE_CASE ) _a : List[str] =nn.Convad(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , 1 ) # pass init params to Decoder _a : List[str] =Decoder( in_channels=SCREAMING_SNAKE_CASE , out_channels=SCREAMING_SNAKE_CASE , up_block_types=SCREAMING_SNAKE_CASE , block_out_channels=SCREAMING_SNAKE_CASE , layers_per_block=SCREAMING_SNAKE_CASE , act_fn=SCREAMING_SNAKE_CASE , norm_num_groups=SCREAMING_SNAKE_CASE , norm_type=SCREAMING_SNAKE_CASE , ) @apply_forward_hook def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :torch.FloatTensor , SCREAMING_SNAKE_CASE :bool = True ) -> VQEncoderOutput: '''simple docstring''' _a : Optional[int] =self.encoder(SCREAMING_SNAKE_CASE ) _a : int =self.quant_conv(SCREAMING_SNAKE_CASE ) if not return_dict: return (h,) return VQEncoderOutput(latents=SCREAMING_SNAKE_CASE ) @apply_forward_hook def __UpperCAmelCase ( self :List[Any] , SCREAMING_SNAKE_CASE :torch.FloatTensor , SCREAMING_SNAKE_CASE :bool = False , SCREAMING_SNAKE_CASE :bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: '''simple docstring''' # also go through quantization layer if not force_not_quantize: _a , _a , _a : Tuple =self.quantize(SCREAMING_SNAKE_CASE ) else: _a : str =h _a : Dict =self.post_quant_conv(SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =self.decoder(SCREAMING_SNAKE_CASE , quant if self.config.norm_type == """spatial""" else None ) if not return_dict: return (dec,) return DecoderOutput(sample=SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :torch.FloatTensor , SCREAMING_SNAKE_CASE :bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: '''simple docstring''' _a : Tuple =sample _a : int =self.encode(SCREAMING_SNAKE_CASE ).latents _a : List[Any] =self.decode(SCREAMING_SNAKE_CASE ).sample if not return_dict: return (dec,) return DecoderOutput(sample=SCREAMING_SNAKE_CASE )
276
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A__: Dict = logging.get_logger(__name__) A__: Optional[int] = { '''google/vivit-b-16x2-kinetics400''': ( '''https://huggingface.co/google/vivit-b-16x2-kinetics400/resolve/main/config.json''' ), # See all Vivit models at https://huggingface.co/models?filter=vivit } class A__ ( UpperCAmelCase__ ): __UpperCamelCase : List[Any] = "vivit" def __init__( self :List[Any] , SCREAMING_SNAKE_CASE :List[str]=2_2_4 , SCREAMING_SNAKE_CASE :Optional[Any]=3_2 , SCREAMING_SNAKE_CASE :Optional[Any]=[2, 1_6, 1_6] , SCREAMING_SNAKE_CASE :Optional[Any]=3 , SCREAMING_SNAKE_CASE :Any=7_6_8 , SCREAMING_SNAKE_CASE :int=1_2 , SCREAMING_SNAKE_CASE :Any=1_2 , SCREAMING_SNAKE_CASE :Union[str, Any]=3_0_7_2 , SCREAMING_SNAKE_CASE :Union[str, Any]="gelu_fast" , SCREAMING_SNAKE_CASE :str=0.0 , SCREAMING_SNAKE_CASE :List[Any]=0.0 , SCREAMING_SNAKE_CASE :Optional[Any]=0.02 , SCREAMING_SNAKE_CASE :Any=1e-06 , SCREAMING_SNAKE_CASE :str=True , **SCREAMING_SNAKE_CASE :str , ) -> List[str]: '''simple docstring''' _a : Optional[Any] =hidden_size _a : Dict =num_hidden_layers _a : List[str] =num_attention_heads _a : Tuple =intermediate_size _a : Any =hidden_act _a : Any =hidden_dropout_prob _a : Union[str, Any] =attention_probs_dropout_prob _a : List[str] =initializer_range _a : Optional[int] =layer_norm_eps _a : List[Any] =image_size _a : int =num_frames _a : Any =tubelet_size _a : Optional[int] =num_channels _a : List[Any] =qkv_bias super().__init__(**SCREAMING_SNAKE_CASE )
276
'''simple docstring''' import unittest from transformers import EsmConfig, is_torch_available from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import EsmForMaskedLM, EsmForSequenceClassification, EsmForTokenClassification, EsmModel from transformers.models.esm.modeling_esm import ( ESM_PRETRAINED_MODEL_ARCHIVE_LIST, EsmEmbeddings, create_position_ids_from_input_ids, ) class A__ : def __init__( self :Tuple , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :Optional[int]=1_3 , SCREAMING_SNAKE_CASE :Optional[int]=7 , SCREAMING_SNAKE_CASE :Tuple=False , SCREAMING_SNAKE_CASE :Dict=True , SCREAMING_SNAKE_CASE :Optional[int]=False , SCREAMING_SNAKE_CASE :Optional[Any]=True , SCREAMING_SNAKE_CASE :List[str]=3_3 , SCREAMING_SNAKE_CASE :Tuple=3_2 , SCREAMING_SNAKE_CASE :Tuple=5 , SCREAMING_SNAKE_CASE :int=4 , SCREAMING_SNAKE_CASE :Union[str, Any]=3_7 , SCREAMING_SNAKE_CASE :List[str]="gelu" , SCREAMING_SNAKE_CASE :Optional[Any]=0.1 , SCREAMING_SNAKE_CASE :Tuple=0.1 , SCREAMING_SNAKE_CASE :str=5_1_2 , SCREAMING_SNAKE_CASE :Dict=1_6 , SCREAMING_SNAKE_CASE :Dict=2 , SCREAMING_SNAKE_CASE :Union[str, Any]=0.02 , SCREAMING_SNAKE_CASE :str=3 , SCREAMING_SNAKE_CASE :List[str]=4 , SCREAMING_SNAKE_CASE :List[str]=None , ) -> Union[str, Any]: '''simple docstring''' _a : Union[str, Any] =parent _a : List[Any] =batch_size _a : Optional[int] =seq_length _a : Union[str, Any] =is_training _a : List[Any] =use_input_mask _a : Optional[int] =use_token_type_ids _a : int =use_labels _a : List[str] =vocab_size _a : List[Any] =hidden_size _a : int =num_hidden_layers _a : Tuple =num_attention_heads _a : Any =intermediate_size _a : str =hidden_act _a : Union[str, Any] =hidden_dropout_prob _a : Union[str, Any] =attention_probs_dropout_prob _a : str =max_position_embeddings _a : Dict =type_vocab_size _a : Tuple =type_sequence_label_size _a : Dict =initializer_range _a : List[str] =num_labels _a : Tuple =num_choices _a : int =scope def __UpperCAmelCase ( self :Union[str, Any] ) -> str: '''simple docstring''' _a : Optional[int] =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _a : List[Any] =None if self.use_input_mask: _a : Any =random_attention_mask([self.batch_size, self.seq_length] ) _a : Optional[int] =None _a : str =None _a : Dict =None if self.use_labels: _a : Dict =ids_tensor([self.batch_size] , self.type_sequence_label_size ) _a : str =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _a : List[str] =ids_tensor([self.batch_size] , self.num_choices ) _a : List[Any] =self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCAmelCase ( self :str ) -> Optional[int]: '''simple docstring''' return EsmConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , pad_token_id=1 , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) def __UpperCAmelCase ( self :List[str] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :int ) -> Tuple: '''simple docstring''' _a : Any =EsmModel(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() _a : Optional[Any] =model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =model(SCREAMING_SNAKE_CASE ) _a : str =model(SCREAMING_SNAKE_CASE ) 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 __UpperCAmelCase ( self :str , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :Optional[Any] ) -> Dict: '''simple docstring''' _a : str =EsmForMaskedLM(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() _a : Union[str, Any] =model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :List[Any] , SCREAMING_SNAKE_CASE :Union[str, Any] ) -> Optional[Any]: '''simple docstring''' _a : int =self.num_labels _a : Tuple =EsmForTokenClassification(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() _a : Tuple =model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCAmelCase ( self :Dict ) -> List[str]: '''simple docstring''' _a : Optional[Any] =self.prepare_config_and_inputs() ( ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ) : Any =config_and_inputs _a : List[Any] ={"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class A__ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): __UpperCamelCase : Any = False __UpperCamelCase : Any = ( ( EsmForMaskedLM, EsmModel, EsmForSequenceClassification, EsmForTokenClassification, ) if is_torch_available() else () ) __UpperCamelCase : str = () __UpperCamelCase : List[str] = ( { "feature-extraction": EsmModel, "fill-mask": EsmForMaskedLM, "text-classification": EsmForSequenceClassification, "token-classification": EsmForTokenClassification, "zero-shot": EsmForSequenceClassification, } if is_torch_available() else {} ) __UpperCamelCase : Union[str, Any] = True def __UpperCAmelCase ( self :Optional[int] ) -> int: '''simple docstring''' _a : Dict =EsmModelTester(self ) _a : Optional[Any] =ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , hidden_size=3_7 ) def __UpperCAmelCase ( self :Tuple ) -> List[Any]: '''simple docstring''' self.config_tester.run_common_tests() def __UpperCAmelCase ( self :Optional[int] ) -> str: '''simple docstring''' _a : List[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :List[Any] ) -> Dict: '''simple docstring''' _a : List[str] =self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: _a : Dict =type self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Dict ) -> List[str]: '''simple docstring''' _a : Tuple =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :List[Any] ) -> List[str]: '''simple docstring''' _a : str =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE ) @slow def __UpperCAmelCase ( self :str ) -> Dict: '''simple docstring''' for model_name in ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _a : Union[str, Any] =EsmModel.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Tuple ) -> int: '''simple docstring''' _a : Optional[Any] =self.model_tester.prepare_config_and_inputs()[0] _a : Dict =EsmEmbeddings(config=SCREAMING_SNAKE_CASE ) _a : Tuple =torch.as_tensor([[1_2, 3_1, 1_3, model.padding_idx]] ) _a : Optional[Any] =torch.as_tensor( [ [ 0 + model.padding_idx + 1, 1 + model.padding_idx + 1, 2 + model.padding_idx + 1, model.padding_idx, ] ] ) _a : Any =create_position_ids_from_input_ids(SCREAMING_SNAKE_CASE , model.padding_idx ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) ) def __UpperCAmelCase ( self :Optional[Any] ) -> Tuple: '''simple docstring''' _a : List[Any] =self.model_tester.prepare_config_and_inputs()[0] _a : Optional[int] =EsmEmbeddings(config=SCREAMING_SNAKE_CASE ) _a : Tuple =torch.empty(2 , 4 , 3_0 ) _a : str =[ 0 + embeddings.padding_idx + 1, 1 + embeddings.padding_idx + 1, 2 + embeddings.padding_idx + 1, 3 + embeddings.padding_idx + 1, ] _a : int =torch.as_tensor([expected_single_positions, expected_single_positions] ) _a : Any =embeddings.create_position_ids_from_inputs_embeds(SCREAMING_SNAKE_CASE ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) ) @unittest.skip("""Esm does not support embedding resizing""" ) def __UpperCAmelCase ( self :Tuple ) -> List[str]: '''simple docstring''' pass @unittest.skip("""Esm does not support embedding resizing""" ) def __UpperCAmelCase ( self :str ) -> Any: '''simple docstring''' pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def __UpperCAmelCase ( self :Dict ) -> Any: '''simple docstring''' pass @require_torch class A__ ( UpperCAmelCase__ ): @slow def __UpperCAmelCase ( self :List[Any] ) -> str: '''simple docstring''' with torch.no_grad(): _a : Optional[int] =EsmForMaskedLM.from_pretrained("""facebook/esm2_t6_8M_UR50D""" ) model.eval() _a : Any =torch.tensor([[0, 1, 2, 3, 4, 5]] ) _a : Tuple =model(SCREAMING_SNAKE_CASE )[0] _a : int =3_3 _a : Tuple =torch.Size((1, 6, vocab_size) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =torch.tensor( [[[8.9_215, -10.5_898, -6.4_671], [-6.3_967, -13.9_114, -1.1_212], [-7.7_812, -13.9_516, -3.7_406]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) ) @slow def __UpperCAmelCase ( self :Union[str, Any] ) -> Tuple: '''simple docstring''' with torch.no_grad(): _a : Any =EsmModel.from_pretrained("""facebook/esm2_t6_8M_UR50D""" ) model.eval() _a : Any =torch.tensor([[0, 6, 4, 1_3, 5, 4, 1_6, 1_2, 1_1, 7, 2]] ) _a : int =model(SCREAMING_SNAKE_CASE )[0] # compare the actual values for a slice. _a : str =torch.tensor( [[[0.1_444, 0.5_413, 0.3_248], [0.3_034, 0.0_053, 0.3_108], [0.3_228, -0.2_499, 0.3_415]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) )
276
1
'''simple docstring''' import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, ClassLabel, Features from .base import TaskTemplate @dataclass(frozen=UpperCAmelCase__ ) class A__ ( UpperCAmelCase__ ): __UpperCamelCase : str = field(default="audio-classification" , metadata={"include_in_asdict_even_if_is_default": True} ) __UpperCamelCase : ClassVar[Features] = Features({"audio": Audio()} ) __UpperCamelCase : ClassVar[Features] = Features({"labels": ClassLabel} ) __UpperCamelCase : str = "audio" __UpperCamelCase : str = "labels" def __UpperCAmelCase ( self :List[Any] , SCREAMING_SNAKE_CASE :Dict ) -> List[str]: '''simple docstring''' if self.label_column not in features: raise ValueError(f"Column {self.label_column} is not present in features." ) if not isinstance(features[self.label_column] , SCREAMING_SNAKE_CASE ): raise ValueError(f"Column {self.label_column} is not a ClassLabel." ) _a : List[str] =copy.deepcopy(self ) _a : str =self.label_schema.copy() _a : List[Any] =features[self.label_column] _a : Union[str, Any] =label_schema return task_template @property def __UpperCAmelCase ( self :int ) -> Dict[str, str]: '''simple docstring''' return { self.audio_column: "audio", self.label_column: "labels", }
276
'''simple docstring''' from math import isqrt def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ) -> bool: return all(number % divisor != 0 for divisor in range(2 ,isqrt(_UpperCAmelCase ) + 1 ) ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int = 10**6 ) -> int: _a : List[Any] =0 _a : str =1 _a : Optional[Any] =7 while prime_candidate < max_prime: primes_count += is_prime(_UpperCAmelCase ) cube_index += 1 prime_candidate += 6 * cube_index return primes_count if __name__ == "__main__": print(F"{solution() = }")
276
1
'''simple docstring''' import unittest from transformers import ( MODEL_FOR_OBJECT_DETECTION_MAPPING, AutoFeatureExtractor, AutoModelForObjectDetection, ObjectDetectionPipeline, is_vision_available, pipeline, ) from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_pytesseract, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class A__ : @staticmethod def __UpperCAmelCase ( *SCREAMING_SNAKE_CASE :Optional[int] , **SCREAMING_SNAKE_CASE :int ) -> Any: '''simple docstring''' pass @is_pipeline_test @require_vision @require_timm @require_torch class A__ ( unittest.TestCase ): __UpperCamelCase : Optional[int] = MODEL_FOR_OBJECT_DETECTION_MAPPING def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :Optional[int] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Optional[Any] ) -> Optional[Any]: '''simple docstring''' _a : Dict =ObjectDetectionPipeline(model=SCREAMING_SNAKE_CASE , image_processor=SCREAMING_SNAKE_CASE ) return object_detector, ["./tests/fixtures/tests_samples/COCO/000000039769.png"] def __UpperCAmelCase ( self :Dict , SCREAMING_SNAKE_CASE :List[Any] , SCREAMING_SNAKE_CASE :Any ) -> Any: '''simple docstring''' _a : int =object_detector("""./tests/fixtures/tests_samples/COCO/000000039769.png""" , threshold=0.0 ) self.assertGreater(len(SCREAMING_SNAKE_CASE ) , 0 ) for detected_object in outputs: self.assertEqual( SCREAMING_SNAKE_CASE , { """score""": ANY(SCREAMING_SNAKE_CASE ), """label""": ANY(SCREAMING_SNAKE_CASE ), """box""": {"""xmin""": ANY(SCREAMING_SNAKE_CASE ), """ymin""": ANY(SCREAMING_SNAKE_CASE ), """xmax""": ANY(SCREAMING_SNAKE_CASE ), """ymax""": ANY(SCREAMING_SNAKE_CASE )}, } , ) import datasets _a : List[Any] =datasets.load_dataset("""hf-internal-testing/fixtures_image_utils""" , """image""" , split="""test""" ) _a : Optional[int] =[ Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ), """http://images.cocodataset.org/val2017/000000039769.jpg""", # RGBA dataset[0]["""file"""], # LA dataset[1]["""file"""], # L dataset[2]["""file"""], ] _a : Optional[int] =object_detector(SCREAMING_SNAKE_CASE , threshold=0.0 ) self.assertEqual(len(SCREAMING_SNAKE_CASE ) , len(SCREAMING_SNAKE_CASE ) ) for outputs in batch_outputs: self.assertGreater(len(SCREAMING_SNAKE_CASE ) , 0 ) for detected_object in outputs: self.assertEqual( SCREAMING_SNAKE_CASE , { """score""": ANY(SCREAMING_SNAKE_CASE ), """label""": ANY(SCREAMING_SNAKE_CASE ), """box""": {"""xmin""": ANY(SCREAMING_SNAKE_CASE ), """ymin""": ANY(SCREAMING_SNAKE_CASE ), """xmax""": ANY(SCREAMING_SNAKE_CASE ), """ymax""": ANY(SCREAMING_SNAKE_CASE )}, } , ) @require_tf @unittest.skip("""Object detection not implemented in TF""" ) def __UpperCAmelCase ( self :Tuple ) -> Any: '''simple docstring''' pass @require_torch def __UpperCAmelCase ( self :Optional[Any] ) -> Dict: '''simple docstring''' _a : Optional[int] ="""hf-internal-testing/tiny-detr-mobilenetsv3""" _a : List[str] =AutoModelForObjectDetection.from_pretrained(SCREAMING_SNAKE_CASE ) _a : int =AutoFeatureExtractor.from_pretrained(SCREAMING_SNAKE_CASE ) _a : List[Any] =ObjectDetectionPipeline(model=SCREAMING_SNAKE_CASE , feature_extractor=SCREAMING_SNAKE_CASE ) _a : Optional[Any] =object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" , threshold=0.0 ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.3_376, """label""": """LABEL_0""", """box""": {"""xmin""": 1_5_9, """ymin""": 1_2_0, """xmax""": 4_8_0, """ymax""": 3_5_9}}, {"""score""": 0.3_376, """label""": """LABEL_0""", """box""": {"""xmin""": 1_5_9, """ymin""": 1_2_0, """xmax""": 4_8_0, """ymax""": 3_5_9}}, ] , ) _a : Optional[int] =object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] , threshold=0.0 , ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.3_376, """label""": """LABEL_0""", """box""": {"""xmin""": 1_5_9, """ymin""": 1_2_0, """xmax""": 4_8_0, """ymax""": 3_5_9}}, {"""score""": 0.3_376, """label""": """LABEL_0""", """box""": {"""xmin""": 1_5_9, """ymin""": 1_2_0, """xmax""": 4_8_0, """ymax""": 3_5_9}}, ], [ {"""score""": 0.3_376, """label""": """LABEL_0""", """box""": {"""xmin""": 1_5_9, """ymin""": 1_2_0, """xmax""": 4_8_0, """ymax""": 3_5_9}}, {"""score""": 0.3_376, """label""": """LABEL_0""", """box""": {"""xmin""": 1_5_9, """ymin""": 1_2_0, """xmax""": 4_8_0, """ymax""": 3_5_9}}, ], ] , ) @require_torch @slow def __UpperCAmelCase ( self :Any ) -> int: '''simple docstring''' _a : int ="""facebook/detr-resnet-50""" _a : Any =AutoModelForObjectDetection.from_pretrained(SCREAMING_SNAKE_CASE ) _a : Dict =AutoFeatureExtractor.from_pretrained(SCREAMING_SNAKE_CASE ) _a : Dict =ObjectDetectionPipeline(model=SCREAMING_SNAKE_CASE , feature_extractor=SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9_982, """label""": """remote""", """box""": {"""xmin""": 4_0, """ymin""": 7_0, """xmax""": 1_7_5, """ymax""": 1_1_7}}, {"""score""": 0.9_960, """label""": """remote""", """box""": {"""xmin""": 3_3_3, """ymin""": 7_2, """xmax""": 3_6_8, """ymax""": 1_8_7}}, {"""score""": 0.9_955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 6_3_9, """ymax""": 4_7_3}}, {"""score""": 0.9_988, """label""": """cat""", """box""": {"""xmin""": 1_3, """ymin""": 5_2, """xmax""": 3_1_4, """ymax""": 4_7_0}}, {"""score""": 0.9_987, """label""": """cat""", """box""": {"""xmin""": 3_4_5, """ymin""": 2_3, """xmax""": 6_4_0, """ymax""": 3_6_8}}, ] , ) _a : str =object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.9_982, """label""": """remote""", """box""": {"""xmin""": 4_0, """ymin""": 7_0, """xmax""": 1_7_5, """ymax""": 1_1_7}}, {"""score""": 0.9_960, """label""": """remote""", """box""": {"""xmin""": 3_3_3, """ymin""": 7_2, """xmax""": 3_6_8, """ymax""": 1_8_7}}, {"""score""": 0.9_955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 6_3_9, """ymax""": 4_7_3}}, {"""score""": 0.9_988, """label""": """cat""", """box""": {"""xmin""": 1_3, """ymin""": 5_2, """xmax""": 3_1_4, """ymax""": 4_7_0}}, {"""score""": 0.9_987, """label""": """cat""", """box""": {"""xmin""": 3_4_5, """ymin""": 2_3, """xmax""": 6_4_0, """ymax""": 3_6_8}}, ], [ {"""score""": 0.9_982, """label""": """remote""", """box""": {"""xmin""": 4_0, """ymin""": 7_0, """xmax""": 1_7_5, """ymax""": 1_1_7}}, {"""score""": 0.9_960, """label""": """remote""", """box""": {"""xmin""": 3_3_3, """ymin""": 7_2, """xmax""": 3_6_8, """ymax""": 1_8_7}}, {"""score""": 0.9_955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 6_3_9, """ymax""": 4_7_3}}, {"""score""": 0.9_988, """label""": """cat""", """box""": {"""xmin""": 1_3, """ymin""": 5_2, """xmax""": 3_1_4, """ymax""": 4_7_0}}, {"""score""": 0.9_987, """label""": """cat""", """box""": {"""xmin""": 3_4_5, """ymin""": 2_3, """xmax""": 6_4_0, """ymax""": 3_6_8}}, ], ] , ) @require_torch @slow def __UpperCAmelCase ( self :str ) -> List[Any]: '''simple docstring''' _a : Dict ="""facebook/detr-resnet-50""" _a : List[str] =pipeline("""object-detection""" , model=SCREAMING_SNAKE_CASE ) _a : Any =object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9_982, """label""": """remote""", """box""": {"""xmin""": 4_0, """ymin""": 7_0, """xmax""": 1_7_5, """ymax""": 1_1_7}}, {"""score""": 0.9_960, """label""": """remote""", """box""": {"""xmin""": 3_3_3, """ymin""": 7_2, """xmax""": 3_6_8, """ymax""": 1_8_7}}, {"""score""": 0.9_955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 6_3_9, """ymax""": 4_7_3}}, {"""score""": 0.9_988, """label""": """cat""", """box""": {"""xmin""": 1_3, """ymin""": 5_2, """xmax""": 3_1_4, """ymax""": 4_7_0}}, {"""score""": 0.9_987, """label""": """cat""", """box""": {"""xmin""": 3_4_5, """ymin""": 2_3, """xmax""": 6_4_0, """ymax""": 3_6_8}}, ] , ) _a : List[Any] =object_detector( [ """http://images.cocodataset.org/val2017/000000039769.jpg""", """http://images.cocodataset.org/val2017/000000039769.jpg""", ] ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.9_982, """label""": """remote""", """box""": {"""xmin""": 4_0, """ymin""": 7_0, """xmax""": 1_7_5, """ymax""": 1_1_7}}, {"""score""": 0.9_960, """label""": """remote""", """box""": {"""xmin""": 3_3_3, """ymin""": 7_2, """xmax""": 3_6_8, """ymax""": 1_8_7}}, {"""score""": 0.9_955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 6_3_9, """ymax""": 4_7_3}}, {"""score""": 0.9_988, """label""": """cat""", """box""": {"""xmin""": 1_3, """ymin""": 5_2, """xmax""": 3_1_4, """ymax""": 4_7_0}}, {"""score""": 0.9_987, """label""": """cat""", """box""": {"""xmin""": 3_4_5, """ymin""": 2_3, """xmax""": 6_4_0, """ymax""": 3_6_8}}, ], [ {"""score""": 0.9_982, """label""": """remote""", """box""": {"""xmin""": 4_0, """ymin""": 7_0, """xmax""": 1_7_5, """ymax""": 1_1_7}}, {"""score""": 0.9_960, """label""": """remote""", """box""": {"""xmin""": 3_3_3, """ymin""": 7_2, """xmax""": 3_6_8, """ymax""": 1_8_7}}, {"""score""": 0.9_955, """label""": """couch""", """box""": {"""xmin""": 0, """ymin""": 1, """xmax""": 6_3_9, """ymax""": 4_7_3}}, {"""score""": 0.9_988, """label""": """cat""", """box""": {"""xmin""": 1_3, """ymin""": 5_2, """xmax""": 3_1_4, """ymax""": 4_7_0}}, {"""score""": 0.9_987, """label""": """cat""", """box""": {"""xmin""": 3_4_5, """ymin""": 2_3, """xmax""": 6_4_0, """ymax""": 3_6_8}}, ], ] , ) @require_torch @slow def __UpperCAmelCase ( self :List[Any] ) -> Tuple: '''simple docstring''' _a : List[str] =0.9_985 _a : int ="""facebook/detr-resnet-50""" _a : Optional[Any] =pipeline("""object-detection""" , model=SCREAMING_SNAKE_CASE ) _a : List[Any] =object_detector("""http://images.cocodataset.org/val2017/000000039769.jpg""" , threshold=SCREAMING_SNAKE_CASE ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9_988, """label""": """cat""", """box""": {"""xmin""": 1_3, """ymin""": 5_2, """xmax""": 3_1_4, """ymax""": 4_7_0}}, {"""score""": 0.9_987, """label""": """cat""", """box""": {"""xmin""": 3_4_5, """ymin""": 2_3, """xmax""": 6_4_0, """ymax""": 3_6_8}}, ] , ) @require_torch @require_pytesseract @slow def __UpperCAmelCase ( self :Dict ) -> Optional[Any]: '''simple docstring''' _a : str ="""Narsil/layoutlmv3-finetuned-funsd""" _a : str =0.9_993 _a : List[str] =pipeline("""object-detection""" , model=SCREAMING_SNAKE_CASE , threshold=SCREAMING_SNAKE_CASE ) _a : Optional[Any] =object_detector( """https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png""" ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9_993, """label""": """I-ANSWER""", """box""": {"""xmin""": 2_9_4, """ymin""": 2_5_4, """xmax""": 3_4_3, """ymax""": 2_6_4}}, {"""score""": 0.9_993, """label""": """I-ANSWER""", """box""": {"""xmin""": 2_9_4, """ymin""": 2_5_4, """xmax""": 3_4_3, """ymax""": 2_6_4}}, ] , )
276
'''simple docstring''' # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from ...utils import deprecate from ..controlnet.multicontrolnet import MultiControlNetModel # noqa: F401 from ..controlnet.pipeline_controlnet import StableDiffusionControlNetPipeline # noqa: F401 deprecate( '''stable diffusion controlnet''', '''0.22.0''', '''Importing `StableDiffusionControlNetPipeline` or `MultiControlNetModel` from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import StableDiffusionControlNetPipeline` instead.''', standard_warn=False, stacklevel=3, )
276
1
'''simple docstring''' def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int = 100 ) -> int: _a : Dict =set() _a : str =0 _a : List[str] =n + 1 # maximum limit for a in range(2 ,_UpperCAmelCase ): for b in range(2 ,_UpperCAmelCase ): _a : Optional[int] =a**b # calculates the current power collect_powers.add(_UpperCAmelCase ) # adds the result to the set return len(_UpperCAmelCase ) if __name__ == "__main__": print('''Number of terms ''', solution(int(str(input()).strip())))
276
'''simple docstring''' import pytest from datasets.utils.sharding import _distribute_shards, _number_of_shards_in_gen_kwargs, _split_gen_kwargs @pytest.mark.parametrize( """kwargs, expected""" ,[ ({"""num_shards""": 0, """max_num_jobs""": 1}, []), ({"""num_shards""": 10, """max_num_jobs""": 1}, [range(10 )]), ({"""num_shards""": 10, """max_num_jobs""": 10}, [range(_UpperCAmelCase ,i + 1 ) for i in range(10 )]), ({"""num_shards""": 1, """max_num_jobs""": 10}, [range(1 )]), ({"""num_shards""": 10, """max_num_jobs""": 3}, [range(0 ,4 ), range(4 ,7 ), range(7 ,10 )]), ({"""num_shards""": 3, """max_num_jobs""": 10}, [range(0 ,1 ), range(1 ,2 ), range(2 ,3 )]), ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : Dict ) -> Optional[Any]: _a : Tuple =_distribute_shards(**_UpperCAmelCase ) assert out == expected @pytest.mark.parametrize( """gen_kwargs, max_num_jobs, expected""" ,[ ({"""foo""": 0}, 10, [{"""foo""": 0}]), ({"""shards""": [0, 1, 2, 3]}, 1, [{"""shards""": [0, 1, 2, 3]}]), ({"""shards""": [0, 1, 2, 3]}, 4, [{"""shards""": [0]}, {"""shards""": [1]}, {"""shards""": [2]}, {"""shards""": [3]}]), ({"""shards""": [0, 1]}, 4, [{"""shards""": [0]}, {"""shards""": [1]}]), ({"""shards""": [0, 1, 2, 3]}, 2, [{"""shards""": [0, 1]}, {"""shards""": [2, 3]}]), ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : List[Any] ,_UpperCAmelCase : Union[str, Any] ) -> List[str]: _a : List[str] =_split_gen_kwargs(_UpperCAmelCase ,_UpperCAmelCase ) assert out == expected @pytest.mark.parametrize( """gen_kwargs, expected""" ,[ ({"""foo""": 0}, 1), ({"""shards""": [0]}, 1), ({"""shards""": [0, 1, 2, 3]}, 4), ({"""shards""": [0, 1, 2, 3], """foo""": 0}, 4), ({"""shards""": [0, 1, 2, 3], """other""": (0, 1)}, 4), ({"""shards""": [0, 1, 2, 3], """shards2""": [0, 1]}, RuntimeError), ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : List[Any] ) -> Union[str, Any]: if expected is RuntimeError: with pytest.raises(_UpperCAmelCase ): _number_of_shards_in_gen_kwargs(_UpperCAmelCase ) else: _a : Dict =_number_of_shards_in_gen_kwargs(_UpperCAmelCase ) assert out == expected
276
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A__: Optional[int] = logging.get_logger(__name__) A__: Tuple = { '''alibaba-damo/mgp-str-base''': '''https://huggingface.co/alibaba-damo/mgp-str-base/resolve/main/config.json''', } class A__ ( UpperCAmelCase__ ): __UpperCamelCase : Dict = "mgp-str" def __init__( self :List[str] , SCREAMING_SNAKE_CASE :Union[str, Any]=[3_2, 1_2_8] , SCREAMING_SNAKE_CASE :int=4 , SCREAMING_SNAKE_CASE :Union[str, Any]=3 , SCREAMING_SNAKE_CASE :Optional[Any]=2_7 , SCREAMING_SNAKE_CASE :Tuple=3_8 , SCREAMING_SNAKE_CASE :List[Any]=5_0_2_5_7 , SCREAMING_SNAKE_CASE :int=3_0_5_2_2 , SCREAMING_SNAKE_CASE :int=7_6_8 , SCREAMING_SNAKE_CASE :str=1_2 , SCREAMING_SNAKE_CASE :Tuple=1_2 , SCREAMING_SNAKE_CASE :Optional[int]=4.0 , SCREAMING_SNAKE_CASE :Optional[Any]=True , SCREAMING_SNAKE_CASE :int=False , SCREAMING_SNAKE_CASE :Optional[int]=1e-5 , SCREAMING_SNAKE_CASE :Union[str, Any]=0.0 , SCREAMING_SNAKE_CASE :str=0.0 , SCREAMING_SNAKE_CASE :List[str]=0.0 , SCREAMING_SNAKE_CASE :str=False , SCREAMING_SNAKE_CASE :int=0.02 , **SCREAMING_SNAKE_CASE :Optional[Any] , ) -> Any: '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE ) _a : str =image_size _a : Optional[Any] =patch_size _a : Any =num_channels _a : int =max_token_length _a : List[str] =num_character_labels _a : int =num_bpe_labels _a : Dict =num_wordpiece_labels _a : str =hidden_size _a : Optional[Any] =num_hidden_layers _a : str =num_attention_heads _a : int =mlp_ratio _a : int =distilled _a : Union[str, Any] =layer_norm_eps _a : Dict =drop_rate _a : Optional[int] =qkv_bias _a : str =attn_drop_rate _a : Tuple =drop_path_rate _a : Union[str, Any] =output_aa_attentions _a : Dict =initializer_range
276
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A__: Dict = logging.get_logger(__name__) A__: Tuple = { '''weiweishi/roc-bert-base-zh''': '''https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json''', } class A__ ( UpperCAmelCase__ ): __UpperCamelCase : Tuple = "roc_bert" def __init__( self :Optional[int] , SCREAMING_SNAKE_CASE :Tuple=3_0_5_2_2 , SCREAMING_SNAKE_CASE :List[str]=7_6_8 , SCREAMING_SNAKE_CASE :Dict=1_2 , SCREAMING_SNAKE_CASE :List[str]=1_2 , SCREAMING_SNAKE_CASE :Tuple=3_0_7_2 , SCREAMING_SNAKE_CASE :List[Any]="gelu" , SCREAMING_SNAKE_CASE :Union[str, Any]=0.1 , SCREAMING_SNAKE_CASE :List[Any]=0.1 , SCREAMING_SNAKE_CASE :int=5_1_2 , SCREAMING_SNAKE_CASE :Optional[Any]=2 , SCREAMING_SNAKE_CASE :Union[str, Any]=0.02 , SCREAMING_SNAKE_CASE :Optional[Any]=1e-12 , SCREAMING_SNAKE_CASE :Any=True , SCREAMING_SNAKE_CASE :List[Any]=0 , SCREAMING_SNAKE_CASE :Optional[int]="absolute" , SCREAMING_SNAKE_CASE :Union[str, Any]=None , SCREAMING_SNAKE_CASE :List[Any]=True , SCREAMING_SNAKE_CASE :int=True , SCREAMING_SNAKE_CASE :Optional[int]=7_6_8 , SCREAMING_SNAKE_CASE :Optional[Any]=9_1_0 , SCREAMING_SNAKE_CASE :Union[str, Any]=5_1_2 , SCREAMING_SNAKE_CASE :str=2_4_8_5_8 , SCREAMING_SNAKE_CASE :List[Any]=True , **SCREAMING_SNAKE_CASE :Tuple , ) -> Optional[int]: '''simple docstring''' _a : List[str] =vocab_size _a : List[str] =max_position_embeddings _a : Optional[Any] =hidden_size _a : List[Any] =num_hidden_layers _a : List[str] =num_attention_heads _a : int =intermediate_size _a : Any =hidden_act _a : Dict =hidden_dropout_prob _a : int =attention_probs_dropout_prob _a : str =initializer_range _a : Optional[int] =type_vocab_size _a : Any =layer_norm_eps _a : Any =use_cache _a : Optional[int] =enable_pronunciation _a : Optional[Any] =enable_shape _a : Optional[Any] =pronunciation_embed_dim _a : Tuple =pronunciation_vocab_size _a : Union[str, Any] =shape_embed_dim _a : Any =shape_vocab_size _a : Tuple =concat_input _a : List[str] =position_embedding_type _a : List[str] =classifier_dropout super().__init__(pad_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE )
276
1
'''simple docstring''' import argparse import requests import torch from PIL import Image from transformers import SwinConfig, SwinForMaskedImageModeling, ViTImageProcessor def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ) -> Dict: _a : Dict =SwinConfig(image_size=192 ) if "base" in model_name: _a : List[Any] =6 _a : Dict =128 _a : Optional[Any] =(2, 2, 18, 2) _a : Any =(4, 8, 16, 32) elif "large" in model_name: _a : Dict =12 _a : Dict =192 _a : str =(2, 2, 18, 2) _a : Any =(6, 12, 24, 48) else: raise ValueError("""Model not supported, only supports base and large variants""" ) _a : Optional[int] =window_size _a : Union[str, Any] =embed_dim _a : Dict =depths _a : str =num_heads return config def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Dict ) -> List[Any]: if "encoder.mask_token" in name: _a : List[str] =name.replace("""encoder.mask_token""" ,"""embeddings.mask_token""" ) if "encoder.patch_embed.proj" in name: _a : str =name.replace("""encoder.patch_embed.proj""" ,"""embeddings.patch_embeddings.projection""" ) if "encoder.patch_embed.norm" in name: _a : Union[str, Any] =name.replace("""encoder.patch_embed.norm""" ,"""embeddings.norm""" ) if "attn.proj" in name: _a : Dict =name.replace("""attn.proj""" ,"""attention.output.dense""" ) if "attn" in name: _a : str =name.replace("""attn""" ,"""attention.self""" ) if "norm1" in name: _a : List[Any] =name.replace("""norm1""" ,"""layernorm_before""" ) if "norm2" in name: _a : Any =name.replace("""norm2""" ,"""layernorm_after""" ) if "mlp.fc1" in name: _a : Optional[int] =name.replace("""mlp.fc1""" ,"""intermediate.dense""" ) if "mlp.fc2" in name: _a : Dict =name.replace("""mlp.fc2""" ,"""output.dense""" ) if name == "encoder.norm.weight": _a : Any ="""layernorm.weight""" if name == "encoder.norm.bias": _a : Optional[Any] ="""layernorm.bias""" if "decoder" in name: pass else: _a : List[Any] ="""swin.""" + name return name def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ,_UpperCAmelCase : Union[str, Any] ) -> Dict: for key in orig_state_dict.copy().keys(): _a : Tuple =orig_state_dict.pop(_UpperCAmelCase ) if "attn_mask" in key: pass elif "qkv" in key: _a : Tuple =key.split(""".""" ) _a : Optional[int] =int(key_split[2] ) _a : List[Any] =int(key_split[4] ) _a : Union[str, Any] =model.swin.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: _a : List[Any] =val[:dim, :] _a : str =val[ dim : dim * 2, : ] _a : int =val[-dim:, :] else: _a : Optional[Any] =val[ :dim ] _a : Optional[Any] =val[ dim : dim * 2 ] _a : List[Any] =val[ -dim: ] else: _a : Optional[int] =val return orig_state_dict def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : int ,_UpperCAmelCase : Dict ) -> List[Any]: _a : List[Any] =torch.load(_UpperCAmelCase ,map_location="""cpu""" )["""model"""] _a : Any =get_swin_config(_UpperCAmelCase ) _a : Dict =SwinForMaskedImageModeling(_UpperCAmelCase ) model.eval() _a : Union[str, Any] =convert_state_dict(_UpperCAmelCase ,_UpperCAmelCase ) model.load_state_dict(_UpperCAmelCase ) _a : Optional[int] ="""http://images.cocodataset.org/val2017/000000039769.jpg""" _a : Any =ViTImageProcessor(size={"""height""": 192, """width""": 192} ) _a : Any =Image.open(requests.get(_UpperCAmelCase ,stream=_UpperCAmelCase ).raw ) _a : Optional[Any] =image_processor(images=_UpperCAmelCase ,return_tensors="""pt""" ) with torch.no_grad(): _a : Optional[int] =model(**_UpperCAmelCase ).logits print(outputs.keys() ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: print(F"Saving model {model_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(_UpperCAmelCase ) print(F"Saving image processor to {pytorch_dump_folder_path}" ) image_processor.save_pretrained(_UpperCAmelCase ) if push_to_hub: print(F"Pushing model and image processor for {model_name} to hub" ) model.push_to_hub(F"microsoft/{model_name}" ) image_processor.push_to_hub(F"microsoft/{model_name}" ) if __name__ == "__main__": A__: Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default='''swin-base-simmim-window6-192''', type=str, choices=['''swin-base-simmim-window6-192''', '''swin-large-simmim-window12-192'''], help='''Name of the Swin SimMIM model you\'d like to convert.''', ) parser.add_argument( '''--checkpoint_path''', default='''/Users/nielsrogge/Documents/SwinSimMIM/simmim_pretrain__swin_base__img192_window6__100ep.pth''', type=str, help='''Path to the original PyTorch checkpoint (.pth file).''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) parser.add_argument( '''--push_to_hub''', action='''store_true''', help='''Whether or not to push the converted model to the 🤗 hub.''' ) A__: Optional[int] = parser.parse_args() convert_swin_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub)
276
'''simple docstring''' class A__ : def __init__( self :List[str] ) -> List[Any]: '''simple docstring''' _a : Tuple =0 _a : Any =0 _a : int ={} def __UpperCAmelCase ( self :Any , SCREAMING_SNAKE_CASE :List[str] ) -> Optional[int]: '''simple docstring''' if vertex not in self.adjacency: _a : Dict ={} self.num_vertices += 1 def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Any ) -> List[str]: '''simple docstring''' self.add_vertex(SCREAMING_SNAKE_CASE ) self.add_vertex(SCREAMING_SNAKE_CASE ) if head == tail: return _a : Any =weight _a : Tuple =weight def __UpperCAmelCase ( self :Dict ) -> Optional[int]: '''simple docstring''' _a : Union[str, Any] =self.get_edges() for edge in edges: _a , _a , _a : List[str] =edge edges.remove((tail, head, weight) ) for i in range(len(SCREAMING_SNAKE_CASE ) ): _a : str =list(edges[i] ) edges.sort(key=lambda SCREAMING_SNAKE_CASE : e[2] ) for i in range(len(SCREAMING_SNAKE_CASE ) - 1 ): if edges[i][2] >= edges[i + 1][2]: _a : Union[str, Any] =edges[i][2] + 1 for edge in edges: _a , _a , _a : Tuple =edge _a : Tuple =weight _a : List[Any] =weight def __str__( self :int ) -> str: '''simple docstring''' _a : int ="""""" for tail in self.adjacency: for head in self.adjacency[tail]: _a : str =self.adjacency[head][tail] string += f"{head} -> {tail} == {weight}\n" return string.rstrip("""\n""" ) def __UpperCAmelCase ( self :Optional[int] ) -> Optional[Any]: '''simple docstring''' _a : Union[str, Any] =[] for tail in self.adjacency: for head in self.adjacency[tail]: output.append((tail, head, self.adjacency[head][tail]) ) return output def __UpperCAmelCase ( self :List[Any] ) -> List[Any]: '''simple docstring''' return self.adjacency.keys() @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :Dict=None , SCREAMING_SNAKE_CASE :List[Any]=None ) -> Optional[int]: '''simple docstring''' _a : str =Graph() if vertices is None: _a : Union[str, Any] =[] if edges is None: _a : List[Any] =[] for vertex in vertices: g.add_vertex(SCREAMING_SNAKE_CASE ) for edge in edges: g.add_edge(*SCREAMING_SNAKE_CASE ) return g class A__ : def __init__( self :Optional[int] ) -> Union[str, Any]: '''simple docstring''' _a : Optional[int] ={} _a : List[str] ={} def __len__( self :List[Any] ) -> List[Any]: '''simple docstring''' return len(self.parent ) def __UpperCAmelCase ( self :Tuple , SCREAMING_SNAKE_CASE :Tuple ) -> Dict: '''simple docstring''' if item in self.parent: return self.find(SCREAMING_SNAKE_CASE ) _a : Optional[Any] =item _a : List[str] =0 return item def __UpperCAmelCase ( self :int , SCREAMING_SNAKE_CASE :Dict ) -> List[str]: '''simple docstring''' if item not in self.parent: return self.make_set(SCREAMING_SNAKE_CASE ) if item != self.parent[item]: _a : str =self.find(self.parent[item] ) return self.parent[item] def __UpperCAmelCase ( self :Optional[int] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :List[Any] ) -> Optional[Any]: '''simple docstring''' _a : Optional[int] =self.find(SCREAMING_SNAKE_CASE ) _a : Dict =self.find(SCREAMING_SNAKE_CASE ) if roota == roota: return roota if self.rank[roota] > self.rank[roota]: _a : Any =roota return roota if self.rank[roota] < self.rank[roota]: _a : List[str] =roota return roota if self.rank[roota] == self.rank[roota]: self.rank[roota] += 1 _a : List[Any] =roota return roota return None @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :Dict ) -> Union[str, Any]: '''simple docstring''' _a : Any =graph.num_vertices _a : Union[str, Any] =Graph.UnionFind() _a : Optional[int] =[] while num_components > 1: _a : str ={} for vertex in graph.get_vertices(): _a : List[str] =-1 _a : Any =graph.get_edges() for edge in edges: _a , _a , _a : Tuple =edge edges.remove((tail, head, weight) ) for edge in edges: _a , _a , _a : Any =edge _a : Any =union_find.find(SCREAMING_SNAKE_CASE ) _a : List[Any] =union_find.find(SCREAMING_SNAKE_CASE ) if seta != seta: if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight: _a : Optional[int] =[head, tail, weight] if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight: _a : List[Any] =[head, tail, weight] for vertex in cheap_edge: if cheap_edge[vertex] != -1: _a , _a , _a : Optional[Any] =cheap_edge[vertex] if union_find.find(SCREAMING_SNAKE_CASE ) != union_find.find(SCREAMING_SNAKE_CASE ): union_find.union(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) mst_edges.append(cheap_edge[vertex] ) _a : str =num_components - 1 _a : str =Graph.build(edges=SCREAMING_SNAKE_CASE ) return mst
276
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) A__: Optional[int] = { '''configuration_clip''': [ '''CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''CLIPConfig''', '''CLIPOnnxConfig''', '''CLIPTextConfig''', '''CLIPVisionConfig''', ], '''processing_clip''': ['''CLIPProcessor'''], '''tokenization_clip''': ['''CLIPTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: str = ['''CLIPTokenizerFast'''] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Union[str, Any] = ['''CLIPFeatureExtractor'''] A__: Tuple = ['''CLIPImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: List[str] = [ '''CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''CLIPModel''', '''CLIPPreTrainedModel''', '''CLIPTextModel''', '''CLIPTextModelWithProjection''', '''CLIPVisionModel''', '''CLIPVisionModelWithProjection''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: int = [ '''TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFCLIPModel''', '''TFCLIPPreTrainedModel''', '''TFCLIPTextModel''', '''TFCLIPVisionModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Optional[int] = [ '''FlaxCLIPModel''', '''FlaxCLIPPreTrainedModel''', '''FlaxCLIPTextModel''', '''FlaxCLIPTextPreTrainedModel''', '''FlaxCLIPVisionModel''', '''FlaxCLIPVisionPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_clip import ( CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, CLIPConfig, CLIPOnnxConfig, CLIPTextConfig, CLIPVisionConfig, ) from .processing_clip import CLIPProcessor from .tokenization_clip import CLIPTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_clip_fast import CLIPTokenizerFast try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_clip import CLIPFeatureExtractor from .image_processing_clip import CLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_clip import ( CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, CLIPModel, CLIPPreTrainedModel, CLIPTextModel, CLIPTextModelWithProjection, CLIPVisionModel, CLIPVisionModelWithProjection, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_clip import ( TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFCLIPModel, TFCLIPPreTrainedModel, TFCLIPTextModel, TFCLIPVisionModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_clip import ( FlaxCLIPModel, FlaxCLIPPreTrainedModel, FlaxCLIPTextModel, FlaxCLIPTextPreTrainedModel, FlaxCLIPVisionModel, FlaxCLIPVisionPreTrainedModel, ) else: import sys A__: Union[str, Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
276
'''simple docstring''' from datetime import datetime import requests from bsa import BeautifulSoup if __name__ == "__main__": A__: Union[str, Any] = input('''Enter image url: ''').strip() print(F"Downloading image from {url} ...") A__: Tuple = BeautifulSoup(requests.get(url).content, '''html.parser''') # The image URL is in the content field of the first meta tag with property og:image A__: Union[str, Any] = soup.find('''meta''', {'''property''': '''og:image'''})['''content'''] A__: List[Any] = requests.get(image_url).content A__: List[str] = F"{datetime.now():%Y-%m-%d_%H:%M:%S}.jpg" with open(file_name, '''wb''') as fp: fp.write(image_data) print(F"Done. Image saved to disk as {file_name}.")
276
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available A__: int = {'''tokenization_herbert''': ['''HerbertTokenizer''']} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Union[str, Any] = ['''HerbertTokenizerFast'''] if TYPE_CHECKING: from .tokenization_herbert import HerbertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_herbert_fast import HerbertTokenizerFast else: import sys A__: Tuple = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
276
'''simple docstring''' A__: Tuple = ''' # Installazione di Transformers ! pip install transformers datasets # Per installare dalla fonte invece dell\'ultima versione rilasciata, commenta il comando sopra e # rimuovi la modalità commento al comando seguente. # ! pip install git+https://github.com/huggingface/transformers.git ''' A__: Tuple = [{'''type''': '''code''', '''content''': INSTALL_CONTENT}] A__: Any = { '''{processor_class}''': '''FakeProcessorClass''', '''{model_class}''': '''FakeModelClass''', '''{object_class}''': '''FakeObjectClass''', }
276
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import _LazyModule A__: int = {'''processing_wav2vec2_with_lm''': ['''Wav2Vec2ProcessorWithLM''']} if TYPE_CHECKING: from .processing_wavaveca_with_lm import WavaVecaProcessorWithLM else: import sys A__: Union[str, Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
276
'''simple docstring''' A__: Optional[int] = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] A__: Any = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] A__: int = { 0: '''Sunday''', 1: '''Monday''', 2: '''Tuesday''', 3: '''Wednesday''', 4: '''Thursday''', 5: '''Friday''', 6: '''Saturday''', } def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ,_UpperCAmelCase : int ,_UpperCAmelCase : int ) -> str: assert len(str(_UpperCAmelCase ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 12, "month should be between 1 to 12" assert 1 <= day <= 31, "day should be between 1 to 31" # Doomsday algorithm: _a : List[str] =year // 100 _a : List[str] =(5 * (century % 4) + 2) % 7 _a : Optional[int] =year % 100 _a : Any =centurian % 12 _a : int =( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 _a : Optional[Any] =( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 400) == 0) else DOOMSDAY_LEAP[month - 1] ) _a : str =(dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
276
1
'''simple docstring''' import string from math import logaa def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : str ) -> int: _a : Dict =document.translate( str.maketrans("""""" ,"""""" ,string.punctuation ) ).replace("""\n""" ,"""""" ) _a : int =document_without_punctuation.split(""" """ ) # word tokenization return len([word for word in tokenize_document if word.lower() == term.lower()] ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : str ) -> tuple[int, int]: _a : str =corpus.lower().translate( str.maketrans("""""" ,"""""" ,string.punctuation ) ) # strip all punctuation and replace it with '' _a : int =corpus_without_punctuation.split("""\n""" ) _a : Dict =term.lower() return (len([doc for doc in docs if term in doc] ), len(_UpperCAmelCase )) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ,_UpperCAmelCase : int ,_UpperCAmelCase : List[Any]=False ) -> float: if smoothing: if n == 0: raise ValueError("""log10(0) is undefined.""" ) return round(1 + logaa(n / (1 + df) ) ,3 ) if df == 0: raise ZeroDivisionError("""df must be > 0""" ) elif n == 0: raise ValueError("""log10(0) is undefined.""" ) return round(logaa(n / df ) ,3 ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ,_UpperCAmelCase : int ) -> float: return round(tf * idf ,3 )
276
'''simple docstring''' from __future__ import annotations from typing import TypedDict class A__ ( UpperCAmelCase__ ): __UpperCamelCase : str __UpperCamelCase : int def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ) -> list[str]: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError("""The parameter s type must be str.""" ) return [s[i:] + s[:i] for i in range(len(_UpperCAmelCase ) )] def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ) -> BWTTransformDict: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError("""The parameter s type must be str.""" ) if not s: raise ValueError("""The parameter s must not be empty.""" ) _a : List[Any] =all_rotations(_UpperCAmelCase ) rotations.sort() # sort the list of rotations in alphabetically order # make a string composed of the last char of each rotation _a : BWTTransformDict ={ "bwt_string": "".join([word[-1] for word in rotations] ), "idx_original_string": rotations.index(_UpperCAmelCase ), } return response def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : int ) -> str: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError("""The parameter bwt_string type must be str.""" ) if not bwt_string: raise ValueError("""The parameter bwt_string must not be empty.""" ) try: _a : List[str] =int(_UpperCAmelCase ) except ValueError: raise TypeError( """The parameter idx_original_string type must be int or passive""" """ of cast to int.""" ) if idx_original_string < 0: raise ValueError("""The parameter idx_original_string must not be lower than 0.""" ) if idx_original_string >= len(_UpperCAmelCase ): raise ValueError( """The parameter idx_original_string must be lower than""" """ len(bwt_string).""" ) _a : Optional[int] =[""""""] * len(_UpperCAmelCase ) for _ in range(len(_UpperCAmelCase ) ): for i in range(len(_UpperCAmelCase ) ): _a : int =bwt_string[i] + ordered_rotations[i] ordered_rotations.sort() return ordered_rotations[idx_original_string] if __name__ == "__main__": A__: Any = '''Provide a string that I will generate its BWT transform: ''' A__: Union[str, Any] = input(entry_msg).strip() A__: Optional[int] = bwt_transform(s) print( F"Burrows Wheeler transform for string '{s}' results " F"in '{result['bwt_string']}'" ) A__: Union[str, Any] = reverse_bwt(result['''bwt_string'''], result['''idx_original_string''']) print( F"Reversing Burrows Wheeler transform for entry '{result['bwt_string']}' " F"we get original string '{original_string}'" )
276
1
'''simple docstring''' def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ) -> str: if number > 0: raise ValueError("""input must be a negative integer""" ) _a : int =len(bin(_UpperCAmelCase )[3:] ) _a : Tuple =bin(abs(_UpperCAmelCase ) - (1 << binary_number_length) )[3:] _a : Tuple =( ( """1""" + """0""" * (binary_number_length - len(_UpperCAmelCase )) + twos_complement_number ) if number < 0 else """0""" ) return "0b" + twos_complement_number if __name__ == "__main__": import doctest doctest.testmod()
276
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available A__: List[str] = { '''configuration_chinese_clip''': [ '''CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ChineseCLIPConfig''', '''ChineseCLIPOnnxConfig''', '''ChineseCLIPTextConfig''', '''ChineseCLIPVisionConfig''', ], '''processing_chinese_clip''': ['''ChineseCLIPProcessor'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Optional[int] = ['''ChineseCLIPFeatureExtractor'''] A__: Any = ['''ChineseCLIPImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Dict = [ '''CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ChineseCLIPModel''', '''ChineseCLIPPreTrainedModel''', '''ChineseCLIPTextModel''', '''ChineseCLIPVisionModel''', ] if TYPE_CHECKING: from .configuration_chinese_clip import ( CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, ChineseCLIPConfig, ChineseCLIPOnnxConfig, ChineseCLIPTextConfig, ChineseCLIPVisionConfig, ) from .processing_chinese_clip import ChineseCLIPProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_chinese_clip import ChineseCLIPFeatureExtractor, ChineseCLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_chinese_clip import ( CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, ChineseCLIPModel, ChineseCLIPPreTrainedModel, ChineseCLIPTextModel, ChineseCLIPVisionModel, ) else: import sys A__: str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
276
1
'''simple docstring''' from collections import defaultdict from typing import Optional from ..image_utils import load_image from ..utils import ( add_end_docstrings, is_torch_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING A__: str = logging.get_logger(__name__) @add_end_docstrings(UpperCAmelCase__ ) class A__ ( UpperCAmelCase__ ): def __init__( self :Tuple , **SCREAMING_SNAKE_CASE :Optional[int] ) -> List[str]: '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE ) requires_backends(self , """vision""" ) requires_backends(self , """torch""" ) if self.framework != "pt": raise ValueError(f"The {self.__class__} is only available in PyTorch." ) self.check_model_type(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Any , **SCREAMING_SNAKE_CASE :Tuple ) -> Dict: '''simple docstring''' _a : int ={} _a : Optional[int] ={} _a : Union[str, Any] ={} # preprocess args if "points_per_batch" in kwargs: _a : Union[str, Any] =kwargs["""points_per_batch"""] if "points_per_crop" in kwargs: _a : Tuple =kwargs["""points_per_crop"""] if "crops_n_layers" in kwargs: _a : Any =kwargs["""crops_n_layers"""] if "crop_overlap_ratio" in kwargs: _a : Optional[Any] =kwargs["""crop_overlap_ratio"""] if "crop_n_points_downscale_factor" in kwargs: _a : Dict =kwargs["""crop_n_points_downscale_factor"""] # postprocess args if "pred_iou_thresh" in kwargs: _a : List[Any] =kwargs["""pred_iou_thresh"""] if "stability_score_offset" in kwargs: _a : Tuple =kwargs["""stability_score_offset"""] if "mask_threshold" in kwargs: _a : List[str] =kwargs["""mask_threshold"""] if "stability_score_thresh" in kwargs: _a : Optional[Any] =kwargs["""stability_score_thresh"""] if "crops_nms_thresh" in kwargs: _a : List[Any] =kwargs["""crops_nms_thresh"""] if "output_rle_mask" in kwargs: _a : int =kwargs["""output_rle_mask"""] if "output_bboxes_mask" in kwargs: _a : Optional[Any] =kwargs["""output_bboxes_mask"""] return preprocess_kwargs, forward_params, postprocess_kwargs def __call__( self :Union[str, Any] , SCREAMING_SNAKE_CASE :Union[str, Any] , *SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :List[Any]=None , SCREAMING_SNAKE_CASE :str=None , **SCREAMING_SNAKE_CASE :List[Any] ) -> int: '''simple docstring''' return super().__call__(SCREAMING_SNAKE_CASE , *SCREAMING_SNAKE_CASE , num_workers=SCREAMING_SNAKE_CASE , batch_size=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :int , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Any=6_4 , SCREAMING_SNAKE_CASE :int = 0 , SCREAMING_SNAKE_CASE :float = 5_1_2 / 1_5_0_0 , SCREAMING_SNAKE_CASE :Optional[int] = 3_2 , SCREAMING_SNAKE_CASE :Optional[int] = 1 , ) -> Any: '''simple docstring''' _a : Union[str, Any] =load_image(SCREAMING_SNAKE_CASE ) _a : List[str] =self.image_processor.size["""longest_edge"""] _a , _a , _a , _a : int =self.image_processor.generate_crop_boxes( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) _a : Any =self.image_processor(images=SCREAMING_SNAKE_CASE , return_tensors="""pt""" ) with self.device_placement(): if self.framework == "pt": _a : Dict =self.get_inference_context() with inference_context(): _a : Union[str, Any] =self._ensure_tensor_on_device(SCREAMING_SNAKE_CASE , device=self.device ) _a : Optional[Any] =self.model.get_image_embeddings(model_inputs.pop("""pixel_values""" ) ) _a : Any =image_embeddings _a : Dict =grid_points.shape[1] _a : Optional[Any] =points_per_batch if points_per_batch is not None else n_points if points_per_batch <= 0: raise ValueError( """Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. """ """To return all points at once, set points_per_batch to None""" ) for i in range(0 , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): _a : Optional[int] =grid_points[:, i : i + points_per_batch, :, :] _a : str =input_labels[:, i : i + points_per_batch] _a : str =i == n_points - points_per_batch yield { "input_points": batched_points, "input_labels": labels, "input_boxes": crop_boxes, "is_last": is_last, **model_inputs, } def __UpperCAmelCase ( self :int , SCREAMING_SNAKE_CASE :List[Any] , SCREAMING_SNAKE_CASE :Dict=0.88 , SCREAMING_SNAKE_CASE :Optional[Any]=0.95 , SCREAMING_SNAKE_CASE :Tuple=0 , SCREAMING_SNAKE_CASE :Optional[int]=1 , ) -> Optional[Any]: '''simple docstring''' _a : List[Any] =model_inputs.pop("""input_boxes""" ) _a : Tuple =model_inputs.pop("""is_last""" ) _a : Any =model_inputs.pop("""original_sizes""" ).tolist() _a : Optional[Any] =model_inputs.pop("""reshaped_input_sizes""" ).tolist() _a : Optional[Any] =self.model(**SCREAMING_SNAKE_CASE ) # post processing happens here in order to avoid CPU GPU copies of ALL the masks _a : Dict =model_outputs["""pred_masks"""] _a : Tuple =self.image_processor.post_process_masks( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , binarize=SCREAMING_SNAKE_CASE ) _a : Any =model_outputs["""iou_scores"""] _a , _a , _a : int =self.image_processor.filter_masks( masks[0] , iou_scores[0] , original_sizes[0] , input_boxes[0] , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , ) return { "masks": masks, "is_last": is_last, "boxes": boxes, "iou_scores": iou_scores, } def __UpperCAmelCase ( self :Tuple , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :Optional[int]=False , SCREAMING_SNAKE_CASE :str=False , SCREAMING_SNAKE_CASE :str=0.7 , ) -> Dict: '''simple docstring''' _a : str =[] _a : List[Any] =[] _a : List[str] =[] for model_output in model_outputs: all_scores.append(model_output.pop("""iou_scores""" ) ) all_masks.extend(model_output.pop("""masks""" ) ) all_boxes.append(model_output.pop("""boxes""" ) ) _a : Dict =torch.cat(SCREAMING_SNAKE_CASE ) _a : Optional[Any] =torch.cat(SCREAMING_SNAKE_CASE ) _a , _a , _a , _a : Any =self.image_processor.post_process_for_mask_generation( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) _a : Dict =defaultdict(SCREAMING_SNAKE_CASE ) for output in model_outputs: for k, v in output.items(): extra[k].append(SCREAMING_SNAKE_CASE ) _a : Optional[Any] ={} if output_rle_mask: _a : Union[str, Any] =rle_mask if output_bboxes_mask: _a : Optional[int] =bounding_boxes return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
276
'''simple docstring''' class A__ : def __init__( self :List[Any] ) -> None: '''simple docstring''' _a : dict[str, TrieNode] ={} # Mapping from char to TrieNode _a : List[str] =False def __UpperCAmelCase ( self :Tuple , SCREAMING_SNAKE_CASE :list[str] ) -> None: '''simple docstring''' for word in words: self.insert(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :str ) -> None: '''simple docstring''' _a : str =self for char in word: if char not in curr.nodes: _a : Dict =TrieNode() _a : List[Any] =curr.nodes[char] _a : int =True def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :str ) -> bool: '''simple docstring''' _a : int =self for char in word: if char not in curr.nodes: return False _a : List[Any] =curr.nodes[char] return curr.is_leaf def __UpperCAmelCase ( self :Dict , SCREAMING_SNAKE_CASE :str ) -> None: '''simple docstring''' def _delete(SCREAMING_SNAKE_CASE :TrieNode , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :int ) -> bool: if index == len(SCREAMING_SNAKE_CASE ): # If word does not exist if not curr.is_leaf: return False _a : Any =False return len(curr.nodes ) == 0 _a : int =word[index] _a : int =curr.nodes.get(SCREAMING_SNAKE_CASE ) # If char not in current trie node if not char_node: return False # Flag to check if node can be deleted _a : List[Any] =_delete(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , index + 1 ) if delete_curr: del curr.nodes[char] return len(curr.nodes ) == 0 return delete_curr _delete(self , SCREAMING_SNAKE_CASE , 0 ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : TrieNode ,_UpperCAmelCase : str ) -> None: if node.is_leaf: print(_UpperCAmelCase ,end=""" """ ) for key, value in node.nodes.items(): print_words(_UpperCAmelCase ,word + key ) def SCREAMING_SNAKE_CASE_ ( ) -> bool: _a : List[str] ="""banana bananas bandana band apple all beast""".split() _a : List[Any] =TrieNode() root.insert_many(_UpperCAmelCase ) # print_words(root, "") assert all(root.find(_UpperCAmelCase ) for word in words ) assert root.find("""banana""" ) assert not root.find("""bandanas""" ) assert not root.find("""apps""" ) assert root.find("""apple""" ) assert root.find("""all""" ) root.delete("""all""" ) assert not root.find("""all""" ) root.delete("""banana""" ) assert not root.find("""banana""" ) assert root.find("""bananas""" ) return True def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : bool ) -> None: print(str(_UpperCAmelCase ) ,"""works!""" if passes else """doesn't work :(""" ) def SCREAMING_SNAKE_CASE_ ( ) -> None: assert test_trie() def SCREAMING_SNAKE_CASE_ ( ) -> None: print_results("""Testing trie functionality""" ,test_trie() ) if __name__ == "__main__": main()
276
1
'''simple docstring''' import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( UniSpeechConfig, UniSpeechForCTC, UniSpeechForPreTraining, WavaVecaFeatureExtractor, WavaVecaPhonemeCTCTokenizer, WavaVecaProcessor, logging, ) logging.set_verbosity_info() A__: str = logging.get_logger(__name__) A__: Union[str, Any] = { '''post_extract_proj''': '''feature_projection.projection''', '''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''', '''self_attn.k_proj''': '''encoder.layers.*.attention.k_proj''', '''self_attn.v_proj''': '''encoder.layers.*.attention.v_proj''', '''self_attn.q_proj''': '''encoder.layers.*.attention.q_proj''', '''self_attn.out_proj''': '''encoder.layers.*.attention.out_proj''', '''self_attn_layer_norm''': '''encoder.layers.*.layer_norm''', '''fc1''': '''encoder.layers.*.feed_forward.intermediate_dense''', '''fc2''': '''encoder.layers.*.feed_forward.output_dense''', '''final_layer_norm''': '''encoder.layers.*.final_layer_norm''', '''encoder.layer_norm''': '''encoder.layer_norm''', '''w2v_model.layer_norm''': '''feature_projection.layer_norm''', '''quantizer.weight_proj''': '''quantizer.weight_proj''', '''quantizer.vars''': '''quantizer.codevectors''', '''project_q''': '''project_q''', '''final_proj''': '''project_hid''', '''w2v_encoder.proj''': '''ctc_proj''', '''mask_emb''': '''masked_spec_embed''', } A__: Tuple = [ '''ctc_proj''', '''quantizer.weight_proj''', '''quantizer.codevectors''', '''project_q''', '''project_hid''', ] def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[Any] ,_UpperCAmelCase : Dict ,_UpperCAmelCase : List[str] ,_UpperCAmelCase : Optional[int] ,_UpperCAmelCase : str ,_UpperCAmelCase : Tuple ) -> List[str]: for attribute in key.split(""".""" ): if is_finetuned: if attribute in ["quantizer", "project_q", "project_hid"]: # those layers are only relevant for pretraining and should be dropped return if attribute == "ctc_proj": # we should rename `ctc_proj` to `lm_head` for fine-tuned phoneme models _a : Tuple ="""lm_head""" _a : Optional[Any] =getattr(_UpperCAmelCase ,_UpperCAmelCase ) if weight_type is not None: _a : Dict =getattr(_UpperCAmelCase ,_UpperCAmelCase ).shape else: _a : Optional[Any] =hf_pointer.shape assert hf_shape == value.shape, ( F"Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be" F" {value.shape} for {full_name}" ) if weight_type == "weight": _a : Dict =value elif weight_type == "weight_g": _a : Union[str, Any] =value elif weight_type == "weight_v": _a : Tuple =value elif weight_type == "bias": _a : int =value else: _a : List[Any] =value logger.info(F"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}." ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Any ,_UpperCAmelCase : Optional[int] ,_UpperCAmelCase : List[str] ) -> Dict: _a : int =[] _a : Tuple =fairseq_model.state_dict() _a : str =hf_model.unispeech.feature_extractor for name, value in fairseq_dict.items(): _a : Dict =False if "conv_layers" in name: load_conv_layer( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,hf_model.config.feat_extract_norm == """group""" ,) _a : List[str] =True else: for key, mapped_key in MAPPING.items(): _a : List[Any] ="""unispeech.""" + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]: _a : Dict =True if "*" in mapped_key: _a : Optional[int] =name.split(_UpperCAmelCase )[0].split(""".""" )[-2] _a : Any =mapped_key.replace("""*""" ,_UpperCAmelCase ) if "weight_g" in name: _a : Tuple ="""weight_g""" elif "weight_v" in name: _a : int ="""weight_v""" elif "bias" in name: _a : Any ="""bias""" elif "weight" in name: # TODO: don't match quantizer.weight_proj _a : Union[str, Any] ="""weight""" else: _a : Optional[int] =None set_recursively(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) continue if not is_used: unused_weights.append(_UpperCAmelCase ) logger.warning(F"Unused weights: {unused_weights}" ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : Tuple ) -> Optional[Any]: _a : Optional[int] =full_name.split("""conv_layers.""" )[-1] _a : int =name.split(""".""" ) _a : Optional[Any] =int(items[0] ) _a : Optional[Any] =int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F"{full_name} has size {value.shape}, but" F" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found." ) _a : Dict =value logger.info(F"Feat extract conv layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( F"{full_name} has size {value.shape}, but" F" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found." ) _a : List[str] =value logger.info(F"Feat extract conv layer {layer_id} was initialized from {full_name}." ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F"{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was" " found." ) _a : Any =value logger.info(F"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F"{full_name} has size {value.shape}, but" F" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found." ) _a : Optional[int] =value logger.info(F"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) else: unused_weights.append(_UpperCAmelCase ) @torch.no_grad() def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Any ,_UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : List[str]=None ,_UpperCAmelCase : Tuple=None ,_UpperCAmelCase : Optional[Any]=True ) -> str: if config_path is not None: _a : List[Any] =UniSpeechConfig.from_pretrained(_UpperCAmelCase ) else: _a : str =UniSpeechConfig() if is_finetuned: if dict_path: _a : Union[str, Any] =Dictionary.load_from_json(_UpperCAmelCase ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq _a : int =target_dict.pad_index _a : int =target_dict.bos_index _a : int =target_dict.eos_index _a : List[str] =len(target_dict.symbols ) _a : List[str] =os.path.join(_UpperCAmelCase ,"""vocab.json""" ) if not os.path.isdir(_UpperCAmelCase ): logger.error("""--pytorch_dump_folder_path ({}) should be a directory""".format(_UpperCAmelCase ) ) return os.makedirs(_UpperCAmelCase ,exist_ok=_UpperCAmelCase ) _a : str =target_dict.indices # fairseq has the <pad> and <s> switched _a : Optional[Any] =42 _a : Dict =43 with open(_UpperCAmelCase ,"""w""" ,encoding="""utf-8""" ) as vocab_handle: json.dump(_UpperCAmelCase ,_UpperCAmelCase ) _a : List[Any] =WavaVecaPhonemeCTCTokenizer( _UpperCAmelCase ,unk_token=target_dict.unk_word ,pad_token=target_dict.pad_word ,bos_token=target_dict.bos_word ,eos_token=target_dict.eos_word ,word_delimiter_token="""|""" ,do_lower_case=_UpperCAmelCase ,) _a : Tuple =True if config.feat_extract_norm == """layer""" else False _a : Dict =WavaVecaFeatureExtractor( feature_size=1 ,sampling_rate=16000 ,padding_value=0 ,do_normalize=_UpperCAmelCase ,return_attention_mask=_UpperCAmelCase ,) _a : List[Any] =WavaVecaProcessor(feature_extractor=_UpperCAmelCase ,tokenizer=_UpperCAmelCase ) processor.save_pretrained(_UpperCAmelCase ) _a : List[Any] =UniSpeechForCTC(_UpperCAmelCase ) else: _a : List[str] =UniSpeechForPreTraining(_UpperCAmelCase ) if is_finetuned: _a , _a , _a : List[str] =fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] ,arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] ), """w2v_path""": checkpoint_path} ) else: _a , _a , _a : int =fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ) _a : Optional[int] =model[0].eval() recursively_load_weights(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) hf_unispeech.save_pretrained(_UpperCAmelCase ) if __name__ == "__main__": A__: Dict = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--dict_path''', default=None, type=str, help='''Path to dict of fine-tuned model''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument( '''--not_finetuned''', action='''store_true''', help='''Whether the model to convert is a fine-tuned model or not''' ) A__: Optional[int] = parser.parse_args() convert_unispeech_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
276
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available A__: str = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Tuple = ['''GPTSw3Tokenizer'''] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_swa import GPTSwaTokenizer else: import sys A__: str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
276
1
'''simple docstring''' from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .modeling_utils import ModelMixin from .vae import Decoder, DecoderOutput, Encoder, VectorQuantizer @dataclass class A__ ( UpperCAmelCase__ ): __UpperCamelCase : torch.FloatTensor class A__ ( UpperCAmelCase__ , UpperCAmelCase__ ): @register_to_config def __init__( self :Optional[Any] , SCREAMING_SNAKE_CASE :int = 3 , SCREAMING_SNAKE_CASE :int = 3 , SCREAMING_SNAKE_CASE :Tuple[str] = ("DownEncoderBlock2D",) , SCREAMING_SNAKE_CASE :Tuple[str] = ("UpDecoderBlock2D",) , SCREAMING_SNAKE_CASE :Tuple[int] = (6_4,) , SCREAMING_SNAKE_CASE :int = 1 , SCREAMING_SNAKE_CASE :str = "silu" , SCREAMING_SNAKE_CASE :int = 3 , SCREAMING_SNAKE_CASE :int = 3_2 , SCREAMING_SNAKE_CASE :int = 2_5_6 , SCREAMING_SNAKE_CASE :int = 3_2 , SCREAMING_SNAKE_CASE :Optional[int] = None , SCREAMING_SNAKE_CASE :float = 0.18_215 , SCREAMING_SNAKE_CASE :str = "group" , ) -> Optional[int]: '''simple docstring''' super().__init__() # pass init params to Encoder _a : Union[str, Any] =Encoder( in_channels=SCREAMING_SNAKE_CASE , out_channels=SCREAMING_SNAKE_CASE , down_block_types=SCREAMING_SNAKE_CASE , block_out_channels=SCREAMING_SNAKE_CASE , layers_per_block=SCREAMING_SNAKE_CASE , act_fn=SCREAMING_SNAKE_CASE , norm_num_groups=SCREAMING_SNAKE_CASE , double_z=SCREAMING_SNAKE_CASE , ) _a : Optional[int] =vq_embed_dim if vq_embed_dim is not None else latent_channels _a : Optional[int] =nn.Convad(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , 1 ) _a : str =VectorQuantizer(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , beta=0.25 , remap=SCREAMING_SNAKE_CASE , sane_index_shape=SCREAMING_SNAKE_CASE ) _a : List[str] =nn.Convad(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , 1 ) # pass init params to Decoder _a : List[str] =Decoder( in_channels=SCREAMING_SNAKE_CASE , out_channels=SCREAMING_SNAKE_CASE , up_block_types=SCREAMING_SNAKE_CASE , block_out_channels=SCREAMING_SNAKE_CASE , layers_per_block=SCREAMING_SNAKE_CASE , act_fn=SCREAMING_SNAKE_CASE , norm_num_groups=SCREAMING_SNAKE_CASE , norm_type=SCREAMING_SNAKE_CASE , ) @apply_forward_hook def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :torch.FloatTensor , SCREAMING_SNAKE_CASE :bool = True ) -> VQEncoderOutput: '''simple docstring''' _a : Optional[int] =self.encoder(SCREAMING_SNAKE_CASE ) _a : int =self.quant_conv(SCREAMING_SNAKE_CASE ) if not return_dict: return (h,) return VQEncoderOutput(latents=SCREAMING_SNAKE_CASE ) @apply_forward_hook def __UpperCAmelCase ( self :List[Any] , SCREAMING_SNAKE_CASE :torch.FloatTensor , SCREAMING_SNAKE_CASE :bool = False , SCREAMING_SNAKE_CASE :bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: '''simple docstring''' # also go through quantization layer if not force_not_quantize: _a , _a , _a : Tuple =self.quantize(SCREAMING_SNAKE_CASE ) else: _a : str =h _a : Dict =self.post_quant_conv(SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =self.decoder(SCREAMING_SNAKE_CASE , quant if self.config.norm_type == """spatial""" else None ) if not return_dict: return (dec,) return DecoderOutput(sample=SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :torch.FloatTensor , SCREAMING_SNAKE_CASE :bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: '''simple docstring''' _a : Tuple =sample _a : int =self.encode(SCREAMING_SNAKE_CASE ).latents _a : List[Any] =self.decode(SCREAMING_SNAKE_CASE ).sample if not return_dict: return (dec,) return DecoderOutput(sample=SCREAMING_SNAKE_CASE )
276
'''simple docstring''' import importlib.metadata import warnings from copy import deepcopy from packaging import version from ..utils import logging from .import_utils import is_accelerate_available, is_bitsandbytes_available if is_bitsandbytes_available(): import bitsandbytes as bnb import torch import torch.nn as nn from ..pytorch_utils import ConvaD if is_accelerate_available(): from accelerate import init_empty_weights from accelerate.utils import find_tied_parameters A__: str = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[Any] ,_UpperCAmelCase : List[str] ,_UpperCAmelCase : int ,_UpperCAmelCase : int=None ,_UpperCAmelCase : Optional[Any]=None ) -> Optional[Any]: # Recurse if needed if "." in tensor_name: _a : Union[str, Any] =tensor_name.split(""".""" ) for split in splits[:-1]: _a : Optional[Any] =getattr(_UpperCAmelCase ,_UpperCAmelCase ) if new_module is None: raise ValueError(F"{module} has no attribute {split}." ) _a : Optional[int] =new_module _a : Optional[int] =splits[-1] if tensor_name not in module._parameters and tensor_name not in module._buffers: raise ValueError(F"{module} does not have a parameter or a buffer named {tensor_name}." ) _a : Optional[Any] =tensor_name in module._buffers _a : str =getattr(_UpperCAmelCase ,_UpperCAmelCase ) if old_value.device == torch.device("""meta""" ) and device not in ["meta", torch.device("""meta""" )] and value is None: raise ValueError(F"{tensor_name} is on the meta device, we need a `value` to put in on {device}." ) _a : int =False _a : Tuple =False if is_buffer or not is_bitsandbytes_available(): _a : str =False _a : Optional[Any] =False else: _a : int =hasattr(bnb.nn ,"""Params4bit""" ) and isinstance(module._parameters[tensor_name] ,bnb.nn.Paramsabit ) _a : int =isinstance(module._parameters[tensor_name] ,bnb.nn.IntaParams ) if is_abit or is_abit: _a : Any =module._parameters[tensor_name] if param.device.type != "cuda": if value is None: _a : int =old_value.to(_UpperCAmelCase ) elif isinstance(_UpperCAmelCase ,torch.Tensor ): _a : str =value.to("""cpu""" ) if value.dtype == torch.inta: _a : int =version.parse(importlib.metadata.version("""bitsandbytes""" ) ) > version.parse( """0.37.2""" ) if not is_abit_serializable: raise ValueError( """Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. """ """Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`.""" ) else: _a : Dict =torch.tensor(_UpperCAmelCase ,device="""cpu""" ) # Support models using `Conv1D` in place of `nn.Linear` (e.g. gpt2) by transposing the weight matrix prior to quantization. # Since weights are saved in the correct "orientation", we skip transposing when loading. if issubclass(module.source_cls ,_UpperCAmelCase ) and fpaa_statistics is None: _a : int =new_value.T _a : Any =old_value.__dict__ if is_abit: _a : Any =bnb.nn.IntaParams(_UpperCAmelCase ,requires_grad=_UpperCAmelCase ,**_UpperCAmelCase ).to(_UpperCAmelCase ) elif is_abit: _a : Union[str, Any] =bnb.nn.Paramsabit(_UpperCAmelCase ,requires_grad=_UpperCAmelCase ,**_UpperCAmelCase ).to(_UpperCAmelCase ) _a : List[Any] =new_value if fpaa_statistics is not None: setattr(module.weight ,"""SCB""" ,fpaa_statistics.to(_UpperCAmelCase ) ) else: if value is None: _a : str =old_value.to(_UpperCAmelCase ) elif isinstance(_UpperCAmelCase ,torch.Tensor ): _a : Any =value.to(_UpperCAmelCase ) else: _a : str =torch.tensor(_UpperCAmelCase ,device=_UpperCAmelCase ) if is_buffer: _a : Optional[int] =new_value else: _a : Optional[Any] =nn.Parameter(_UpperCAmelCase ,requires_grad=old_value.requires_grad ) _a : Tuple =new_value def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : Union[str, Any]=None ,_UpperCAmelCase : List[Any]=None ,_UpperCAmelCase : str=None ,_UpperCAmelCase : Union[str, Any]=False ) -> Dict: for name, module in model.named_children(): if current_key_name is None: _a : Optional[int] =[] current_key_name.append(_UpperCAmelCase ) if (isinstance(_UpperCAmelCase ,nn.Linear ) or isinstance(_UpperCAmelCase ,_UpperCAmelCase )) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` if not any(key in """.""".join(_UpperCAmelCase ) for key in modules_to_not_convert ): with init_empty_weights(): if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): _a , _a : int =module.weight.shape else: _a : List[str] =module.in_features _a : Tuple =module.out_features if quantization_config.quantization_method() == "llm_int8": _a : Optional[Any] =bnb.nn.LinearabitLt( _UpperCAmelCase ,_UpperCAmelCase ,module.bias is not None ,has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight ,threshold=quantization_config.llm_inta_threshold ,) _a : Optional[Any] =True else: if ( quantization_config.llm_inta_skip_modules is not None and name in quantization_config.llm_inta_skip_modules ): pass else: _a : Dict =bnb.nn.Linearabit( _UpperCAmelCase ,_UpperCAmelCase ,module.bias is not None ,quantization_config.bnb_abit_compute_dtype ,compress_statistics=quantization_config.bnb_abit_use_double_quant ,quant_type=quantization_config.bnb_abit_quant_type ,) _a : List[Any] =True # Store the module class in case we need to transpose the weight later _a : int =type(_UpperCAmelCase ) # Force requires grad to False to avoid unexpected errors model._modules[name].requires_grad_(_UpperCAmelCase ) if len(list(module.children() ) ) > 0: _a , _a : List[Any] =_replace_with_bnb_linear( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,has_been_replaced=_UpperCAmelCase ,) # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : int=None ,_UpperCAmelCase : Union[str, Any]=None ,_UpperCAmelCase : Any=None ) -> Tuple: _a : Dict =["""lm_head"""] if modules_to_not_convert is None else modules_to_not_convert _a , _a : List[Any] =_replace_with_bnb_linear( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) if not has_been_replaced: logger.warning( """You are loading your model in 8bit or 4bit but no linear modules were found in your model.""" """ Please double check your model architecture, or submit an issue on github if you think this is""" """ a bug.""" ) return model def SCREAMING_SNAKE_CASE_ ( *_UpperCAmelCase : Any ,**_UpperCAmelCase : Any ) -> str: warnings.warn( """`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead""" ,_UpperCAmelCase ,) return replace_with_bnb_linear(*_UpperCAmelCase ,**_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( *_UpperCAmelCase : str ,**_UpperCAmelCase : Optional[int] ) -> Optional[int]: warnings.warn( """`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead""" ,_UpperCAmelCase ,) return set_module_quantized_tensor_to_device(*_UpperCAmelCase ,**_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ) -> Union[str, Any]: _a : Any =deepcopy(_UpperCAmelCase ) # this has 0 cost since it is done inside `init_empty_weights` context manager` tied_model.tie_weights() _a : List[Any] =find_tied_parameters(_UpperCAmelCase ) # For compatibility with Accelerate < 0.18 if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): _a : str =sum(list(tied_params.values() ) ,[] ) + list(tied_params.keys() ) else: _a : Optional[int] =sum(_UpperCAmelCase ,[] ) _a : List[Any] =len(_UpperCAmelCase ) > 0 # Check if it is a base model _a : Tuple =not hasattr(_UpperCAmelCase ,model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head _a : List[Any] =list(model.named_children() ) _a : Dict =[list_modules[-1][0]] # add last module together with tied weights _a : List[str] =set(_UpperCAmelCase ) - set(_UpperCAmelCase ) _a : str =list(set(_UpperCAmelCase ) ) + list(_UpperCAmelCase ) # remove ".weight" from the keys _a : List[Any] =[""".weight""", """.bias"""] _a : Any =[] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: _a : Any =name.replace(_UpperCAmelCase ,"""""" ) filtered_module_names.append(_UpperCAmelCase ) return filtered_module_names
276
1
'''simple docstring''' import argparse import re from flax.traverse_util import flatten_dict, unflatten_dict from tax import checkpoints from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorch_model from transformers.utils import logging logging.set_verbosity_info() # should not include what is already done by the `from_pt` argument A__: int = { '''/attention/''': '''/0/SelfAttention/''', '''/self_attention/''': '''/0/SelfAttention/''', '''/encoder_decoder_attention/''': '''/1/EncDecAttention/''', '''value''': '''v''', '''query''': '''q''', '''key''': '''k''', '''out''': '''o''', '''pre_self_attention_layer_norm''': '''0/layer_norm''', '''pre_cross_attention_layer_norm''': '''1/layer_norm''', '''pre_attention_layer_norm''': '''0/layer_norm''', # previously 1, but seems wrong '''token_embedder''': '''shared''', '''encoder_norm''': '''final_layer_norm''', '''decoder_norm''': '''final_layer_norm''', '''relpos_bias/rel_embedding''': '''block/0/layer/0/SelfAttention/relative_attention_bias/weight''', '''router/router_weights/w/''': '''router/classifier/''', '''roer/roer_weights/w/''': '''router/classifier/''', '''logits_dense''': '''lm_head''', } def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Tuple ) -> List[Any]: # 1. in HF T5, we have block.{x}.layer.{y}. which corresponds to layer.{x} in # the original model _a : Any =list(s_dict.keys() ) for key in keys: _a : int =R""".*/layers_(\d+)""" _a : Union[str, Any] =key if re.match(_UpperCAmelCase ,_UpperCAmelCase ): _a : str =re.sub(R"""layers_(\d+)""" ,R"""block/\1/layer""" ,_UpperCAmelCase ) _a : str =R"""(encoder|decoder)\/""" if re.match(_UpperCAmelCase ,_UpperCAmelCase ): _a : int =re.match(_UpperCAmelCase ,_UpperCAmelCase ).groups() if groups[0] == "encoder": _a : List[str] =re.sub(R"""/mlp/""" ,R"""/1/mlp/""" ,_UpperCAmelCase ) _a : Union[str, Any] =re.sub(R"""/pre_mlp_layer_norm/""" ,R"""/1/layer_norm/""" ,_UpperCAmelCase ) elif groups[0] == "decoder": _a : Dict =re.sub(R"""/mlp/""" ,R"""/2/mlp/""" ,_UpperCAmelCase ) _a : List[str] =re.sub(R"""/pre_mlp_layer_norm/""" ,R"""/2/layer_norm/""" ,_UpperCAmelCase ) # 2. Convert other classic mappings for old_key, temp_key in MOE_LAYER_NAME_MAPPING.items(): if old_key in new_key: _a : int =new_key.replace(_UpperCAmelCase ,_UpperCAmelCase ) print(F"{key} -> {new_key}" ) _a : List[Any] =s_dict.pop(_UpperCAmelCase ) if "encoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight" in s_dict: _a : Optional[int] =s_dict[ """encoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight""" ].T if "decoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight" in s_dict: _a : List[Any] =s_dict[ """decoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight""" ].T # 3. Take extra care of the EXPERTS layer for key in list(s_dict.keys() ): if "expert" in key: _a : Optional[int] =s_dict[key].shape[0] _a : Optional[int] =s_dict[key] for idx in range(_UpperCAmelCase ): _a : Dict =expert_weihts[idx] print(F"{key} -> {key.replace('expert/' ,'nested fstring' )}" ) s_dict.pop(_UpperCAmelCase ) return s_dict A__: Any = { '''NUM_ENCODER_LAYERS''': '''num_layers''', '''NUM_DECODER_LAYERS''': '''num_decoder_layers''', '''NUM_HEADS''': '''num_heads''', '''HEAD_DIM''': '''d_kv''', '''EMBED_DIM''': '''d_model''', '''MLP_DIM''': '''d_ff''', '''NUM_SELECTED_EXPERTS''': '''num_selected_experts''', '''NUM_ENCODER_SPARSE_LAYERS''': '''num_sparse_encoder_layers''', '''NUM_DECODER_SPARSE_LAYERS''': '''num_sparse_decoder_layers''', '''dense.MlpBlock.activations''': '''feed_forward_proj''', } def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : int ) -> str: # Convert a google style config to the hugging face fromat import regex as re with open(_UpperCAmelCase ,"""r""" ) as f: _a : Dict =f.read() _a : Union[str, Any] =re.findall(R"""(.*) = ([0-9.]*)""" ,_UpperCAmelCase ) _a : Optional[int] ={} for param, value in regex_match: if param in GIN_TO_CONFIG_MAPPING and value != "": _a : Dict =float(_UpperCAmelCase ) if """.""" in value else int(_UpperCAmelCase ) _a : Tuple =re.findall(R"""(.*activations) = \(\'(.*)\',\)""" ,_UpperCAmelCase )[0] _a : List[str] =str(activation[1] ) _a : Any =num_experts _a : Dict =SwitchTransformersConfig(**_UpperCAmelCase ) return config def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Union[str, Any]=None ,_UpperCAmelCase : List[Any]="./" ,_UpperCAmelCase : Optional[Any]=8 ) -> List[str]: # Initialise PyTorch model print(F"Loading flax weights from : {flax_checkpoint_path}" ) _a : Optional[Any] =checkpoints.load_tax_checkpoint(_UpperCAmelCase ) if gin_file is not None: _a : List[Any] =convert_gin_to_config(_UpperCAmelCase ,_UpperCAmelCase ) else: _a : int =SwitchTransformersConfig.from_pretrained(_UpperCAmelCase ) _a : List[str] =SwitchTransformersForConditionalGeneration(_UpperCAmelCase ) _a : List[str] =flax_params["""target"""] _a : Union[str, Any] =flatten_dict(_UpperCAmelCase ,sep="""/""" ) _a : str =rename_keys(_UpperCAmelCase ) _a : List[Any] =unflatten_dict(_UpperCAmelCase ,sep="""/""" ) # Load the flax params in the PT model load_flax_weights_in_pytorch_model(_UpperCAmelCase ,_UpperCAmelCase ) print(F"Save PyTorch model to {pytorch_dump_path}" ) pt_model.save_pretrained(_UpperCAmelCase ) if __name__ == "__main__": A__: Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--switch_t5x_checkpoint_path''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained SwitchTransformers model. \nThis specifies the''' ''' model architecture. If not provided, a `gin_file` has to be provided.''' ), ) parser.add_argument( '''--gin_file''', default=None, type=str, required=False, help='''Path to the gin config file. If not provided, a `config_file` has to be passed ''', ) parser.add_argument( '''--config_name''', default=None, type=str, required=False, help='''Config name of SwitchTransformers model.''' ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output pytorch model.''' ) parser.add_argument('''--num_experts''', default=8, type=int, required=False, help='''Number of experts''') A__: Optional[int] = parser.parse_args() convert_flax_checkpoint_to_pytorch( args.switch_tax_checkpoint_path, args.config_name, args.gin_file, args.pytorch_dump_folder_path, args.num_experts, )
276
'''simple docstring''' import logging import os from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union from filelock import FileLock from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available A__: int = logging.getLogger(__name__) @dataclass class A__ : __UpperCamelCase : str __UpperCamelCase : List[str] __UpperCamelCase : Optional[List[str]] @dataclass class A__ : __UpperCamelCase : List[int] __UpperCamelCase : List[int] __UpperCamelCase : Optional[List[int]] = None __UpperCamelCase : Optional[List[int]] = None class A__ ( UpperCAmelCase__ ): __UpperCamelCase : str = "train" __UpperCamelCase : Tuple = "dev" __UpperCamelCase : str = "test" class A__ : @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :Union[Split, str] ) -> List[InputExample]: '''simple docstring''' raise NotImplementedError @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :str ) -> List[str]: '''simple docstring''' raise NotImplementedError @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :List[InputExample] , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :PreTrainedTokenizer , SCREAMING_SNAKE_CASE :str=False , SCREAMING_SNAKE_CASE :Optional[Any]="[CLS]" , SCREAMING_SNAKE_CASE :Optional[int]=1 , SCREAMING_SNAKE_CASE :Any="[SEP]" , SCREAMING_SNAKE_CASE :List[Any]=False , SCREAMING_SNAKE_CASE :Union[str, Any]=False , SCREAMING_SNAKE_CASE :List[str]=0 , SCREAMING_SNAKE_CASE :str=0 , SCREAMING_SNAKE_CASE :Dict=-1_0_0 , SCREAMING_SNAKE_CASE :Optional[int]=0 , SCREAMING_SNAKE_CASE :Tuple=True , ) -> List[InputFeatures]: '''simple docstring''' _a : str ={label: i for i, label in enumerate(SCREAMING_SNAKE_CASE )} _a : Tuple =[] for ex_index, example in enumerate(SCREAMING_SNAKE_CASE ): if ex_index % 1_0_0_0_0 == 0: logger.info("""Writing example %d of %d""" , SCREAMING_SNAKE_CASE , len(SCREAMING_SNAKE_CASE ) ) _a : Optional[Any] =[] _a : List[Any] =[] for word, label in zip(example.words , example.labels ): _a : Optional[int] =tokenizer.tokenize(SCREAMING_SNAKE_CASE ) # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space. if len(SCREAMING_SNAKE_CASE ) > 0: tokens.extend(SCREAMING_SNAKE_CASE ) # Use the real label id for the first token of the word, and padding ids for the remaining tokens label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(SCREAMING_SNAKE_CASE ) - 1) ) # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa. _a : Optional[int] =tokenizer.num_special_tokens_to_add() if len(SCREAMING_SNAKE_CASE ) > max_seq_length - special_tokens_count: _a : List[Any] =tokens[: (max_seq_length - special_tokens_count)] _a : Tuple =label_ids[: (max_seq_length - special_tokens_count)] # The convention in BERT is: # (a) For sequence pairs: # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP] # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1 # (b) For single sequences: # tokens: [CLS] the dog is hairy . [SEP] # type_ids: 0 0 0 0 0 0 0 # # Where "type_ids" are used to indicate whether this is the first # sequence or the second sequence. The embedding vectors for `type=0` and # `type=1` were learned during pre-training and are added to the wordpiece # embedding vector (and position vector). This is not *strictly* necessary # since the [SEP] token unambiguously separates the sequences, but it makes # it easier for the model to learn the concept of sequences. # # For classification tasks, the first vector (corresponding to [CLS]) is # used as the "sentence vector". Note that this only makes sense because # the entire model is fine-tuned. tokens += [sep_token] label_ids += [pad_token_label_id] if sep_token_extra: # roberta uses an extra separator b/w pairs of sentences tokens += [sep_token] label_ids += [pad_token_label_id] _a : Dict =[sequence_a_segment_id] * len(SCREAMING_SNAKE_CASE ) if cls_token_at_end: tokens += [cls_token] label_ids += [pad_token_label_id] segment_ids += [cls_token_segment_id] else: _a : Any =[cls_token] + tokens _a : Dict =[pad_token_label_id] + label_ids _a : Union[str, Any] =[cls_token_segment_id] + segment_ids _a : List[str] =tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE ) # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. _a : Optional[int] =[1 if mask_padding_with_zero else 0] * len(SCREAMING_SNAKE_CASE ) # Zero-pad up to the sequence length. _a : Union[str, Any] =max_seq_length - len(SCREAMING_SNAKE_CASE ) if pad_on_left: _a : Optional[Any] =([pad_token] * padding_length) + input_ids _a : Optional[int] =([0 if mask_padding_with_zero else 1] * padding_length) + input_mask _a : Union[str, Any] =([pad_token_segment_id] * padding_length) + segment_ids _a : Dict =([pad_token_label_id] * padding_length) + label_ids else: input_ids += [pad_token] * padding_length input_mask += [0 if mask_padding_with_zero else 1] * padding_length segment_ids += [pad_token_segment_id] * padding_length label_ids += [pad_token_label_id] * padding_length assert len(SCREAMING_SNAKE_CASE ) == max_seq_length assert len(SCREAMING_SNAKE_CASE ) == max_seq_length assert len(SCREAMING_SNAKE_CASE ) == max_seq_length assert len(SCREAMING_SNAKE_CASE ) == max_seq_length if ex_index < 5: logger.info("""*** Example ***""" ) logger.info("""guid: %s""" , example.guid ) logger.info("""tokens: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in tokens] ) ) logger.info("""input_ids: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in input_ids] ) ) logger.info("""input_mask: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in input_mask] ) ) logger.info("""segment_ids: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in segment_ids] ) ) logger.info("""label_ids: %s""" , """ """.join([str(SCREAMING_SNAKE_CASE ) for x in label_ids] ) ) if "token_type_ids" not in tokenizer.model_input_names: _a : Tuple =None features.append( InputFeatures( input_ids=SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , token_type_ids=SCREAMING_SNAKE_CASE , label_ids=SCREAMING_SNAKE_CASE ) ) return features if is_torch_available(): import torch from torch import nn from torch.utils.data import Dataset class A__ ( UpperCAmelCase__ ): __UpperCamelCase : List[InputFeatures] __UpperCamelCase : int = nn.CrossEntropyLoss().ignore_index def __init__( self :Dict , SCREAMING_SNAKE_CASE :TokenClassificationTask , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :PreTrainedTokenizer , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Optional[int] = None , SCREAMING_SNAKE_CASE :int=False , SCREAMING_SNAKE_CASE :Split = Split.train , ) -> List[str]: '''simple docstring''' # Load data features from cache or dataset file _a : Optional[Any] =os.path.join( SCREAMING_SNAKE_CASE , """cached_{}_{}_{}""".format(mode.value , tokenizer.__class__.__name__ , str(SCREAMING_SNAKE_CASE ) ) , ) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. _a : List[str] =cached_features_file + """.lock""" with FileLock(SCREAMING_SNAKE_CASE ): if os.path.exists(SCREAMING_SNAKE_CASE ) and not overwrite_cache: logger.info(f"Loading features from cached file {cached_features_file}" ) _a : Any =torch.load(SCREAMING_SNAKE_CASE ) else: logger.info(f"Creating features from dataset file at {data_dir}" ) _a : Any =token_classification_task.read_examples_from_file(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # TODO clean up all this to leverage built-in features of tokenizers _a : List[str] =token_classification_task.convert_examples_to_features( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cls_token_at_end=bool(model_type in ["""xlnet"""] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ["""xlnet"""] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=SCREAMING_SNAKE_CASE , pad_on_left=bool(tokenizer.padding_side == """left""" ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info(f"Saving features into cached file {cached_features_file}" ) torch.save(self.features , SCREAMING_SNAKE_CASE ) def __len__( self :Optional[int] ) -> Union[str, Any]: '''simple docstring''' return len(self.features ) def __getitem__( self :Dict , SCREAMING_SNAKE_CASE :int ) -> InputFeatures: '''simple docstring''' return self.features[i] if is_tf_available(): import tensorflow as tf class A__ : __UpperCamelCase : List[InputFeatures] __UpperCamelCase : int = -100 def __init__( self :str , SCREAMING_SNAKE_CASE :TokenClassificationTask , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :PreTrainedTokenizer , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Optional[int] = None , SCREAMING_SNAKE_CASE :str=False , SCREAMING_SNAKE_CASE :Split = Split.train , ) -> Any: '''simple docstring''' _a : Tuple =token_classification_task.read_examples_from_file(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # TODO clean up all this to leverage built-in features of tokenizers _a : List[Any] =token_classification_task.convert_examples_to_features( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cls_token_at_end=bool(model_type in ["""xlnet"""] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ["""xlnet"""] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=SCREAMING_SNAKE_CASE , pad_on_left=bool(tokenizer.padding_side == """left""" ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) def gen(): for ex in self.features: if ex.token_type_ids is None: yield ( {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label_ids, ) else: yield ( { "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label_ids, ) if "token_type_ids" not in tokenizer.model_input_names: _a : Union[str, Any] =tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE , ({"""input_ids""": tf.intaa, """attention_mask""": tf.intaa}, tf.intaa) , ( {"""input_ids""": tf.TensorShape([None] ), """attention_mask""": tf.TensorShape([None] )}, tf.TensorShape([None] ), ) , ) else: _a : Union[str, Any] =tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE , ({"""input_ids""": tf.intaa, """attention_mask""": tf.intaa, """token_type_ids""": tf.intaa}, tf.intaa) , ( { """input_ids""": tf.TensorShape([None] ), """attention_mask""": tf.TensorShape([None] ), """token_type_ids""": tf.TensorShape([None] ), }, tf.TensorShape([None] ), ) , ) def __UpperCAmelCase ( self :Tuple ) -> Any: '''simple docstring''' _a : List[Any] =self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features ) ) ) return self.dataset def __len__( self :str ) -> Optional[int]: '''simple docstring''' return len(self.features ) def __getitem__( self :int , SCREAMING_SNAKE_CASE :str ) -> InputFeatures: '''simple docstring''' return self.features[i]
276
1
'''simple docstring''' from datetime import datetime import requests from bsa import BeautifulSoup if __name__ == "__main__": A__: Union[str, Any] = input('''Enter image url: ''').strip() print(F"Downloading image from {url} ...") A__: Tuple = BeautifulSoup(requests.get(url).content, '''html.parser''') # The image URL is in the content field of the first meta tag with property og:image A__: Union[str, Any] = soup.find('''meta''', {'''property''': '''og:image'''})['''content'''] A__: List[Any] = requests.get(image_url).content A__: List[str] = F"{datetime.now():%Y-%m-%d_%H:%M:%S}.jpg" with open(file_name, '''wb''') as fp: fp.write(image_data) print(F"Done. Image saved to disk as {file_name}.")
276
'''simple docstring''' from __future__ import annotations class A__ : def __init__( self :Union[str, Any] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :str ) -> Optional[int]: '''simple docstring''' _a , _a : List[str] =text, pattern _a , _a : Union[str, Any] =len(SCREAMING_SNAKE_CASE ), len(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Optional[int] , SCREAMING_SNAKE_CASE :str ) -> int: '''simple docstring''' for i in range(self.patLen - 1 , -1 , -1 ): if char == self.pattern[i]: return i return -1 def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :int ) -> int: '''simple docstring''' for i in range(self.patLen - 1 , -1 , -1 ): if self.pattern[i] != self.text[current_pos + i]: return current_pos + i return -1 def __UpperCAmelCase ( self :Union[str, Any] ) -> list[int]: '''simple docstring''' # searches pattern in text and returns index positions _a : Union[str, Any] =[] for i in range(self.textLen - self.patLen + 1 ): _a : Any =self.mismatch_in_text(SCREAMING_SNAKE_CASE ) if mismatch_index == -1: positions.append(SCREAMING_SNAKE_CASE ) else: _a : int =self.match_in_pattern(self.text[mismatch_index] ) _a : List[str] =( mismatch_index - match_index ) # shifting index lgtm [py/multiple-definition] return positions A__: Any = '''ABAABA''' A__: int = '''AB''' A__: Optional[int] = BoyerMooreSearch(text, pattern) A__: Optional[Any] = bms.bad_character_heuristic() if len(positions) == 0: print('''No match found''') else: print('''Pattern found in following positions: ''') print(positions)
276
1
'''simple docstring''' import warnings from ...utils import logging from .image_processing_clip import CLIPImageProcessor A__: Union[str, Any] = logging.get_logger(__name__) class A__ ( UpperCAmelCase__ ): def __init__( self :Optional[int] , *SCREAMING_SNAKE_CASE :int , **SCREAMING_SNAKE_CASE :str ) -> None: '''simple docstring''' warnings.warn( """The class CLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please""" """ use CLIPImageProcessor instead.""" , SCREAMING_SNAKE_CASE , ) super().__init__(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE )
276
'''simple docstring''' 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''' ) A__: Dict = None A__: Tuple = { '''7B''': 1_1008, '''13B''': 1_3824, '''30B''': 1_7920, '''65B''': 2_2016, '''70B''': 2_8672, } A__: Any = { '''7B''': 1, '''7Bf''': 1, '''13B''': 2, '''13Bf''': 2, '''30B''': 4, '''65B''': 8, '''70B''': 8, '''70Bf''': 8, } def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Optional[int]=1 ,_UpperCAmelCase : List[str]=256 ) -> Dict: return multiple_of * ((int(ffn_dim_multiplier * int(8 * n / 3 ) ) + multiple_of - 1) // multiple_of) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[Any] ) -> List[str]: with open(_UpperCAmelCase ,"""r""" ) as f: return json.load(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : Optional[Any] ) -> Tuple: with open(_UpperCAmelCase ,"""w""" ) as f: json.dump(_UpperCAmelCase ,_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : int ,_UpperCAmelCase : List[Any]=True ) -> Union[str, Any]: os.makedirs(_UpperCAmelCase ,exist_ok=_UpperCAmelCase ) _a : Union[str, Any] =os.path.join(_UpperCAmelCase ,"""tmp""" ) os.makedirs(_UpperCAmelCase ,exist_ok=_UpperCAmelCase ) _a : int =read_json(os.path.join(_UpperCAmelCase ,"""params.json""" ) ) _a : int =NUM_SHARDS[model_size] _a : Dict =params["""n_layers"""] _a : Union[str, Any] =params["""n_heads"""] _a : List[str] =n_heads // num_shards _a : int =params["""dim"""] _a : Union[str, Any] =dim // n_heads _a : int =1_0_0_0_0.0 _a : str =1.0 / (base ** (torch.arange(0 ,_UpperCAmelCase ,2 ).float() / dims_per_head)) if "n_kv_heads" in params: _a : str =params["""n_kv_heads"""] # for GQA / MQA _a : Optional[Any] =n_heads_per_shard // num_key_value_heads _a : Optional[int] =dim // num_key_value_heads else: # compatibility with other checkpoints _a : str =n_heads _a : Any =n_heads_per_shard _a : str =dim # permute for sliced rotary def permute(_UpperCAmelCase : Tuple ,_UpperCAmelCase : Optional[int]=n_heads ,_UpperCAmelCase : Optional[int]=dim ,_UpperCAmelCase : List[str]=dim ): return w.view(_UpperCAmelCase ,dima // n_heads // 2 ,2 ,_UpperCAmelCase ).transpose(1 ,2 ).reshape(_UpperCAmelCase ,_UpperCAmelCase ) 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.) _a : Any =torch.load(os.path.join(_UpperCAmelCase ,"""consolidated.00.pth""" ) ,map_location="""cpu""" ) else: # Sharded _a : List[Any] =[ torch.load(os.path.join(_UpperCAmelCase ,F"consolidated.{i:02d}.pth" ) ,map_location="""cpu""" ) for i in range(_UpperCAmelCase ) ] _a : Any =0 _a : Optional[int] ={"""weight_map""": {}} for layer_i in range(_UpperCAmelCase ): _a : List[str] =F"pytorch_model-{layer_i + 1}-of-{n_layers + 1}.bin" if model_size == "7B": # Unsharded _a : List[str] ={ 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. _a : Tuple ={ 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(), } _a : str =permute( torch.cat( [ loaded[i][F"layers.{layer_i}.attention.wq.weight"].view(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) for i in range(_UpperCAmelCase ) ] ,dim=0 ,).reshape(_UpperCAmelCase ,_UpperCAmelCase ) ) _a : Tuple =permute( torch.cat( [ loaded[i][F"layers.{layer_i}.attention.wk.weight"].view( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) for i in range(_UpperCAmelCase ) ] ,dim=0 ,).reshape(_UpperCAmelCase ,_UpperCAmelCase ) ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,) _a : Any =torch.cat( [ loaded[i][F"layers.{layer_i}.attention.wv.weight"].view( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) for i in range(_UpperCAmelCase ) ] ,dim=0 ,).reshape(_UpperCAmelCase ,_UpperCAmelCase ) _a : List[str] =torch.cat( [loaded[i][F"layers.{layer_i}.attention.wo.weight"] for i in range(_UpperCAmelCase )] ,dim=1 ) _a : Union[str, Any] =torch.cat( [loaded[i][F"layers.{layer_i}.feed_forward.w1.weight"] for i in range(_UpperCAmelCase )] ,dim=0 ) _a : Tuple =torch.cat( [loaded[i][F"layers.{layer_i}.feed_forward.w2.weight"] for i in range(_UpperCAmelCase )] ,dim=1 ) _a : Union[str, Any] =torch.cat( [loaded[i][F"layers.{layer_i}.feed_forward.w3.weight"] for i in range(_UpperCAmelCase )] ,dim=0 ) _a : str =inv_freq for k, v in state_dict.items(): _a : Any =filename param_count += v.numel() torch.save(_UpperCAmelCase ,os.path.join(_UpperCAmelCase ,_UpperCAmelCase ) ) _a : Union[str, Any] =F"pytorch_model-{n_layers + 1}-of-{n_layers + 1}.bin" if model_size == "7B": # Unsharded _a : List[str] ={ """model.embed_tokens.weight""": loaded["""tok_embeddings.weight"""], """model.norm.weight""": loaded["""norm.weight"""], """lm_head.weight""": loaded["""output.weight"""], } else: _a : int ={ """model.norm.weight""": loaded[0]["""norm.weight"""], """model.embed_tokens.weight""": torch.cat( [loaded[i]["""tok_embeddings.weight"""] for i in range(_UpperCAmelCase )] ,dim=1 ), """lm_head.weight""": torch.cat([loaded[i]["""output.weight"""] for i in range(_UpperCAmelCase )] ,dim=0 ), } for k, v in state_dict.items(): _a : Dict =filename param_count += v.numel() torch.save(_UpperCAmelCase ,os.path.join(_UpperCAmelCase ,_UpperCAmelCase ) ) # Write configs _a : Tuple ={"""total_size""": param_count * 2} write_json(_UpperCAmelCase ,os.path.join(_UpperCAmelCase ,"""pytorch_model.bin.index.json""" ) ) _a : Optional[Any] =params["""ffn_dim_multiplier"""] if """ffn_dim_multiplier""" in params else 1 _a : int =params["""multiple_of"""] if """multiple_of""" in params else 256 _a : List[Any] =LlamaConfig( hidden_size=_UpperCAmelCase ,intermediate_size=compute_intermediate_size(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) ,num_attention_heads=params["""n_heads"""] ,num_hidden_layers=params["""n_layers"""] ,rms_norm_eps=params["""norm_eps"""] ,num_key_value_heads=_UpperCAmelCase ,) config.save_pretrained(_UpperCAmelCase ) # 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.""" ) _a : Any =LlamaForCausalLM.from_pretrained(_UpperCAmelCase ,torch_dtype=torch.floataa ,low_cpu_mem_usage=_UpperCAmelCase ) # Avoid saving this as part of the config. del model.config._name_or_path print("""Saving in the Transformers format.""" ) model.save_pretrained(_UpperCAmelCase ,safe_serialization=_UpperCAmelCase ) shutil.rmtree(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ,_UpperCAmelCase : int ) -> Optional[Any]: # Initialize the tokenizer based on the `spm` model _a : List[str] =LlamaTokenizer if LlamaTokenizerFast is None else LlamaTokenizerFast print(F"Saving a {tokenizer_class.__name__} to {tokenizer_path}." ) _a : List[Any] =tokenizer_class(_UpperCAmelCase ) tokenizer.save_pretrained(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( ) -> Union[str, Any]: _a : List[str] =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=_UpperCAmelCase ,help="""Whether or not to save using `safetensors`.""" ) _a : Optional[Any] =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 ,) _a : List[Any] =os.path.join(args.input_dir ,"""tokenizer.model""" ) write_tokenizer(args.output_dir ,_UpperCAmelCase ) if __name__ == "__main__": main()
276
1
'''simple docstring''' from typing import TYPE_CHECKING from ..utils import _LazyModule A__: Optional[int] = { '''config''': [ '''EXTERNAL_DATA_FORMAT_SIZE_LIMIT''', '''OnnxConfig''', '''OnnxConfigWithPast''', '''OnnxSeq2SeqConfigWithPast''', '''PatchingSpec''', ], '''convert''': ['''export''', '''validate_model_outputs'''], '''features''': ['''FeaturesManager'''], '''utils''': ['''ParameterFormat''', '''compute_serialized_parameters_size'''], } if TYPE_CHECKING: from .config import ( EXTERNAL_DATA_FORMAT_SIZE_LIMIT, OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast, PatchingSpec, ) from .convert import export, validate_model_outputs from .features import FeaturesManager from .utils import ParameterFormat, compute_serialized_parameters_size else: import sys A__: str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
276
'''simple docstring''' import contextlib import os import sqlitea import pytest from datasets import Dataset, Features, Value from datasets.io.sql import SqlDatasetReader, SqlDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases, require_sqlalchemy def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Any ,_UpperCAmelCase : str ) -> Dict: assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ) 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 @require_sqlalchemy @pytest.mark.parametrize("""keep_in_memory""" ,[False, True] ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Optional[int] ,_UpperCAmelCase : str ) -> Optional[Any]: _a : Any =tmp_path / """cache""" _a : int ={"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): _a : Tuple =SqlDatasetReader( """dataset""" ,"""sqlite:///""" + sqlite_path ,cache_dir=_UpperCAmelCase ,keep_in_memory=_UpperCAmelCase ).read() _check_sql_dataset(_UpperCAmelCase ,_UpperCAmelCase ) @require_sqlalchemy @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 SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[Any] ,_UpperCAmelCase : Dict ,_UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : int ) -> List[Any]: _a : Union[str, Any] =tmp_path / """cache""" _a : str ={"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} _a : Optional[int] =features.copy() if features else default_expected_features _a : Union[str, Any] =( Features({feature: Value(_UpperCAmelCase ) for feature, dtype in features.items()} ) if features is not None else None ) _a : Optional[Any] =SqlDatasetReader("""dataset""" ,"""sqlite:///""" + sqlite_path ,features=_UpperCAmelCase ,cache_dir=_UpperCAmelCase ).read() _check_sql_dataset(_UpperCAmelCase ,_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[Any] ) -> List[str]: with contextlib.closing(sqlitea.connect(_UpperCAmelCase ) ) as con: _a : Any =con.cursor() cur.execute("""SELECT * FROM dataset""" ) for row in cur: yield row @require_sqlalchemy def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Dict ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : List[str] ) -> Union[str, Any]: _a : Union[str, Any] =tmp_path / """cache""" _a : Union[str, Any] =os.path.join(_UpperCAmelCase ,"""tmp.sql""" ) _a : Tuple =SqlDatasetReader("""dataset""" ,"""sqlite:///""" + sqlite_path ,cache_dir=_UpperCAmelCase ).read() SqlDatasetWriter(_UpperCAmelCase ,"""dataset""" ,"""sqlite:///""" + output_sqlite_path ,num_proc=1 ).write() _a : Tuple =iter_sql_file(_UpperCAmelCase ) _a : List[Any] =iter_sql_file(_UpperCAmelCase ) for rowa, rowa in zip(_UpperCAmelCase ,_UpperCAmelCase ): assert rowa == rowa @require_sqlalchemy def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Any ,_UpperCAmelCase : List[Any] ) -> Optional[int]: _a : int =tmp_path / """cache""" _a : Any =os.path.join(_UpperCAmelCase ,"""tmp.sql""" ) _a : Union[str, Any] =SqlDatasetReader("""dataset""" ,"""sqlite:///""" + sqlite_path ,cache_dir=_UpperCAmelCase ).read() SqlDatasetWriter(_UpperCAmelCase ,"""dataset""" ,"""sqlite:///""" + output_sqlite_path ,num_proc=2 ).write() _a : List[Any] =iter_sql_file(_UpperCAmelCase ) _a : str =iter_sql_file(_UpperCAmelCase ) for rowa, rowa in zip(_UpperCAmelCase ,_UpperCAmelCase ): assert rowa == rowa @require_sqlalchemy def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : str ,_UpperCAmelCase : List[Any] ) -> List[str]: _a : List[str] =tmp_path / """cache""" _a : Dict =os.path.join(_UpperCAmelCase ,"""tmp.sql""" ) _a : Optional[Any] =SqlDatasetReader("""dataset""" ,"""sqlite:///""" + sqlite_path ,cache_dir=_UpperCAmelCase ).read() with pytest.raises(_UpperCAmelCase ): SqlDatasetWriter(_UpperCAmelCase ,"""dataset""" ,"""sqlite:///""" + output_sqlite_path ,num_proc=0 ).write()
276
1
'''simple docstring''' from __future__ import annotations def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : list[int | float] ,_UpperCAmelCase : int ,_UpperCAmelCase : int ) -> int | float: if len(_UpperCAmelCase ) == 0: raise ValueError("""find_max() arg is an empty sequence""" ) if ( left >= len(_UpperCAmelCase ) or left < -len(_UpperCAmelCase ) or right >= len(_UpperCAmelCase ) or right < -len(_UpperCAmelCase ) ): raise IndexError("""list index out of range""" ) if left == right: return nums[left] _a : Dict =(left + right) >> 1 # the middle _a : List[Any] =find_max(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) # find max in range[left, mid] _a : Optional[Any] =find_max(_UpperCAmelCase ,mid + 1 ,_UpperCAmelCase ) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
276
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A__: List[str] = logging.get_logger(__name__) A__: Union[str, Any] = { '''facebook/data2vec-text-base''': '''https://huggingface.co/data2vec/resolve/main/config.json''', } class A__ ( UpperCAmelCase__ ): __UpperCamelCase : int = "data2vec-text" def __init__( self :str , SCREAMING_SNAKE_CASE :Optional[Any]=3_0_5_2_2 , SCREAMING_SNAKE_CASE :Any=7_6_8 , SCREAMING_SNAKE_CASE :List[Any]=1_2 , SCREAMING_SNAKE_CASE :List[str]=1_2 , SCREAMING_SNAKE_CASE :Dict=3_0_7_2 , SCREAMING_SNAKE_CASE :List[str]="gelu" , SCREAMING_SNAKE_CASE :Any=0.1 , SCREAMING_SNAKE_CASE :List[str]=0.1 , SCREAMING_SNAKE_CASE :int=5_1_2 , SCREAMING_SNAKE_CASE :int=2 , SCREAMING_SNAKE_CASE :Union[str, Any]=0.02 , SCREAMING_SNAKE_CASE :Dict=1e-12 , SCREAMING_SNAKE_CASE :int=1 , SCREAMING_SNAKE_CASE :Dict=0 , SCREAMING_SNAKE_CASE :List[Any]=2 , SCREAMING_SNAKE_CASE :str="absolute" , SCREAMING_SNAKE_CASE :Tuple=True , SCREAMING_SNAKE_CASE :Union[str, Any]=None , **SCREAMING_SNAKE_CASE :Union[str, Any] , ) -> List[str]: '''simple docstring''' super().__init__(pad_token_id=SCREAMING_SNAKE_CASE , bos_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) _a : Optional[Any] =vocab_size _a : Optional[Any] =hidden_size _a : Any =num_hidden_layers _a : List[str] =num_attention_heads _a : Union[str, Any] =hidden_act _a : Any =intermediate_size _a : str =hidden_dropout_prob _a : Optional[Any] =attention_probs_dropout_prob _a : Optional[Any] =max_position_embeddings _a : Union[str, Any] =type_vocab_size _a : Tuple =initializer_range _a : Optional[int] =layer_norm_eps _a : Tuple =position_embedding_type _a : int =use_cache _a : List[str] =classifier_dropout class A__ ( UpperCAmelCase__ ): @property def __UpperCAmelCase ( self :int ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' 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), ] )
276
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A__: Optional[Any] = logging.get_logger(__name__) A__: Any = { '''microsoft/swinv2-tiny-patch4-window8-256''': ( '''https://huggingface.co/microsoft/swinv2-tiny-patch4-window8-256/resolve/main/config.json''' ), } class A__ ( UpperCAmelCase__ ): __UpperCamelCase : List[str] = "swinv2" __UpperCamelCase : Optional[Any] = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self :Optional[int] , SCREAMING_SNAKE_CASE :Tuple=2_2_4 , SCREAMING_SNAKE_CASE :Dict=4 , SCREAMING_SNAKE_CASE :Dict=3 , SCREAMING_SNAKE_CASE :str=9_6 , SCREAMING_SNAKE_CASE :List[Any]=[2, 2, 6, 2] , SCREAMING_SNAKE_CASE :Optional[int]=[3, 6, 1_2, 2_4] , SCREAMING_SNAKE_CASE :Union[str, Any]=7 , SCREAMING_SNAKE_CASE :List[str]=4.0 , SCREAMING_SNAKE_CASE :Tuple=True , SCREAMING_SNAKE_CASE :Dict=0.0 , SCREAMING_SNAKE_CASE :Optional[int]=0.0 , SCREAMING_SNAKE_CASE :Optional[int]=0.1 , SCREAMING_SNAKE_CASE :List[Any]="gelu" , SCREAMING_SNAKE_CASE :str=False , SCREAMING_SNAKE_CASE :List[Any]=0.02 , SCREAMING_SNAKE_CASE :Dict=1e-5 , SCREAMING_SNAKE_CASE :List[str]=3_2 , **SCREAMING_SNAKE_CASE :int , ) -> Optional[int]: '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE ) _a : int =image_size _a : List[Any] =patch_size _a : str =num_channels _a : Any =embed_dim _a : Optional[int] =depths _a : Optional[int] =len(SCREAMING_SNAKE_CASE ) _a : Tuple =num_heads _a : Union[str, Any] =window_size _a : Union[str, Any] =mlp_ratio _a : str =qkv_bias _a : int =hidden_dropout_prob _a : Tuple =attention_probs_dropout_prob _a : Tuple =drop_path_rate _a : Any =hidden_act _a : Tuple =use_absolute_embeddings _a : Any =layer_norm_eps _a : Optional[int] =initializer_range _a : int =encoder_stride # we set the hidden_size attribute in order to make Swinv2 work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model _a : Any =int(embed_dim * 2 ** (len(SCREAMING_SNAKE_CASE ) - 1) ) _a : int =(0, 0, 0, 0)
276
'''simple docstring''' from typing import Dict, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import flip_channel_order, resize, to_channel_dimension_format, to_pil_image from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_pytesseract_available, is_vision_available, logging, requires_backends if is_vision_available(): import PIL # soft dependency if is_pytesseract_available(): import pytesseract A__: Union[str, Any] = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : List[str] ) -> int: return [ int(1000 * (box[0] / width) ), int(1000 * (box[1] / height) ), int(1000 * (box[2] / width) ), int(1000 * (box[3] / height) ), ] def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : np.ndarray ,_UpperCAmelCase : Optional[str] ,_UpperCAmelCase : Optional[str] = None ) -> Optional[int]: _a : Any =tesseract_config if tesseract_config is not None else """""" # apply OCR _a : Optional[Any] =to_pil_image(_UpperCAmelCase ) _a , _a : List[Any] =pil_image.size _a : List[str] =pytesseract.image_to_data(_UpperCAmelCase ,lang=_UpperCAmelCase ,output_type="""dict""" ,config=_UpperCAmelCase ) _a , _a , _a , _a , _a : str =data["""text"""], data["""left"""], data["""top"""], data["""width"""], data["""height"""] # filter empty words and corresponding coordinates _a : Tuple =[idx for idx, word in enumerate(_UpperCAmelCase ) if not word.strip()] _a : List[Any] =[word for idx, word in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] _a : Dict =[coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] _a : List[str] =[coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] _a : Union[str, Any] =[coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] _a : Union[str, Any] =[coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] # turn coordinates into (left, top, left+width, top+height) format _a : List[str] =[] for x, y, w, h in zip(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ): _a : int =[x, y, x + w, y + h] actual_boxes.append(_UpperCAmelCase ) # finally, normalize the bounding boxes _a : str =[] for box in actual_boxes: normalized_boxes.append(normalize_box(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) ) assert len(_UpperCAmelCase ) == len(_UpperCAmelCase ), "Not as many words as there are bounding boxes" return words, normalized_boxes class A__ ( UpperCAmelCase__ ): __UpperCamelCase : List[Any] = ["pixel_values"] def __init__( self :Tuple , SCREAMING_SNAKE_CASE :bool = True , SCREAMING_SNAKE_CASE :Dict[str, int] = None , SCREAMING_SNAKE_CASE :PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE :bool = True , SCREAMING_SNAKE_CASE :Optional[str] = None , SCREAMING_SNAKE_CASE :Optional[str] = "" , **SCREAMING_SNAKE_CASE :Tuple , ) -> None: '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE ) _a : List[Any] =size if size is not None else {"""height""": 2_2_4, """width""": 2_2_4} _a : Tuple =get_size_dict(SCREAMING_SNAKE_CASE ) _a : Dict =do_resize _a : Tuple =size _a : str =resample _a : Dict =apply_ocr _a : Union[str, Any] =ocr_lang _a : Dict =tesseract_config def __UpperCAmelCase ( self :List[str] , SCREAMING_SNAKE_CASE :np.ndarray , SCREAMING_SNAKE_CASE :Dict[str, int] , SCREAMING_SNAKE_CASE :PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE :Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE :Dict , ) -> np.ndarray: '''simple docstring''' _a : int =get_size_dict(SCREAMING_SNAKE_CASE ) if "height" not in size or "width" not in size: raise ValueError(f"The size dictionary must contain the keys 'height' and 'width'. Got {size.keys()}" ) _a : Any =(size["""height"""], size["""width"""]) return resize(SCREAMING_SNAKE_CASE , size=SCREAMING_SNAKE_CASE , resample=SCREAMING_SNAKE_CASE , data_format=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Dict , SCREAMING_SNAKE_CASE :ImageInput , SCREAMING_SNAKE_CASE :bool = None , SCREAMING_SNAKE_CASE :Dict[str, int] = None , SCREAMING_SNAKE_CASE :PILImageResampling = None , SCREAMING_SNAKE_CASE :bool = None , SCREAMING_SNAKE_CASE :Optional[str] = None , SCREAMING_SNAKE_CASE :Optional[str] = None , SCREAMING_SNAKE_CASE :Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE :ChannelDimension = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE :Optional[Any] , ) -> PIL.Image.Image: '''simple docstring''' _a : Optional[int] =do_resize if do_resize is not None else self.do_resize _a : Optional[int] =size if size is not None else self.size _a : str =get_size_dict(SCREAMING_SNAKE_CASE ) _a : List[str] =resample if resample is not None else self.resample _a : int =apply_ocr if apply_ocr is not None else self.apply_ocr _a : str =ocr_lang if ocr_lang is not None else self.ocr_lang _a : Union[str, Any] =tesseract_config if tesseract_config is not None else self.tesseract_config _a : List[str] =make_list_of_images(SCREAMING_SNAKE_CASE ) if not valid_images(SCREAMING_SNAKE_CASE ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None: raise ValueError("""Size must be specified if do_resize is True.""" ) # All transformations expect numpy arrays. _a : List[Any] =[to_numpy_array(SCREAMING_SNAKE_CASE ) for image in images] if apply_ocr: requires_backends(self , """pytesseract""" ) _a : Any =[] _a : Any =[] for image in images: _a , _a : int =apply_tesseract(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) words_batch.append(SCREAMING_SNAKE_CASE ) boxes_batch.append(SCREAMING_SNAKE_CASE ) if do_resize: _a : Union[str, Any] =[self.resize(image=SCREAMING_SNAKE_CASE , size=SCREAMING_SNAKE_CASE , resample=SCREAMING_SNAKE_CASE ) for image in images] # flip color channels from RGB to BGR (as Detectron2 requires this) _a : Dict =[flip_channel_order(SCREAMING_SNAKE_CASE ) for image in images] _a : str =[to_channel_dimension_format(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for image in images] _a : str =BatchFeature(data={"""pixel_values""": images} , tensor_type=SCREAMING_SNAKE_CASE ) if apply_ocr: _a : List[Any] =words_batch _a : Dict =boxes_batch return data
276
1
'''simple docstring''' from ...utils import is_note_seq_available, is_transformers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .notes_encoder import SpectrogramNotesEncoder from .continous_encoder import SpectrogramContEncoder from .pipeline_spectrogram_diffusion import ( SpectrogramContEncoder, SpectrogramDiffusionPipeline, TaFilmDecoder, ) try: if not (is_transformers_available() and is_torch_available() and is_note_seq_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_transformers_and_torch_and_note_seq_objects import * # noqa F403 else: from .midi_utils import MidiProcessor
276
'''simple docstring''' from __future__ import annotations import requests def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ) -> dict: _a : Any =F"https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty" return requests.get(_UpperCAmelCase ).json() def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int = 10 ) -> list[dict]: _a : Union[str, Any] ="""https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty""" _a : int =requests.get(_UpperCAmelCase ).json()[:max_stories] return [get_hackernews_story(_UpperCAmelCase ) for story_id in story_ids] def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int = 10 ) -> str: _a : Union[str, Any] =hackernews_top_stories(_UpperCAmelCase ) return "\n".join("""* [{title}]({url})""".format(**_UpperCAmelCase ) for story in stories ) if __name__ == "__main__": print(hackernews_top_stories_as_markdown())
276
1
'''simple docstring''' from unittest.mock import patch import pyspark from datasets.packaged_modules.spark.spark import ( Spark, SparkExamplesIterable, _generate_iterable_examples, ) from ..utils import ( require_dill_gt_0_3_2, require_not_windows, ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : Optional[int] ) -> Any: _a : Any =[] for part_id in partition_order: _a : List[Any] =df.where(F"SPARK_PARTITION_ID() = {part_id}" ).collect() for row_idx, row in enumerate(_UpperCAmelCase ): expected_row_ids_and_row_dicts.append((F"{part_id}_{row_idx}", row.asDict()) ) return expected_row_ids_and_row_dicts @require_not_windows @require_dill_gt_0_3_2 def SCREAMING_SNAKE_CASE_ ( ) -> Union[str, Any]: _a : Optional[Any] =pyspark.sql.SparkSession.builder.master("""local[*]""" ).appName("""pyspark""" ).getOrCreate() _a : Any =spark.range(100 ).repartition(1 ) _a : Dict =Spark(_UpperCAmelCase ) # The id ints will be converted to Pyarrow int64s, so each row will be 8 bytes. Setting a max_shard_size of 16 means # that each partition can hold 2 rows. spark_builder._repartition_df_if_needed(max_shard_size=16 ) # Given that the dataframe has 100 rows and each partition has 2 rows, we expect 50 partitions. assert spark_builder.df.rdd.getNumPartitions() == 50 @require_not_windows @require_dill_gt_0_3_2 def SCREAMING_SNAKE_CASE_ ( ) -> str: _a : Dict =pyspark.sql.SparkSession.builder.master("""local[*]""" ).appName("""pyspark""" ).getOrCreate() _a : List[Any] =spark.range(10 ).repartition(2 ) _a : Optional[Any] =[1, 0] _a : int =_generate_iterable_examples(_UpperCAmelCase ,_UpperCAmelCase ) # Reverse the partitions. _a : Union[str, Any] =_get_expected_row_ids_and_row_dicts_for_partition_order(_UpperCAmelCase ,_UpperCAmelCase ) for i, (row_id, row_dict) in enumerate(generate_fn() ): _a , _a : int =expected_row_ids_and_row_dicts[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def SCREAMING_SNAKE_CASE_ ( ) -> int: _a : str =pyspark.sql.SparkSession.builder.master("""local[*]""" ).appName("""pyspark""" ).getOrCreate() _a : str =spark.range(10 ).repartition(1 ) _a : int =SparkExamplesIterable(_UpperCAmelCase ) assert it.n_shards == 1 for i, (row_id, row_dict) in enumerate(_UpperCAmelCase ): assert row_id == F"0_{i}" assert row_dict == {"id": i} @require_not_windows @require_dill_gt_0_3_2 def SCREAMING_SNAKE_CASE_ ( ) -> Tuple: _a : List[str] =pyspark.sql.SparkSession.builder.master("""local[*]""" ).appName("""pyspark""" ).getOrCreate() _a : List[Any] =spark.range(30 ).repartition(3 ) # Mock the generator so that shuffle reverses the partition indices. with patch("""numpy.random.Generator""" ) as generator_mock: _a : Optional[int] =lambda _UpperCAmelCase : x.reverse() _a : Optional[int] =_get_expected_row_ids_and_row_dicts_for_partition_order(_UpperCAmelCase ,[2, 1, 0] ) _a : Tuple =SparkExamplesIterable(_UpperCAmelCase ).shuffle_data_sources(_UpperCAmelCase ) assert shuffled_it.n_shards == 3 for i, (row_id, row_dict) in enumerate(_UpperCAmelCase ): _a , _a : Optional[Any] =expected_row_ids_and_row_dicts[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def SCREAMING_SNAKE_CASE_ ( ) -> List[str]: _a : int =pyspark.sql.SparkSession.builder.master("""local[*]""" ).appName("""pyspark""" ).getOrCreate() _a : int =spark.range(20 ).repartition(4 ) # Partitions 0 and 2 _a : str =SparkExamplesIterable(_UpperCAmelCase ).shard_data_sources(worker_id=0 ,num_workers=2 ) assert shard_it_a.n_shards == 2 _a : Optional[int] =_get_expected_row_ids_and_row_dicts_for_partition_order(_UpperCAmelCase ,[0, 2] ) for i, (row_id, row_dict) in enumerate(_UpperCAmelCase ): _a , _a : Any =expected_row_ids_and_row_dicts_a[i] assert row_id == expected_row_id assert row_dict == expected_row_dict # Partitions 1 and 3 _a : int =SparkExamplesIterable(_UpperCAmelCase ).shard_data_sources(worker_id=1 ,num_workers=2 ) assert shard_it_a.n_shards == 2 _a : Dict =_get_expected_row_ids_and_row_dicts_for_partition_order(_UpperCAmelCase ,[1, 3] ) for i, (row_id, row_dict) in enumerate(_UpperCAmelCase ): _a , _a : Dict =expected_row_ids_and_row_dicts_a[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def SCREAMING_SNAKE_CASE_ ( ) -> Tuple: _a : Optional[int] =pyspark.sql.SparkSession.builder.master("""local[*]""" ).appName("""pyspark""" ).getOrCreate() _a : int =spark.range(100 ).repartition(1 ) _a : List[Any] =Spark(_UpperCAmelCase ) # Choose a small max_shard_size for maximum partitioning. spark_builder._repartition_df_if_needed(max_shard_size=1 ) # The new number of partitions should not be greater than the number of rows. assert spark_builder.df.rdd.getNumPartitions() == 100
276
'''simple docstring''' from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .modeling_utils import ModelMixin from .vae import Decoder, DecoderOutput, Encoder, VectorQuantizer @dataclass class A__ ( UpperCAmelCase__ ): __UpperCamelCase : torch.FloatTensor class A__ ( UpperCAmelCase__ , UpperCAmelCase__ ): @register_to_config def __init__( self :Optional[Any] , SCREAMING_SNAKE_CASE :int = 3 , SCREAMING_SNAKE_CASE :int = 3 , SCREAMING_SNAKE_CASE :Tuple[str] = ("DownEncoderBlock2D",) , SCREAMING_SNAKE_CASE :Tuple[str] = ("UpDecoderBlock2D",) , SCREAMING_SNAKE_CASE :Tuple[int] = (6_4,) , SCREAMING_SNAKE_CASE :int = 1 , SCREAMING_SNAKE_CASE :str = "silu" , SCREAMING_SNAKE_CASE :int = 3 , SCREAMING_SNAKE_CASE :int = 3_2 , SCREAMING_SNAKE_CASE :int = 2_5_6 , SCREAMING_SNAKE_CASE :int = 3_2 , SCREAMING_SNAKE_CASE :Optional[int] = None , SCREAMING_SNAKE_CASE :float = 0.18_215 , SCREAMING_SNAKE_CASE :str = "group" , ) -> Optional[int]: '''simple docstring''' super().__init__() # pass init params to Encoder _a : Union[str, Any] =Encoder( in_channels=SCREAMING_SNAKE_CASE , out_channels=SCREAMING_SNAKE_CASE , down_block_types=SCREAMING_SNAKE_CASE , block_out_channels=SCREAMING_SNAKE_CASE , layers_per_block=SCREAMING_SNAKE_CASE , act_fn=SCREAMING_SNAKE_CASE , norm_num_groups=SCREAMING_SNAKE_CASE , double_z=SCREAMING_SNAKE_CASE , ) _a : Optional[int] =vq_embed_dim if vq_embed_dim is not None else latent_channels _a : Optional[int] =nn.Convad(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , 1 ) _a : str =VectorQuantizer(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , beta=0.25 , remap=SCREAMING_SNAKE_CASE , sane_index_shape=SCREAMING_SNAKE_CASE ) _a : List[str] =nn.Convad(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , 1 ) # pass init params to Decoder _a : List[str] =Decoder( in_channels=SCREAMING_SNAKE_CASE , out_channels=SCREAMING_SNAKE_CASE , up_block_types=SCREAMING_SNAKE_CASE , block_out_channels=SCREAMING_SNAKE_CASE , layers_per_block=SCREAMING_SNAKE_CASE , act_fn=SCREAMING_SNAKE_CASE , norm_num_groups=SCREAMING_SNAKE_CASE , norm_type=SCREAMING_SNAKE_CASE , ) @apply_forward_hook def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :torch.FloatTensor , SCREAMING_SNAKE_CASE :bool = True ) -> VQEncoderOutput: '''simple docstring''' _a : Optional[int] =self.encoder(SCREAMING_SNAKE_CASE ) _a : int =self.quant_conv(SCREAMING_SNAKE_CASE ) if not return_dict: return (h,) return VQEncoderOutput(latents=SCREAMING_SNAKE_CASE ) @apply_forward_hook def __UpperCAmelCase ( self :List[Any] , SCREAMING_SNAKE_CASE :torch.FloatTensor , SCREAMING_SNAKE_CASE :bool = False , SCREAMING_SNAKE_CASE :bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: '''simple docstring''' # also go through quantization layer if not force_not_quantize: _a , _a , _a : Tuple =self.quantize(SCREAMING_SNAKE_CASE ) else: _a : str =h _a : Dict =self.post_quant_conv(SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =self.decoder(SCREAMING_SNAKE_CASE , quant if self.config.norm_type == """spatial""" else None ) if not return_dict: return (dec,) return DecoderOutput(sample=SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :torch.FloatTensor , SCREAMING_SNAKE_CASE :bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: '''simple docstring''' _a : Tuple =sample _a : int =self.encode(SCREAMING_SNAKE_CASE ).latents _a : List[Any] =self.decode(SCREAMING_SNAKE_CASE ).sample if not return_dict: return (dec,) return DecoderOutput(sample=SCREAMING_SNAKE_CASE )
276
1
'''simple docstring''' import unittest from transformers import SPIECE_UNDERLINE from transformers.models.speechta import SpeechTaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.tokenization_utils import AddedToken from ...test_tokenization_common import TokenizerTesterMixin A__: Optional[int] = get_tests_dir('''fixtures/test_sentencepiece_bpe_char.model''') @require_sentencepiece @require_tokenizers class A__ ( UpperCAmelCase__ , unittest.TestCase ): __UpperCamelCase : Any = SpeechTaTokenizer __UpperCamelCase : List[str] = False __UpperCamelCase : Optional[int] = True def __UpperCAmelCase ( self :Union[str, Any] ) -> Tuple: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing _a : Optional[Any] =SpeechTaTokenizer(SCREAMING_SNAKE_CASE ) _a : List[str] =AddedToken("""<mask>""" , lstrip=SCREAMING_SNAKE_CASE , rstrip=SCREAMING_SNAKE_CASE ) _a : str =mask_token tokenizer.add_special_tokens({"""mask_token""": mask_token} ) tokenizer.add_tokens(["""<ctc_blank>"""] ) tokenizer.save_pretrained(self.tmpdirname ) def __UpperCAmelCase ( self :Optional[int] , SCREAMING_SNAKE_CASE :Any ) -> Optional[Any]: '''simple docstring''' _a : Tuple ="""this is a test""" _a : List[str] ="""this is a test""" return input_text, output_text def __UpperCAmelCase ( self :str , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Dict=False , SCREAMING_SNAKE_CASE :Tuple=2_0 , SCREAMING_SNAKE_CASE :Any=5 ) -> Any: '''simple docstring''' _a , _a : Any =self.get_input_output_texts(SCREAMING_SNAKE_CASE ) _a : str =tokenizer.encode(SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE ) _a : Tuple =tokenizer.decode(SCREAMING_SNAKE_CASE , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE ) return text, ids def __UpperCAmelCase ( self :List[Any] ) -> str: '''simple docstring''' _a : Tuple ="""<pad>""" _a : List[Any] =1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :int ) -> Optional[Any]: '''simple docstring''' _a : Tuple =list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """<s>""" ) self.assertEqual(vocab_keys[1] , """<pad>""" ) self.assertEqual(vocab_keys[-4] , """œ""" ) self.assertEqual(vocab_keys[-2] , """<mask>""" ) self.assertEqual(vocab_keys[-1] , """<ctc_blank>""" ) self.assertEqual(len(SCREAMING_SNAKE_CASE ) , 8_1 ) def __UpperCAmelCase ( self :List[Any] ) -> int: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 7_9 ) def __UpperCAmelCase ( self :List[str] ) -> Optional[int]: '''simple docstring''' _a : int =self.get_tokenizers(do_lower_case=SCREAMING_SNAKE_CASE ) for tokenizer in tokenizers: with self.subTest(f"{tokenizer.__class__.__name__}" ): _a : List[str] =tokenizer.vocab_size _a : Dict =len(SCREAMING_SNAKE_CASE ) self.assertNotEqual(SCREAMING_SNAKE_CASE , 0 ) # We usually have added tokens from the start in tests because our vocab fixtures are # smaller than the original vocabs - let's not assert this # self.assertEqual(vocab_size, all_size) _a : str =["""aaaaa bbbbbb""", """cccccccccdddddddd"""] _a : int =tokenizer.add_tokens(SCREAMING_SNAKE_CASE ) _a : Optional[int] =tokenizer.vocab_size _a : Optional[Any] =len(SCREAMING_SNAKE_CASE ) self.assertNotEqual(SCREAMING_SNAKE_CASE , 0 ) self.assertEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) self.assertEqual(SCREAMING_SNAKE_CASE , len(SCREAMING_SNAKE_CASE ) ) self.assertEqual(SCREAMING_SNAKE_CASE , all_size + len(SCREAMING_SNAKE_CASE ) ) _a : Optional[Any] =tokenizer.encode("""aaaaa bbbbbb low cccccccccdddddddd l""" , add_special_tokens=SCREAMING_SNAKE_CASE ) self.assertGreaterEqual(len(SCREAMING_SNAKE_CASE ) , 4 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) _a : int ={"""eos_token""": """>>>>|||<||<<|<<""", """pad_token""": """<<<<<|||>|>>>>|>"""} _a : Union[str, Any] =tokenizer.add_special_tokens(SCREAMING_SNAKE_CASE ) _a : Any =tokenizer.vocab_size _a : Optional[Any] =len(SCREAMING_SNAKE_CASE ) self.assertNotEqual(SCREAMING_SNAKE_CASE , 0 ) self.assertEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) self.assertEqual(SCREAMING_SNAKE_CASE , len(SCREAMING_SNAKE_CASE ) ) self.assertEqual(SCREAMING_SNAKE_CASE , all_size_a + len(SCREAMING_SNAKE_CASE ) ) _a : Union[str, Any] =tokenizer.encode( """>>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l""" , add_special_tokens=SCREAMING_SNAKE_CASE ) self.assertGreaterEqual(len(SCREAMING_SNAKE_CASE ) , 6 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[0] , tokens[1] ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokens[-4] ) self.assertEqual(tokens[0] , tokenizer.eos_token_id ) self.assertEqual(tokens[-3] , tokenizer.pad_token_id ) def __UpperCAmelCase ( self :int ) -> Any: '''simple docstring''' pass def __UpperCAmelCase ( self :Tuple ) -> List[Any]: '''simple docstring''' pass def __UpperCAmelCase ( self :List[str] ) -> Optional[Any]: '''simple docstring''' _a : Optional[int] =self.get_tokenizer() _a : Union[str, Any] =tokenizer.tokenize("""This is a test""" ) # fmt: off self.assertListEqual(SCREAMING_SNAKE_CASE , [SPIECE_UNDERLINE, """T""", """h""", """i""", """s""", SPIECE_UNDERLINE, """i""", """s""", SPIECE_UNDERLINE, """a""", SPIECE_UNDERLINE, """t""", """e""", """s""", """t"""] ) # fmt: on self.assertListEqual( tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE ) , [4, 3_2, 1_1, 1_0, 1_2, 4, 1_0, 1_2, 4, 7, 4, 6, 5, 1_2, 6] , ) _a : Optional[int] =tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( SCREAMING_SNAKE_CASE , [SPIECE_UNDERLINE, """I""", SPIECE_UNDERLINE, """w""", """a""", """s""", SPIECE_UNDERLINE, """b""", """o""", """r""", """n""", SPIECE_UNDERLINE, """i""", """n""", SPIECE_UNDERLINE, """92000""", """,""", SPIECE_UNDERLINE, """a""", """n""", """d""", SPIECE_UNDERLINE, """t""", """h""", """i""", """s""", SPIECE_UNDERLINE, """i""", """s""", SPIECE_UNDERLINE, """f""", """a""", """l""", """s""", """é""", """."""] ) _a : List[str] =tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE ) # fmt: off self.assertListEqual(SCREAMING_SNAKE_CASE , [4, 3_0, 4, 2_0, 7, 1_2, 4, 2_5, 8, 1_3, 9, 4, 1_0, 9, 4, 3, 2_3, 4, 7, 9, 1_4, 4, 6, 1_1, 1_0, 1_2, 4, 1_0, 1_2, 4, 1_9, 7, 1_5, 1_2, 7_3, 2_6] ) # fmt: on _a : Any =tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE ) self.assertListEqual( SCREAMING_SNAKE_CASE , [SPIECE_UNDERLINE, """I""", SPIECE_UNDERLINE, """w""", """a""", """s""", SPIECE_UNDERLINE, """b""", """o""", """r""", """n""", SPIECE_UNDERLINE, """i""", """n""", SPIECE_UNDERLINE, """<unk>""", """,""", SPIECE_UNDERLINE, """a""", """n""", """d""", SPIECE_UNDERLINE, """t""", """h""", """i""", """s""", SPIECE_UNDERLINE, """i""", """s""", SPIECE_UNDERLINE, """f""", """a""", """l""", """s""", """é""", """."""] ) @slow def __UpperCAmelCase ( self :List[str] ) -> Any: '''simple docstring''' # Use custom sequence because this tokenizer does not handle numbers. _a : Dict =[ """Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides """ """general-purpose architectures (BERT, GPT, RoBERTa, XLM, DistilBert, XLNet...) for Natural """ """Language Understanding (NLU) and Natural Language Generation (NLG) with over thirty-two pretrained """ """models in one hundred plus languages and deep interoperability between Jax, PyTorch and TensorFlow.""", """BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly """ """conditioning on both left and right context in all layers.""", """The quick brown fox jumps over the lazy dog.""", ] # fmt: off _a : List[Any] ={ """input_ids""": [ [4, 3_2, 1_3, 7, 9, 1_2, 1_9, 8, 1_3, 1_8, 5, 1_3, 1_2, 4, 6_4, 1_9, 8, 1_3, 1_8, 5, 1_3, 1_5, 2_2, 4, 2_8, 9, 8, 2_0, 9, 4, 7, 1_2, 4, 2_4, 2_2, 6, 8, 1_3, 1_7, 1_1, 3_9, 6, 1_3, 7, 9, 1_2, 1_9, 8, 1_3, 1_8, 5, 1_3, 1_2, 4, 7, 9, 1_4, 4, 2_4, 2_2, 6, 8, 1_3, 1_7, 1_1, 3_9, 2_4, 1_3, 5, 6, 1_3, 7, 1_0, 9, 5, 1_4, 3_9, 2_5, 5, 1_3, 6, 6_3, 4, 2_4, 1_3, 8, 2_7, 1_0, 1_4, 5, 1_2, 4, 2_1, 5, 9, 5, 1_3, 7, 1_5, 3_9, 2_4, 1_6, 1_3, 2_4, 8, 1_2, 5, 4, 7, 1_3, 1_7, 1_1, 1_0, 6, 5, 1_7, 6, 1_6, 1_3, 5, 1_2, 4, 6_4, 4_0, 4_7, 5_4, 3_2, 2_3, 4, 5_3, 4_9, 3_2, 2_3, 4, 5_4, 8, 4_0, 4_7, 5_4, 3_2, 7, 2_3, 4, 6_9, 5_2, 4_3, 2_3, 4, 5_1, 1_0, 1_2, 6, 1_0, 1_5, 4_0, 5, 1_3, 6, 2_3, 4, 6_9, 5_2, 4_8, 5, 6, 2_6, 2_6, 2_6, 6_3, 4, 1_9, 8, 1_3, 4, 4_8, 7, 6, 1_6, 1_3, 7, 1_5, 4, 5_2, 7, 9, 2_1, 1_6, 7, 2_1, 5, 4, 6_1, 9, 1_4, 5, 1_3, 1_2, 6, 7, 9, 1_4, 1_0, 9, 2_1, 4, 6_4, 4_8, 5_2, 6_1, 6_3, 4, 7, 9, 1_4, 4, 4_8, 7, 6, 1_6, 1_3, 7, 1_5, 4, 5_2, 7, 9, 2_1, 1_6, 7, 2_1, 5, 4, 5_3, 5, 9, 5, 1_3, 7, 6, 1_0, 8, 9, 4, 6_4, 4_8, 5_2, 5_3, 6_3, 4, 2_0, 1_0, 6, 1_1, 4, 8, 2_7, 5, 1_3, 4, 6, 1_1, 1_0, 1_3, 6, 2_2, 3_9, 6, 2_0, 8, 4, 2_4, 1_3, 5, 6, 1_3, 7, 1_0, 9, 5, 1_4, 4, 1_8, 8, 1_4, 5, 1_5, 1_2, 4, 1_0, 9, 4, 8, 9, 5, 4, 1_1, 1_6, 9, 1_4, 1_3, 5, 1_4, 4, 2_4, 1_5, 1_6, 1_2, 4, 1_5, 7, 9, 2_1, 1_6, 7, 2_1, 5, 1_2, 4, 7, 9, 1_4, 4, 1_4, 5, 5, 2_4, 4, 1_0, 9, 6, 5, 1_3, 8, 2_4, 5, 1_3, 7, 2_5, 1_0, 1_5, 1_0, 6, 2_2, 4, 2_5, 5, 6, 2_0, 5, 5, 9, 4, 5_8, 7, 3_7, 2_3, 4, 4_9, 2_2, 3_2, 8, 1_3, 1_7, 1_1, 4, 7, 9, 1_4, 4, 3_2, 5, 9, 1_2, 8, 1_3, 5_5, 1_5, 8, 2_0, 2_6, 2], [4, 4_0, 4_7, 5_4, 3_2, 4, 1_0, 1_2, 4, 1_4, 5, 1_2, 1_0, 2_1, 9, 5, 1_4, 4, 6, 8, 4, 2_4, 1_3, 5, 3_9, 6, 1_3, 7, 1_0, 9, 4, 1_4, 5, 5, 2_4, 4, 2_5, 1_0, 1_4, 1_0, 1_3, 5, 1_7, 6, 1_0, 8, 9, 7, 1_5, 4, 1_3, 5, 2_4, 1_3, 5, 1_2, 5, 9, 6, 7, 6, 1_0, 8, 9, 1_2, 4, 1_9, 1_3, 8, 1_8, 4, 1_6, 9, 1_5, 7, 2_5, 5, 1_5, 5, 1_4, 4, 6, 5, 3_7, 6, 4, 2_5, 2_2, 4, 4_6, 8, 1_0, 9, 6, 1_5, 2_2, 4, 1_7, 8, 9, 1_4, 1_0, 6, 1_0, 8, 9, 1_0, 9, 2_1, 4, 8, 9, 4, 2_5, 8, 6, 1_1, 4, 1_5, 5, 1_9, 6, 4, 7, 9, 1_4, 4, 1_3, 1_0, 2_1, 1_1, 6, 4, 1_7, 8, 9, 6, 5, 3_7, 6, 4, 1_0, 9, 4, 7, 1_5, 1_5, 4, 1_5, 7, 2_2, 5, 1_3, 1_2, 2_6, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [4, 3_2, 1_1, 5, 4, 4_5, 1_6, 1_0, 1_7, 2_8, 4, 2_5, 1_3, 8, 2_0, 9, 4, 1_9, 8, 3_7, 4, 4_6, 1_6, 1_8, 2_4, 1_2, 4, 8, 2_7, 5, 1_3, 4, 6, 1_1, 5, 4, 1_5, 7, 5_7, 2_2, 4, 1_4, 8, 2_1, 2_6, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], ], """attention_mask""": [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] } # fmt: on self.tokenizer_integration_test_util( expected_encoding=SCREAMING_SNAKE_CASE , model_name="""microsoft/speecht5_asr""" , revision="""c5ef64c71905caeccde0e4462ef3f9077224c524""" , sequences=SCREAMING_SNAKE_CASE , )
276
'''simple docstring''' import unittest from transformers import EsmConfig, is_torch_available from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import EsmForMaskedLM, EsmForSequenceClassification, EsmForTokenClassification, EsmModel from transformers.models.esm.modeling_esm import ( ESM_PRETRAINED_MODEL_ARCHIVE_LIST, EsmEmbeddings, create_position_ids_from_input_ids, ) class A__ : def __init__( self :Tuple , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :Optional[int]=1_3 , SCREAMING_SNAKE_CASE :Optional[int]=7 , SCREAMING_SNAKE_CASE :Tuple=False , SCREAMING_SNAKE_CASE :Dict=True , SCREAMING_SNAKE_CASE :Optional[int]=False , SCREAMING_SNAKE_CASE :Optional[Any]=True , SCREAMING_SNAKE_CASE :List[str]=3_3 , SCREAMING_SNAKE_CASE :Tuple=3_2 , SCREAMING_SNAKE_CASE :Tuple=5 , SCREAMING_SNAKE_CASE :int=4 , SCREAMING_SNAKE_CASE :Union[str, Any]=3_7 , SCREAMING_SNAKE_CASE :List[str]="gelu" , SCREAMING_SNAKE_CASE :Optional[Any]=0.1 , SCREAMING_SNAKE_CASE :Tuple=0.1 , SCREAMING_SNAKE_CASE :str=5_1_2 , SCREAMING_SNAKE_CASE :Dict=1_6 , SCREAMING_SNAKE_CASE :Dict=2 , SCREAMING_SNAKE_CASE :Union[str, Any]=0.02 , SCREAMING_SNAKE_CASE :str=3 , SCREAMING_SNAKE_CASE :List[str]=4 , SCREAMING_SNAKE_CASE :List[str]=None , ) -> Union[str, Any]: '''simple docstring''' _a : Union[str, Any] =parent _a : List[Any] =batch_size _a : Optional[int] =seq_length _a : Union[str, Any] =is_training _a : List[Any] =use_input_mask _a : Optional[int] =use_token_type_ids _a : int =use_labels _a : List[str] =vocab_size _a : List[Any] =hidden_size _a : int =num_hidden_layers _a : Tuple =num_attention_heads _a : Any =intermediate_size _a : str =hidden_act _a : Union[str, Any] =hidden_dropout_prob _a : Union[str, Any] =attention_probs_dropout_prob _a : str =max_position_embeddings _a : Dict =type_vocab_size _a : Tuple =type_sequence_label_size _a : Dict =initializer_range _a : List[str] =num_labels _a : Tuple =num_choices _a : int =scope def __UpperCAmelCase ( self :Union[str, Any] ) -> str: '''simple docstring''' _a : Optional[int] =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _a : List[Any] =None if self.use_input_mask: _a : Any =random_attention_mask([self.batch_size, self.seq_length] ) _a : Optional[int] =None _a : str =None _a : Dict =None if self.use_labels: _a : Dict =ids_tensor([self.batch_size] , self.type_sequence_label_size ) _a : str =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _a : List[str] =ids_tensor([self.batch_size] , self.num_choices ) _a : List[Any] =self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCAmelCase ( self :str ) -> Optional[int]: '''simple docstring''' return EsmConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , pad_token_id=1 , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) def __UpperCAmelCase ( self :List[str] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :int ) -> Tuple: '''simple docstring''' _a : Any =EsmModel(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() _a : Optional[Any] =model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =model(SCREAMING_SNAKE_CASE ) _a : str =model(SCREAMING_SNAKE_CASE ) 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 __UpperCAmelCase ( self :str , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :Optional[Any] ) -> Dict: '''simple docstring''' _a : str =EsmForMaskedLM(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() _a : Union[str, Any] =model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :List[Any] , SCREAMING_SNAKE_CASE :Union[str, Any] ) -> Optional[Any]: '''simple docstring''' _a : int =self.num_labels _a : Tuple =EsmForTokenClassification(config=SCREAMING_SNAKE_CASE ) model.to(SCREAMING_SNAKE_CASE ) model.eval() _a : Tuple =model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCAmelCase ( self :Dict ) -> List[str]: '''simple docstring''' _a : Optional[Any] =self.prepare_config_and_inputs() ( ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ) : Any =config_and_inputs _a : List[Any] ={"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class A__ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): __UpperCamelCase : Any = False __UpperCamelCase : Any = ( ( EsmForMaskedLM, EsmModel, EsmForSequenceClassification, EsmForTokenClassification, ) if is_torch_available() else () ) __UpperCamelCase : str = () __UpperCamelCase : List[str] = ( { "feature-extraction": EsmModel, "fill-mask": EsmForMaskedLM, "text-classification": EsmForSequenceClassification, "token-classification": EsmForTokenClassification, "zero-shot": EsmForSequenceClassification, } if is_torch_available() else {} ) __UpperCamelCase : Union[str, Any] = True def __UpperCAmelCase ( self :Optional[int] ) -> int: '''simple docstring''' _a : Dict =EsmModelTester(self ) _a : Optional[Any] =ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , hidden_size=3_7 ) def __UpperCAmelCase ( self :Tuple ) -> List[Any]: '''simple docstring''' self.config_tester.run_common_tests() def __UpperCAmelCase ( self :Optional[int] ) -> str: '''simple docstring''' _a : List[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :List[Any] ) -> Dict: '''simple docstring''' _a : List[str] =self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: _a : Dict =type self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Dict ) -> List[str]: '''simple docstring''' _a : Tuple =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :List[Any] ) -> List[str]: '''simple docstring''' _a : str =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE ) @slow def __UpperCAmelCase ( self :str ) -> Dict: '''simple docstring''' for model_name in ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _a : Union[str, Any] =EsmModel.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Tuple ) -> int: '''simple docstring''' _a : Optional[Any] =self.model_tester.prepare_config_and_inputs()[0] _a : Dict =EsmEmbeddings(config=SCREAMING_SNAKE_CASE ) _a : Tuple =torch.as_tensor([[1_2, 3_1, 1_3, model.padding_idx]] ) _a : Optional[Any] =torch.as_tensor( [ [ 0 + model.padding_idx + 1, 1 + model.padding_idx + 1, 2 + model.padding_idx + 1, model.padding_idx, ] ] ) _a : Any =create_position_ids_from_input_ids(SCREAMING_SNAKE_CASE , model.padding_idx ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) ) def __UpperCAmelCase ( self :Optional[Any] ) -> Tuple: '''simple docstring''' _a : List[Any] =self.model_tester.prepare_config_and_inputs()[0] _a : Optional[int] =EsmEmbeddings(config=SCREAMING_SNAKE_CASE ) _a : Tuple =torch.empty(2 , 4 , 3_0 ) _a : str =[ 0 + embeddings.padding_idx + 1, 1 + embeddings.padding_idx + 1, 2 + embeddings.padding_idx + 1, 3 + embeddings.padding_idx + 1, ] _a : int =torch.as_tensor([expected_single_positions, expected_single_positions] ) _a : Any =embeddings.create_position_ids_from_inputs_embeds(SCREAMING_SNAKE_CASE ) self.assertEqual(position_ids.shape , expected_positions.shape ) self.assertTrue(torch.all(torch.eq(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) ) @unittest.skip("""Esm does not support embedding resizing""" ) def __UpperCAmelCase ( self :Tuple ) -> List[str]: '''simple docstring''' pass @unittest.skip("""Esm does not support embedding resizing""" ) def __UpperCAmelCase ( self :str ) -> Any: '''simple docstring''' pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def __UpperCAmelCase ( self :Dict ) -> Any: '''simple docstring''' pass @require_torch class A__ ( UpperCAmelCase__ ): @slow def __UpperCAmelCase ( self :List[Any] ) -> str: '''simple docstring''' with torch.no_grad(): _a : Optional[int] =EsmForMaskedLM.from_pretrained("""facebook/esm2_t6_8M_UR50D""" ) model.eval() _a : Any =torch.tensor([[0, 1, 2, 3, 4, 5]] ) _a : Tuple =model(SCREAMING_SNAKE_CASE )[0] _a : int =3_3 _a : Tuple =torch.Size((1, 6, vocab_size) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =torch.tensor( [[[8.9_215, -10.5_898, -6.4_671], [-6.3_967, -13.9_114, -1.1_212], [-7.7_812, -13.9_516, -3.7_406]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) ) @slow def __UpperCAmelCase ( self :Union[str, Any] ) -> Tuple: '''simple docstring''' with torch.no_grad(): _a : Any =EsmModel.from_pretrained("""facebook/esm2_t6_8M_UR50D""" ) model.eval() _a : Any =torch.tensor([[0, 6, 4, 1_3, 5, 4, 1_6, 1_2, 1_1, 7, 2]] ) _a : int =model(SCREAMING_SNAKE_CASE )[0] # compare the actual values for a slice. _a : str =torch.tensor( [[[0.1_444, 0.5_413, 0.3_248], [0.3_034, 0.0_053, 0.3_108], [0.3_228, -0.2_499, 0.3_415]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) )
276
1
'''simple docstring''' import gc import threading import time import psutil import torch class A__ : def __init__( self :int ) -> Tuple: '''simple docstring''' _a : int =psutil.Process() _a : List[Any] =False def __UpperCAmelCase ( self :Dict ) -> List[str]: '''simple docstring''' _a : List[Any] =-1 while True: _a : int =max(self.process.memory_info().rss , self.cpu_memory_peak ) # can't sleep or will not catch the peak right (this comment is here on purpose) if not self.peak_monitoring: break def __UpperCAmelCase ( self :List[str] ) -> str: '''simple docstring''' _a : List[str] =True _a : Optional[int] =threading.Thread(target=self.peak_monitor ) _a : Dict =True self.thread.start() def __UpperCAmelCase ( self :Dict ) -> Any: '''simple docstring''' _a : Any =False self.thread.join() return self.cpu_memory_peak A__: int = PeakCPUMemory() def SCREAMING_SNAKE_CASE_ ( ) -> Union[str, Any]: # Time _a : Any ={"""time""": time.time()} gc.collect() torch.cuda.empty_cache() # CPU mem _a : Optional[Any] =psutil.Process().memory_info().rss cpu_peak_tracker.start() # GPU mem for i in range(torch.cuda.device_count() ): _a : Union[str, Any] =torch.cuda.memory_allocated(_UpperCAmelCase ) torch.cuda.reset_peak_memory_stats() return measures def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[Any] ) -> List[Any]: # Time _a : Optional[int] ={"""time""": time.time() - start_measures["""time"""]} gc.collect() torch.cuda.empty_cache() # CPU mem _a : int =(psutil.Process().memory_info().rss - start_measures["""cpu"""]) / 2**20 _a : int =(cpu_peak_tracker.stop() - start_measures["""cpu"""]) / 2**20 # GPU mem for i in range(torch.cuda.device_count() ): _a : str =(torch.cuda.memory_allocated(_UpperCAmelCase ) - start_measures[str(_UpperCAmelCase )]) / 2**20 _a : List[Any] =(torch.cuda.max_memory_allocated(_UpperCAmelCase ) - start_measures[str(_UpperCAmelCase )]) / 2**20 return measures def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ,_UpperCAmelCase : Tuple ) -> str: print(F"{description}:" ) print(F"- Time: {measures['time']:.2f}s" ) for i in range(torch.cuda.device_count() ): print(F"- GPU {i} allocated: {measures[str(_UpperCAmelCase )]:.2f}MiB" ) _a : Union[str, Any] =measures[F"{i}-peak"] print(F"- GPU {i} peak: {peak:.2f}MiB" ) print(F"- CPU RAM allocated: {measures['cpu']:.2f}MiB" ) print(F"- CPU RAM peak: {measures['cpu-peak']:.2f}MiB" )
276
'''simple docstring''' from math import isqrt def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ) -> bool: return all(number % divisor != 0 for divisor in range(2 ,isqrt(_UpperCAmelCase ) + 1 ) ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int = 10**6 ) -> int: _a : List[Any] =0 _a : str =1 _a : Optional[Any] =7 while prime_candidate < max_prime: primes_count += is_prime(_UpperCAmelCase ) cube_index += 1 prime_candidate += 6 * cube_index return primes_count if __name__ == "__main__": print(F"{solution() = }")
276
1
'''simple docstring''' import unittest import numpy as np def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : np.ndarray ,_UpperCAmelCase : np.ndarray ,_UpperCAmelCase : np.ndarray ,_UpperCAmelCase : np.ndarray | None = None ,) -> np.ndarray: _a : int =np.shape(_UpperCAmelCase ) _a : Optional[Any] =np.shape(_UpperCAmelCase ) _a : Optional[Any] =np.shape(_UpperCAmelCase ) if shape_a[0] != shape_b[0]: _a : int =( """Expected the same number of rows for A and B. """ F"Instead found A of size {shape_a} and B of size {shape_b}" ) raise ValueError(_UpperCAmelCase ) if shape_b[1] != shape_c[1]: _a : List[Any] =( """Expected the same number of columns for B and C. """ F"Instead found B of size {shape_b} and C of size {shape_c}" ) raise ValueError(_UpperCAmelCase ) _a : Tuple =pseudo_inv if a_inv is None: try: _a : str =np.linalg.inv(_UpperCAmelCase ) except np.linalg.LinAlgError: raise ValueError( """Input matrix A is not invertible. Cannot compute Schur complement.""" ) return mat_c - mat_b.T @ a_inv @ mat_b class A__ ( unittest.TestCase ): def __UpperCAmelCase ( self :Any ) -> None: '''simple docstring''' _a : Tuple =np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) _a : Union[str, Any] =np.array([[0, 3], [3, 0], [2, 3]] ) _a : List[Any] =np.array([[2, 1], [6, 3]] ) _a : int =schur_complement(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) _a : Tuple =np.block([[a, b], [b.T, c]] ) _a : Tuple =np.linalg.det(SCREAMING_SNAKE_CASE ) _a : Dict =np.linalg.det(SCREAMING_SNAKE_CASE ) _a : List[str] =np.linalg.det(SCREAMING_SNAKE_CASE ) self.assertAlmostEqual(SCREAMING_SNAKE_CASE , det_a * det_s ) def __UpperCAmelCase ( self :Union[str, Any] ) -> None: '''simple docstring''' _a : Optional[Any] =np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) _a : Union[str, Any] =np.array([[0, 3], [3, 0], [2, 3]] ) _a : List[str] =np.array([[2, 1], [6, 3]] ) with self.assertRaises(SCREAMING_SNAKE_CASE ): schur_complement(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :str ) -> None: '''simple docstring''' _a : str =np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) _a : int =np.array([[0, 3], [3, 0], [2, 3]] ) _a : Tuple =np.array([[2, 1, 3], [6, 3, 5]] ) with self.assertRaises(SCREAMING_SNAKE_CASE ): schur_complement(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if __name__ == "__main__": import doctest doctest.testmod() unittest.main()
276
'''simple docstring''' # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from ...utils import deprecate from ..controlnet.multicontrolnet import MultiControlNetModel # noqa: F401 from ..controlnet.pipeline_controlnet import StableDiffusionControlNetPipeline # noqa: F401 deprecate( '''stable diffusion controlnet''', '''0.22.0''', '''Importing `StableDiffusionControlNetPipeline` or `MultiControlNetModel` from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import StableDiffusionControlNetPipeline` instead.''', standard_warn=False, stacklevel=3, )
276
1
'''simple docstring''' from math import isqrt def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ) -> bool: return all(number % divisor != 0 for divisor in range(2 ,isqrt(_UpperCAmelCase ) + 1 ) ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int = 10**6 ) -> int: _a : List[Any] =0 _a : str =1 _a : Optional[Any] =7 while prime_candidate < max_prime: primes_count += is_prime(_UpperCAmelCase ) cube_index += 1 prime_candidate += 6 * cube_index return primes_count if __name__ == "__main__": print(F"{solution() = }")
276
'''simple docstring''' import pytest from datasets.utils.sharding import _distribute_shards, _number_of_shards_in_gen_kwargs, _split_gen_kwargs @pytest.mark.parametrize( """kwargs, expected""" ,[ ({"""num_shards""": 0, """max_num_jobs""": 1}, []), ({"""num_shards""": 10, """max_num_jobs""": 1}, [range(10 )]), ({"""num_shards""": 10, """max_num_jobs""": 10}, [range(_UpperCAmelCase ,i + 1 ) for i in range(10 )]), ({"""num_shards""": 1, """max_num_jobs""": 10}, [range(1 )]), ({"""num_shards""": 10, """max_num_jobs""": 3}, [range(0 ,4 ), range(4 ,7 ), range(7 ,10 )]), ({"""num_shards""": 3, """max_num_jobs""": 10}, [range(0 ,1 ), range(1 ,2 ), range(2 ,3 )]), ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : Dict ) -> Optional[Any]: _a : Tuple =_distribute_shards(**_UpperCAmelCase ) assert out == expected @pytest.mark.parametrize( """gen_kwargs, max_num_jobs, expected""" ,[ ({"""foo""": 0}, 10, [{"""foo""": 0}]), ({"""shards""": [0, 1, 2, 3]}, 1, [{"""shards""": [0, 1, 2, 3]}]), ({"""shards""": [0, 1, 2, 3]}, 4, [{"""shards""": [0]}, {"""shards""": [1]}, {"""shards""": [2]}, {"""shards""": [3]}]), ({"""shards""": [0, 1]}, 4, [{"""shards""": [0]}, {"""shards""": [1]}]), ({"""shards""": [0, 1, 2, 3]}, 2, [{"""shards""": [0, 1]}, {"""shards""": [2, 3]}]), ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : List[Any] ,_UpperCAmelCase : Union[str, Any] ) -> List[str]: _a : List[str] =_split_gen_kwargs(_UpperCAmelCase ,_UpperCAmelCase ) assert out == expected @pytest.mark.parametrize( """gen_kwargs, expected""" ,[ ({"""foo""": 0}, 1), ({"""shards""": [0]}, 1), ({"""shards""": [0, 1, 2, 3]}, 4), ({"""shards""": [0, 1, 2, 3], """foo""": 0}, 4), ({"""shards""": [0, 1, 2, 3], """other""": (0, 1)}, 4), ({"""shards""": [0, 1, 2, 3], """shards2""": [0, 1]}, RuntimeError), ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : List[Any] ) -> Union[str, Any]: if expected is RuntimeError: with pytest.raises(_UpperCAmelCase ): _number_of_shards_in_gen_kwargs(_UpperCAmelCase ) else: _a : Dict =_number_of_shards_in_gen_kwargs(_UpperCAmelCase ) assert out == expected
276
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available A__: Optional[Any] = { '''configuration_ctrl''': ['''CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''CTRLConfig'''], '''tokenization_ctrl''': ['''CTRLTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: List[str] = [ '''CTRL_PRETRAINED_MODEL_ARCHIVE_LIST''', '''CTRLForSequenceClassification''', '''CTRLLMHeadModel''', '''CTRLModel''', '''CTRLPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: List[str] = [ '''TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFCTRLForSequenceClassification''', '''TFCTRLLMHeadModel''', '''TFCTRLModel''', '''TFCTRLPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_ctrl import CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRLConfig from .tokenization_ctrl import CTRLTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ctrl import ( CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, CTRLForSequenceClassification, CTRLLMHeadModel, CTRLModel, CTRLPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_ctrl import ( TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, TFCTRLForSequenceClassification, TFCTRLLMHeadModel, TFCTRLModel, TFCTRLPreTrainedModel, ) else: import sys A__: Optional[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
276
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A__: Dict = logging.get_logger(__name__) A__: Tuple = { '''weiweishi/roc-bert-base-zh''': '''https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json''', } class A__ ( UpperCAmelCase__ ): __UpperCamelCase : Tuple = "roc_bert" def __init__( self :Optional[int] , SCREAMING_SNAKE_CASE :Tuple=3_0_5_2_2 , SCREAMING_SNAKE_CASE :List[str]=7_6_8 , SCREAMING_SNAKE_CASE :Dict=1_2 , SCREAMING_SNAKE_CASE :List[str]=1_2 , SCREAMING_SNAKE_CASE :Tuple=3_0_7_2 , SCREAMING_SNAKE_CASE :List[Any]="gelu" , SCREAMING_SNAKE_CASE :Union[str, Any]=0.1 , SCREAMING_SNAKE_CASE :List[Any]=0.1 , SCREAMING_SNAKE_CASE :int=5_1_2 , SCREAMING_SNAKE_CASE :Optional[Any]=2 , SCREAMING_SNAKE_CASE :Union[str, Any]=0.02 , SCREAMING_SNAKE_CASE :Optional[Any]=1e-12 , SCREAMING_SNAKE_CASE :Any=True , SCREAMING_SNAKE_CASE :List[Any]=0 , SCREAMING_SNAKE_CASE :Optional[int]="absolute" , SCREAMING_SNAKE_CASE :Union[str, Any]=None , SCREAMING_SNAKE_CASE :List[Any]=True , SCREAMING_SNAKE_CASE :int=True , SCREAMING_SNAKE_CASE :Optional[int]=7_6_8 , SCREAMING_SNAKE_CASE :Optional[Any]=9_1_0 , SCREAMING_SNAKE_CASE :Union[str, Any]=5_1_2 , SCREAMING_SNAKE_CASE :str=2_4_8_5_8 , SCREAMING_SNAKE_CASE :List[Any]=True , **SCREAMING_SNAKE_CASE :Tuple , ) -> Optional[int]: '''simple docstring''' _a : List[str] =vocab_size _a : List[str] =max_position_embeddings _a : Optional[Any] =hidden_size _a : List[Any] =num_hidden_layers _a : List[str] =num_attention_heads _a : int =intermediate_size _a : Any =hidden_act _a : Dict =hidden_dropout_prob _a : int =attention_probs_dropout_prob _a : str =initializer_range _a : Optional[int] =type_vocab_size _a : Any =layer_norm_eps _a : Any =use_cache _a : Optional[int] =enable_pronunciation _a : Optional[Any] =enable_shape _a : Optional[Any] =pronunciation_embed_dim _a : Tuple =pronunciation_vocab_size _a : Union[str, Any] =shape_embed_dim _a : Any =shape_vocab_size _a : Tuple =concat_input _a : List[str] =position_embedding_type _a : List[str] =classifier_dropout super().__init__(pad_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE )
276
1
'''simple docstring''' from argparse import ArgumentParser, Namespace from ..utils import logging from . import BaseTransformersCLICommand def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Namespace ) -> Union[str, Any]: return ConvertCommand( args.model_type ,args.tf_checkpoint ,args.pytorch_dump_output ,args.config ,args.finetuning_task_name ) A__: str = ''' transformers can only be used from the commandline to convert TensorFlow models in PyTorch, In that case, it requires TensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installation instructions. ''' class A__ ( UpperCAmelCase__ ): @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :ArgumentParser ) -> int: '''simple docstring''' _a : Optional[int] =parser.add_parser( """convert""" , help="""CLI tool to run convert model from original author checkpoints to Transformers PyTorch checkpoints.""" , ) train_parser.add_argument("""--model_type""" , type=SCREAMING_SNAKE_CASE , required=SCREAMING_SNAKE_CASE , help="""Model's type.""" ) train_parser.add_argument( """--tf_checkpoint""" , type=SCREAMING_SNAKE_CASE , required=SCREAMING_SNAKE_CASE , help="""TensorFlow checkpoint path or folder.""" ) train_parser.add_argument( """--pytorch_dump_output""" , type=SCREAMING_SNAKE_CASE , required=SCREAMING_SNAKE_CASE , help="""Path to the PyTorch saved model output.""" ) train_parser.add_argument("""--config""" , type=SCREAMING_SNAKE_CASE , default="""""" , help="""Configuration file path or folder.""" ) train_parser.add_argument( """--finetuning_task_name""" , type=SCREAMING_SNAKE_CASE , default=SCREAMING_SNAKE_CASE , help="""Optional fine-tuning task name if the TF model was a finetuned model.""" , ) train_parser.set_defaults(func=SCREAMING_SNAKE_CASE ) def __init__( self :Dict , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :str , *SCREAMING_SNAKE_CASE :str , ) -> List[str]: '''simple docstring''' _a : str =logging.get_logger("""transformers-cli/converting""" ) self._logger.info(f"Loading model {model_type}" ) _a : Optional[int] =model_type _a : Any =tf_checkpoint _a : Tuple =pytorch_dump_output _a : int =config _a : Any =finetuning_task_name def __UpperCAmelCase ( self :Dict ) -> List[Any]: '''simple docstring''' if self._model_type == "albert": try: from ..models.albert.convert_albert_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(SCREAMING_SNAKE_CASE ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "bert": try: from ..models.bert.convert_bert_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(SCREAMING_SNAKE_CASE ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "funnel": try: from ..models.funnel.convert_funnel_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(SCREAMING_SNAKE_CASE ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "t5": try: from ..models.ta.convert_ta_original_tf_checkpoint_to_pytorch import convert_tf_checkpoint_to_pytorch except ImportError: raise ImportError(SCREAMING_SNAKE_CASE ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "gpt": from ..models.openai.convert_openai_original_tf_checkpoint_to_pytorch import ( convert_openai_checkpoint_to_pytorch, ) convert_openai_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "transfo_xl": try: from ..models.transfo_xl.convert_transfo_xl_original_tf_checkpoint_to_pytorch import ( convert_transfo_xl_checkpoint_to_pytorch, ) except ImportError: raise ImportError(SCREAMING_SNAKE_CASE ) if "ckpt" in self._tf_checkpoint.lower(): _a : Dict =self._tf_checkpoint _a : Union[str, Any] ="""""" else: _a : Any =self._tf_checkpoint _a : Union[str, Any] ="""""" convert_transfo_xl_checkpoint_to_pytorch( SCREAMING_SNAKE_CASE , self._config , self._pytorch_dump_output , SCREAMING_SNAKE_CASE ) elif self._model_type == "gpt2": try: from ..models.gpta.convert_gpta_original_tf_checkpoint_to_pytorch import ( convert_gpta_checkpoint_to_pytorch, ) except ImportError: raise ImportError(SCREAMING_SNAKE_CASE ) convert_gpta_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "xlnet": try: from ..models.xlnet.convert_xlnet_original_tf_checkpoint_to_pytorch import ( convert_xlnet_checkpoint_to_pytorch, ) except ImportError: raise ImportError(SCREAMING_SNAKE_CASE ) convert_xlnet_checkpoint_to_pytorch( self._tf_checkpoint , self._config , self._pytorch_dump_output , self._finetuning_task_name ) elif self._model_type == "xlm": from ..models.xlm.convert_xlm_original_pytorch_checkpoint_to_pytorch import ( convert_xlm_checkpoint_to_pytorch, ) convert_xlm_checkpoint_to_pytorch(self._tf_checkpoint , self._pytorch_dump_output ) elif self._model_type == "lxmert": from ..models.lxmert.convert_lxmert_original_tf_checkpoint_to_pytorch import ( convert_lxmert_checkpoint_to_pytorch, ) convert_lxmert_checkpoint_to_pytorch(self._tf_checkpoint , self._pytorch_dump_output ) elif self._model_type == "rembert": from ..models.rembert.convert_rembert_tf_checkpoint_to_pytorch import ( convert_rembert_tf_checkpoint_to_pytorch, ) convert_rembert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) else: raise ValueError( """--model_type should be selected in the list [bert, gpt, gpt2, t5, transfo_xl, xlnet, xlm, lxmert]""" )
276
'''simple docstring''' class A__ : def __init__( self :List[str] ) -> List[Any]: '''simple docstring''' _a : Tuple =0 _a : Any =0 _a : int ={} def __UpperCAmelCase ( self :Any , SCREAMING_SNAKE_CASE :List[str] ) -> Optional[int]: '''simple docstring''' if vertex not in self.adjacency: _a : Dict ={} self.num_vertices += 1 def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Any ) -> List[str]: '''simple docstring''' self.add_vertex(SCREAMING_SNAKE_CASE ) self.add_vertex(SCREAMING_SNAKE_CASE ) if head == tail: return _a : Any =weight _a : Tuple =weight def __UpperCAmelCase ( self :Dict ) -> Optional[int]: '''simple docstring''' _a : Union[str, Any] =self.get_edges() for edge in edges: _a , _a , _a : List[str] =edge edges.remove((tail, head, weight) ) for i in range(len(SCREAMING_SNAKE_CASE ) ): _a : str =list(edges[i] ) edges.sort(key=lambda SCREAMING_SNAKE_CASE : e[2] ) for i in range(len(SCREAMING_SNAKE_CASE ) - 1 ): if edges[i][2] >= edges[i + 1][2]: _a : Union[str, Any] =edges[i][2] + 1 for edge in edges: _a , _a , _a : Tuple =edge _a : Tuple =weight _a : List[Any] =weight def __str__( self :int ) -> str: '''simple docstring''' _a : int ="""""" for tail in self.adjacency: for head in self.adjacency[tail]: _a : str =self.adjacency[head][tail] string += f"{head} -> {tail} == {weight}\n" return string.rstrip("""\n""" ) def __UpperCAmelCase ( self :Optional[int] ) -> Optional[Any]: '''simple docstring''' _a : Union[str, Any] =[] for tail in self.adjacency: for head in self.adjacency[tail]: output.append((tail, head, self.adjacency[head][tail]) ) return output def __UpperCAmelCase ( self :List[Any] ) -> List[Any]: '''simple docstring''' return self.adjacency.keys() @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :Dict=None , SCREAMING_SNAKE_CASE :List[Any]=None ) -> Optional[int]: '''simple docstring''' _a : str =Graph() if vertices is None: _a : Union[str, Any] =[] if edges is None: _a : List[Any] =[] for vertex in vertices: g.add_vertex(SCREAMING_SNAKE_CASE ) for edge in edges: g.add_edge(*SCREAMING_SNAKE_CASE ) return g class A__ : def __init__( self :Optional[int] ) -> Union[str, Any]: '''simple docstring''' _a : Optional[int] ={} _a : List[str] ={} def __len__( self :List[Any] ) -> List[Any]: '''simple docstring''' return len(self.parent ) def __UpperCAmelCase ( self :Tuple , SCREAMING_SNAKE_CASE :Tuple ) -> Dict: '''simple docstring''' if item in self.parent: return self.find(SCREAMING_SNAKE_CASE ) _a : Optional[Any] =item _a : List[str] =0 return item def __UpperCAmelCase ( self :int , SCREAMING_SNAKE_CASE :Dict ) -> List[str]: '''simple docstring''' if item not in self.parent: return self.make_set(SCREAMING_SNAKE_CASE ) if item != self.parent[item]: _a : str =self.find(self.parent[item] ) return self.parent[item] def __UpperCAmelCase ( self :Optional[int] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :List[Any] ) -> Optional[Any]: '''simple docstring''' _a : Optional[int] =self.find(SCREAMING_SNAKE_CASE ) _a : Dict =self.find(SCREAMING_SNAKE_CASE ) if roota == roota: return roota if self.rank[roota] > self.rank[roota]: _a : Any =roota return roota if self.rank[roota] < self.rank[roota]: _a : List[str] =roota return roota if self.rank[roota] == self.rank[roota]: self.rank[roota] += 1 _a : List[Any] =roota return roota return None @staticmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :Dict ) -> Union[str, Any]: '''simple docstring''' _a : Any =graph.num_vertices _a : Union[str, Any] =Graph.UnionFind() _a : Optional[int] =[] while num_components > 1: _a : str ={} for vertex in graph.get_vertices(): _a : List[str] =-1 _a : Any =graph.get_edges() for edge in edges: _a , _a , _a : Tuple =edge edges.remove((tail, head, weight) ) for edge in edges: _a , _a , _a : Any =edge _a : Any =union_find.find(SCREAMING_SNAKE_CASE ) _a : List[Any] =union_find.find(SCREAMING_SNAKE_CASE ) if seta != seta: if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight: _a : Optional[int] =[head, tail, weight] if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight: _a : List[Any] =[head, tail, weight] for vertex in cheap_edge: if cheap_edge[vertex] != -1: _a , _a , _a : Optional[Any] =cheap_edge[vertex] if union_find.find(SCREAMING_SNAKE_CASE ) != union_find.find(SCREAMING_SNAKE_CASE ): union_find.union(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) mst_edges.append(cheap_edge[vertex] ) _a : str =num_components - 1 _a : str =Graph.build(edges=SCREAMING_SNAKE_CASE ) return mst
276
1
'''simple docstring''' from __future__ import annotations def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ) -> list[int]: _a : Optional[Any] =2 _a : List[str] =[] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(_UpperCAmelCase ) if n > 1: factors.append(_UpperCAmelCase ) return factors if __name__ == "__main__": import doctest doctest.testmod()
276
'''simple docstring''' from datetime import datetime import requests from bsa import BeautifulSoup if __name__ == "__main__": A__: Union[str, Any] = input('''Enter image url: ''').strip() print(F"Downloading image from {url} ...") A__: Tuple = BeautifulSoup(requests.get(url).content, '''html.parser''') # The image URL is in the content field of the first meta tag with property og:image A__: Union[str, Any] = soup.find('''meta''', {'''property''': '''og:image'''})['''content'''] A__: List[Any] = requests.get(image_url).content A__: List[str] = F"{datetime.now():%Y-%m-%d_%H:%M:%S}.jpg" with open(file_name, '''wb''') as fp: fp.write(image_data) print(F"Done. Image saved to disk as {file_name}.")
276
1